Archilyzer · Source

archilyzer

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

commit 408664737b03e4abf81e8545f3b69a95598e39c0
parent 7de532cee1d3bedcb5bff0cf314e8ff9539fe8be
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:25:48 -0500

umtool: an ingredient's nine stages, read from the files that exist (lib/ingredients/stages.mjs, lane L5)

Found (find-clips.json, research marks, case candidates), Downloaded (metadata.info.json's HEAD only,
the outcome, availability and history sidecars, the saved video, the media files and their links),
Transcribed (transcript.cues.json's head and tail -- never the cues), Clock (clock.json), Windows (clips/
and their sidecars, cross-checked against the usage index: a draft clip no window holds, a window asked
for a clip no project uses), Used in (the usage index), Checked (quote-check.json rows, rowIsCurrent),
Rendered (each version's render.json, the segments' cut records), Published (out/links.json, the archive
moment). Each answers a pill (ok, a count, warn, none) and a line; ?window= narrows the stages after
Windows to the clips that window plays. Read-only over the corpus: the test lists the channels tree
before and after. heads.mjs reads a big JSON file by its ends. The usage index keeps each Rumble/Twitch
id's directory, so a warm read is 0.4 s on the real tree (19 s re-resolving embed ids before).

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

Diffstat:
Aumtool/lib/ingredients/heads.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/stages.mjs | 559+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/stages.test.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/ingredients/usedIn.mjs | 32+++++++++++++++++++++++++++-----
4 files changed, 890 insertions(+), 5 deletions(-)

diff --git a/umtool/lib/ingredients/heads.mjs b/umtool/lib/ingredients/heads.mjs @@ -0,0 +1,152 @@ +// READING A BIG JSON FILE BY ITS ENDS (lane L5). `metadata.info.json` runs to +// 600 KB+ (yt-dlp's formats), `transcript.cues.json` to megabytes; the +// ingredient page needs a handful of top-level fields of each, and how far the +// last cue reaches. So a file is read by its HEAD (the first bytes, scanned as +// the top-level object's members until the buffer ends or a named key is met) +// and its TAIL (the last bytes, searched for the last `"end"`), never whole. +// +// Plain ESM; the CLI runs it under bare node. +import { open } from "node:fs/promises"; + +export const HEAD_BYTES = 64 * 1024; +export const TAIL_BYTES = 4 * 1024; + +async function readRange(file, start, length) { + let fh; + try { + fh = await open(file, "r"); + const st = await fh.stat(); + const from = start < 0 ? Math.max(0, st.size + start) : start; + const n = Math.max(0, Math.min(length, st.size - from)); + const buf = Buffer.alloc(n); + const { bytesRead } = await fh.read(buf, 0, n, from); + return { text: buf.subarray(0, bytesRead).toString("utf8"), size: st.size }; + } catch { + return null; + } finally { + await fh?.close().catch(() => {}); + } +} + +/** + * The top-level PRIMITIVE members of a JSON object, from the start of its text + * (a truncated text is fine: what was complete is returned). An object or + * array member is skipped (its key is listed in `nested`); scanning stops at + * `stopKey`. + * @param {string} text + * @param {{ stopKey?: string | null }} [o] + * @returns {{ fields: Record<string, string | number | boolean | null>, nested: string[], complete: boolean }} + */ +export function scanHead(text, { stopKey = null } = {}) { + const fields = {}; + const nested = []; + let i = 0; + const n = text.length; + const ws = () => { + while (i < n && /\s/.test(text[i])) i += 1; + }; + const str = () => { + // at a quote; returns the decoded string, or null when it runs off the end + const s = i; + i += 1; + while (i < n) { + const c = text[i]; + if (c === "\\") i += 2; + else if (c === '"') { + i += 1; + try { + return JSON.parse(text.slice(s, i)); + } catch { + return null; + } + } else i += 1; + } + return null; + }; + const skipNested = () => { + let depth = 0; + while (i < n) { + const c = text[i]; + if (c === '"') { + if (str() === null) return false; + continue; + } + if (c === "{" || c === "[") depth += 1; + else if (c === "}" || c === "]") { + depth -= 1; + if (depth === 0) { + i += 1; + return true; + } + } + i += 1; + } + return false; + }; + ws(); + if (text[i] !== "{") return { fields, nested, complete: false }; + i += 1; + for (;;) { + ws(); + if (i >= n) return { fields, nested, complete: false }; + if (text[i] === "}") return { fields, nested, complete: true }; + if (text[i] === ",") { + i += 1; + continue; + } + if (text[i] !== '"') return { fields, nested, complete: false }; + const key = str(); + if (key === null) return { fields, nested, complete: false }; + ws(); + if (text[i] !== ":") return { fields, nested, complete: false }; + i += 1; + ws(); + if (stopKey && key === stopKey) return { fields, nested: [...nested, key], complete: false }; + const c = text[i]; + if (c === '"') { + const v = str(); + if (v === null) return { fields, nested, complete: false }; + fields[key] = v; + } else if (c === "{" || c === "[") { + nested.push(key); + if (!skipNested()) return { fields, nested, complete: false }; + } else { + const m = /^(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i, i + 40)); + if (!m) return { fields, nested, complete: false }; + // A number at the very end of a truncated text may be cut short: only a terminated one counts. + if (i + m[0].length >= n) return { fields, nested, complete: false }; + fields[key] = JSON.parse(m[0]); + i += m[0].length; + } + } +} + +/** + * A JSON file's head: its top-level primitive members (scanHead), and its size. + * @param {string} file + * @param {{ bytes?: number, stopKey?: string | null }} [o] + * @returns {Promise<{ fields: Record<string, any>, nested: string[], size: number } | null>} + */ +export async function readJsonHead(file, { bytes = HEAD_BYTES, stopKey = null } = {}) { + const r = await readRange(file, 0, bytes); + if (!r) return null; + const { fields, nested } = scanHead(r.text, { stopKey }); + return { fields, nested, size: r.size }; +} + +/** + * The largest `"end": <seconds>` in a file's last bytes: how far a cue file's + * last cue reaches, without reading the cues. + * @param {string} file + * @returns {Promise<number | null>} + */ +export async function lastEndOf(file, { bytes = TAIL_BYTES } = {}) { + const r = await readRange(file, -bytes, bytes); + if (!r) return null; + let best = null; + for (const m of r.text.matchAll(/"end"\s*:\s*(-?\d+(?:\.\d+)?)/g)) { + const v = Number(m[1]); + if (Number.isFinite(v) && (best === null || v > best)) best = v; + } + return best; +} diff --git a/umtool/lib/ingredients/stages.mjs b/umtool/lib/ingredients/stages.mjs @@ -0,0 +1,559 @@ +// ONE INGREDIENT'S WHOLE LIFE CYCLE (umtool redesign, lane L5; operator, 9 Nov 2026: "the stage rail could be +// good for viewing a downloaded clip or other video ingredient to see its entire life cycle"). +// +// An ingredient is one recording of the corpus, `channels/<ch>/data/<id>/`, and optionally one clip window of +// it (`?window=<from>-<to>`). Nine stages, each read from files that already exist: +// +// found data/<id>/find-clips.json; research sessions' marks["ch/id"]; research cases' candidates.jsonl +// downloaded metadata.info.json (its HEAD only), metadata.history.json, download-outcome.json, +// availability.json, saved-video.json, media-import.json, the media files and their links +// transcribed transcript.cues.json (its head and its tail, never the cues), the .vtt files, +// transcript-pin.json, transcribe-outcome.json, words.json (stat only) +// clock clock.json (recordingClock-read.mjs, describeClock) +// windows clips/<from>-<to>.{mp4,…} and their sidecars, cross-checked against the usage index +// used the usage index (usedIn.mjs): every project clip that cuts from it, draft and versions +// checked <project>/quote-check.json rows for those clips (rowIsCurrent) +// rendered <project>/takes/<id>/render.json for the versions holding them, out/segments/<clip>.cut.json +// published <project>/out/links.json for those clips (linkVerdicts' rows), the archive moment +// +// READ-ONLY OVER THE CORPUS, no exceptions: nothing here writes under the channels dir (the usage index lives +// in umtool's own state dir). Each stage answers a PILL -- `ok` (✓), `count` (a number), `warn` (!) or `none` +// (—) -- and a one-line summary; its panel reads the rest of the stage's object. +// +// Plain ESM: `umtool ingredient` prints it under bare node; the page renders it. +import { lstat, readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { describeClock } from "yt-dlp-transcript-common/lib/recordingClock.mjs"; +import { readRecordingClock } from "yt-dlp-transcript-common/lib/recordingClock-read.mjs"; +import { audioFilesOf, present, readSavedVideoPointer, WIN_EPS } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; +import { readChannelPlatform, recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { archiveMomentUrl } from "umtool-report-to-video/site-links"; +import { readLog } from "../research/log.mjs"; +import { readQuoteCheck, rowIsCurrent } from "../report/quoteCheck.mjs"; +import { readRenderRecord } from "../report/renderRecord.mjs"; +import { readLinkCheck } from "../report/linkCheck.mjs"; +import { lastEndOf, readJsonHead } from "./heads.mjs"; +import { loadUsageIndex, overlaps, playedOf, rowsInWindow, usesOf } from "./usedIn.mjs"; + +export const STAGES = [ + { key: "found", label: "Found" }, + { key: "downloaded", label: "Downloaded" }, + { key: "transcribed", label: "Transcribed" }, + { key: "clock", label: "Clock" }, + { key: "windows", label: "Windows" }, + { key: "used", label: "Used in" }, + { key: "checked", label: "Checked" }, + { key: "rendered", label: "Rendered" }, + { key: "published", label: "Published" }, +]; + +const ID_RE = /^[\w.-]{1,128}$/; +const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +export const isChannelSlug = (v) => typeof v === "string" && SLUG_RE.test(v) && !v.includes(".."); +export const isVideoId = (v) => typeof v === "string" && ID_RE.test(v) && v !== "." && v !== ".."; + +const WINDOW_NAME = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)(\.desynced)?\.(mp4|mkv|webm)$/i; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const round2 = (x) => Math.round(Number(x) * 100) / 100; + +/** `?window=<from>-<to>` -> {from, to}, or null. */ +export function parseWindowParam(v) { + const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(v ?? "").trim()); + if (!m) return null; + const from = Number(m[1]); + const to = Number(m[2]); + return to > from ? { from, to } : null; +} + +/** The window's own name, `<from>-<to>` with two decimals (clipWindow.ts clipWindowName). */ +export const windowName = (from, to) => `${Number(from).toFixed(2)}-${Number(to).toFixed(2)}`; + +const pill = (kind, n = null) => ({ kind, ...(n !== null ? { n } : {}) }); + +async function readJson(file) { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +} +const statOf = (p) => stat(p).catch(() => null); +const lstatOf = (p) => lstat(p).catch(() => null); +const hms = (sec) => { + const t = Math.max(0, Math.floor(Number(sec) || 0)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const s = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`; +}; +export const spanText = (from, to) => (fin(from) && fin(to) ? `${hms(from)}–${hms(to)}` : "?"); + +/** + * A file in the video dir: is it there, a link (the media tier), and does it resolve? + * @param {string} dir + * @param {string} name + */ +async function fileState(dir, name) { + const p = path.join(dir, name); + const l = await lstatOf(p); + if (!l) return null; + const link = l.isSymbolicLink(); + const s = link ? await statOf(p) : l; + return { name, link, reachable: !!s, bytes: s?.size ?? null }; +} + +// ── identity ───────────────────────────────────────────────────────────────── + +/** + * Who the ingredient is: the directory it lives in (either Rumble id finds it), the archive's id for it, the + * channel's platform and the guards' facts about the channel's media (moving, a drive not answering). + */ +export async function ingredientIdentity({ channelsDir, ch, id }) { + const platform = await readChannelPlatform(channelsDir, ch); + const dirId = await resolveVideoDirId(channelsDir, ch, id, { platform }).catch(() => id); + const siteId = await recordIdOfVideoDir(channelsDir, ch, dirId, { platform }).catch(() => dirId); + const channelDir = path.join(channelsDir, ch); + const dir = path.join(channelDir, "data", dirId); + const exists = !!(await statOf(dir))?.isDirectory(); + const channelExists = !!(await statOf(channelDir))?.isDirectory(); + const notes = []; + if (await statOf(path.join(channelDir, ".relocating.json"))) notes.push("the channel's media is being moved (.relocating.json): its big files may not answer until the move ends"); + const dataL = await lstatOf(path.join(channelDir, "data")); + if (dataL?.isSymbolicLink() && !(await statOf(path.join(channelDir, "data")))) notes.push("the channel's data/ is a link to a drive that is not mounted: an unmounted drive is not an empty channel"); + const mediaL = await lstatOf(path.join(channelDir, "media")); + const mediaDrive = mediaL?.isSymbolicLink() ? ((await statOf(path.join(channelDir, "media"))) ? "linked" : "missing") : mediaL ? "local" : "none"; + if (mediaDrive === "missing") notes.push("the channel's media/ links to a drive that is not answering: its media files read as missing, not as never downloaded"); + return { ch, asked: id, dirId, siteId: siteId !== dirId ? siteId : null, platform, dir, exists, channelExists, mediaDrive, notes }; +} + +// ── found ──────────────────────────────────────────────────────────────────── + +async function foundStage({ reportsRoot, idn }) { + const keys = new Set([`${idn.ch}/${idn.dirId}`, ...(idn.siteId ? [`${idn.ch}/${idn.siteId}`] : []), `${idn.ch}/${idn.asked}`]); + const ids = new Set([idn.dirId, idn.asked, ...(idn.siteId ? [idn.siteId] : [])]); + const fc = idn.exists ? await readJson(path.join(idn.dir, "find-clips.json")) : null; + const findClips = + fc && fc.version === 1 && typeof fc.project === "string" + ? { at: fc.at ?? null, project: fc.project, url: typeof fc.url === "string" ? fc.url : null, segments: Array.isArray(fc.segments) ? fc.segments.length : 0, segment: fc.segment ?? null, created: fc.created === true } + : null; + const research = path.join(reportsRoot, ".umtool", "research"); + const marks = []; + for (const name of await readdir(path.join(research, "sessions")).catch(() => [])) { + if (!name.endsWith(".json")) continue; + const session = name.slice(0, -5); + const log = await readLog(reportsRoot, session); + for (const k of keys) { + const m = log.marks?.[k]; + if (m) { + marks.push({ session, query: log.query ?? null, state: m.state, at: m.at || null }); + break; + } + } + } + const candidates = []; + for (const c of await readdir(research, { withFileTypes: true }).catch(() => [])) { + if (!c.isDirectory() || c.name.startsWith(".") || c.name === "sessions") continue; + const text = await readFile(path.join(research, c.name, "candidates.jsonl"), "utf8").catch(() => ""); + if (!text) continue; + for (const line of text.split("\n")) { + if (!line || ![...ids].some((x) => line.includes(`"${x}"`))) continue; + let w; + try { + w = JSON.parse(line); + } catch { + continue; + } + if (w?.slug !== idn.ch || !ids.has(String(w.id))) continue; + candidates.push({ case: c.name, key: w.key ?? null, from: w.from ?? null, to: w.to ?? null, title: w.title ?? null, hits: Array.isArray(w.hits) ? w.hits.length : 0 }); + if (candidates.length >= 200) break; + } + } + const n = (findClips ? 1 : 0) + marks.length + candidates.length; + const parts = [findClips && `the clip finder (${findClips.project})`, marks.length && `${marks.length} research mark${marks.length === 1 ? "" : "s"}`, candidates.length && `${candidates.length} case window${candidates.length === 1 ? "" : "s"}`].filter(Boolean); + return { + key: "found", + label: "Found", + pill: n ? pill("count", n) : pill("none"), + line: n ? `Found by ${parts.join(", ")}` : "Not found by a search, a case or the clip finder (it came in some other way)", + findClips, + marks, + candidates, + }; +} + +// ── downloaded ─────────────────────────────────────────────────────────────── + +const AVAILABLE = new Set(["public", "unlisted"]); + +async function downloadedStage({ idn }) { + if (!idn.exists) { + return { key: "downloaded", label: "Downloaded", pill: pill("none"), line: idn.channelExists ? `Not in the corpus: no ${idn.ch}/data/${idn.dirId}/` : `No channel ${idn.ch} in the corpus`, meta: null, media: [] }; + } + const dir = idn.dir; + const head = await readJsonHead(path.join(dir, "metadata.info.json")); + const meta = head + ? { + bytes: head.size, + id: head.fields.id ?? null, + title: head.fields.title ?? null, + webpageUrl: head.fields.webpage_url ?? null, + uploadDate: head.fields.upload_date ?? null, + extractor: head.fields.extractor_key ?? head.fields.extractor ?? null, + } + : null; + const hist = await readJson(path.join(dir, "metadata.history.json")); + const histEntries = Array.isArray(hist?.entries) ? hist.entries : []; + const history = histEntries.length ? { count: histEntries.length, lastAt: histEntries[histEntries.length - 1]?.at ?? null, lastBy: histEntries[histEntries.length - 1]?.by ?? null } : null; + const oc = await readJson(path.join(dir, "download-outcome.json")); + const outcome = oc ? { status: String(oc.status ?? "unknown"), finishedAt: oc.finishedAt ?? null, attempts: Array.isArray(oc.attempts) ? oc.attempts.length : 0, webpageUrl: oc.webpageUrl ?? null, error: oc.error ?? oc.message ?? null } : null; + const av = await readJson(path.join(dir, "availability.json")); + const availability = av ? { availability: String(av.availability ?? "unknown"), checkedAt: av.checkedAt ?? null } : null; + const pointer = await readSavedVideoPointer(dir); + const saved = pointer ? { file: pointer.file, height: pointer.height ?? null, reachable: await present(pointer.path) } : null; + const mi = await readJson(path.join(dir, "media-import.json")); + const miEntries = Array.isArray(mi) ? mi : Array.isArray(mi?.entries) ? mi.entries : []; + const imported = miEntries.length ? { count: miEntries.length, lastAt: miEntries[miEntries.length - 1]?.at ?? null, via: miEntries[miEntries.length - 1]?.via ?? null } : null; + const names = await readdir(dir).catch(() => []); + const mediaNames = [...(await audioFilesOf(dir)).map((a) => a.name), ...names.filter((n) => /^source-media\.(mp4|webm|mkv|mov|m4v)$/i.test(n))]; + const media = []; + for (const n of [...new Set(mediaNames)]) { + const f = await fileState(dir, n); + if (f) media.push(f); + } + const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + const problems = []; + if (outcome && !outcome.status.startsWith("ok")) problems.push(`the last download ended ${outcome.status}`); + if (availability && !AVAILABLE.has(availability.availability)) problems.push(`the recording reads ${availability.availability} (checked ${availability.checkedAt ?? "?"})`); + if (media.some((m) => m.link && !m.reachable)) problems.push("a media link does not resolve (its drive is not answering)"); + if (saved && !saved.reachable) problems.push("the saved video's file does not answer"); + const have = [meta && "metadata", vtts.length && "captions", media.length && `${media.length} media file${media.length === 1 ? "" : "s"}`, saved && `the saved video${saved.height ? ` (${saved.height}p)` : ""}`].filter(Boolean); + return { + key: "downloaded", + label: "Downloaded", + pill: problems.length ? pill("warn") : have.length ? pill("ok") : pill("none"), + line: problems.length ? problems.join("; ") : have.length ? `${have.join(", ")} on disk` : "Nothing downloaded yet", + meta, + history, + outcome, + availability, + saved, + imported, + media, + captions: vtts, + problems, + }; +} + +// ── transcribed ────────────────────────────────────────────────────────────── + +async function transcribedStage({ idn }) { + if (!idn.exists) return { key: "transcribed", label: "Transcribed", pill: pill("none"), line: "No recording to transcribe", cues: null }; + const dir = idn.dir; + const cueFile = path.join(dir, "transcript.cues.json"); + const head = await readJsonHead(cueFile, { stopKey: "cues" }); + const lastEnd = head ? await lastEndOf(cueFile) : null; + const f = head?.fields ?? {}; + const duration = fin(f.duration) && f.duration > 0 ? f.duration : null; + const cues = head + ? { + bytes: head.size, + source: f.source ?? null, + format: f.transcriptFormat ?? null, + vttFile: f.vttFile ?? null, + engine: f.engine ?? f.model ?? f.app ?? null, + platform: f.platform ?? null, + title: f.title ?? null, + uploadDate: f.uploadDate ?? null, + duration, + lastEnd, + coverage: duration && fin(lastEnd) ? Math.min(1, lastEnd / duration) : null, + } + : null; + const pin = await readJson(path.join(dir, "transcript-pin.json")); + const to = await readJson(path.join(dir, "transcribe-outcome.json")); + // transcribe-outcome.json is written when a transcript is FINALIZED (transcribeOutcome.ts): who made it, when, a salvage. + const outcome = to && typeof to === "object" ? { at: to.transcribedAt ?? null, worker: to.worker?.appId ?? to.worker?.id ?? null, durationMs: fin(to.durationMs) ? to.durationMs : null, salvaged: !!to.salvaged } : null; + const words = await statOf(path.join(dir, "words.json")); + const names = await readdir(dir).catch(() => []); + const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + const line = cues + ? `${cues.source ?? "cues"}${cues.engine ?? outcome?.worker ? ` (${cues.engine ?? outcome?.worker})` : ""}${cues.coverage !== null ? `, ${Math.round(cues.coverage * 100)}% of ${hms(cues.duration)}` : ""}${outcome?.salvaged ? ", SALVAGED (gaps)" : ""}${words ? ", timed words" : ""}${pin ? ", pinned" : ""}` + : vtts.length + ? `${vtts.length} caption file${vtts.length === 1 ? "" : "s"}, no cues built` + : "Not transcribed"; + return { + key: "transcribed", + label: "Transcribed", + pill: cues ? ((cues.coverage !== null && cues.coverage < 0.5) || outcome?.salvaged ? pill("warn") : pill("ok")) : pill("none"), + line, + cues, + pin: pin ? { ...(typeof pin === "object" ? pin : {}) } : null, + outcome, + words: words ? { bytes: words.size } : null, + captions: vtts, + }; +} + +// ── clock ──────────────────────────────────────────────────────────────────── + +async function clockStage({ idn }) { + const clock = idn.exists ? await readRecordingClock(idn.dir) : null; + if (!clock) return { key: "clock", label: "Clock", pill: pill("none"), line: "No time map (clock.json): one is made when a window is cut from a saved recording", clock: null }; + const steps = (clock.gaps ?? []).length; + return { + key: "clock", + label: "Clock", + pill: clock.ok && !steps ? pill("ok") : pill("warn"), + line: describeClock(clock), + clock: { id: clock.id, ok: clock.ok, source: clock.source?.file ?? null, target: clock.target?.file ?? null, segments: (clock.segments ?? []).length, steps, residualMs: fin(clock.residual?.rms) ? round2(clock.residual.rms * 1000) : null, measuredAt: clock.measuredAt ?? clock.at ?? null }, + }; +} + +// ── windows ────────────────────────────────────────────────────────────────── + +/** + * Every clip window of the video dir, oldest-start first, each with its sidecar's provenance and the usage + * rows it can cut (its span holds the row's played span whole) -- the cross-check: a window asked for a clip + * no project uses now, and a draft clip no window holds. + */ +export async function listWindows(dir) { + const clips = path.join(dir, "clips"); + const out = []; + for (const name of await readdir(clips).catch(() => [])) { + const m = WINDOW_NAME.exec(name); + if (!m) continue; + const from = Number(m[1]); + const to = Number(m[2]); + if (!(to > from)) continue; + const desynced = !!m[3]; + const st = await statOf(path.join(clips, name)); + if (!st?.isFile()) continue; + const side = await readJson(path.join(clips, `${m[1]}-${m[2]}${desynced ? ".desynced" : ""}.json`)); + out.push({ + name: `${m[1]}-${m[2]}`, + file: name, + from, + to, + bytes: st.size, + mtime: new Date(st.mtimeMs).toISOString(), + desynced, + sidecar: side && typeof side === "object" + ? { + requestedBy: side.requestedBy ?? null, + manifest: side.manifest ?? null, + clipId: side.clipId ?? null, + reason: side.reason ?? null, + fetchedAt: side.fetchedAt ?? null, + source: side.source ?? null, + syncOk: side.sync && typeof side.sync === "object" ? side.sync.ok === true : null, + clock: side.clock && typeof side.clock === "object" ? { id: side.clock.id ?? null, offset: side.clock.offset ?? null, certain: side.clock.certain === true } : null, + } + : null, + }); + } + out.sort((a, b) => a.from - b.from || a.to - b.to); + return out; +} + +const holds = (w, s) => fin(s.from) && fin(s.to) && w.from <= s.from + WIN_EPS && w.to >= s.to - WIN_EPS; + +function windowsStage({ idn, windows, rows, savedWhole, focus }) { + const live = windows.filter((w) => !w.desynced); + const clipIds = new Set(rows.map((r) => r.clipId)); + const annotated = windows.map((w) => { + const serves = w.desynced ? [] : rows.filter((r) => holds(w, playedOf(r))).map((r) => ({ project: r.project, clipId: r.clipId })); + const partly = w.desynced ? [] : rows.filter((r) => !holds(w, playedOf(r)) && overlaps(playedOf(r).from, playedOf(r).to, w.from, w.to)).map((r) => ({ project: r.project, clipId: r.clipId })); + const orphan = !!(w.sidecar?.clipId && !clipIds.has(w.sidecar.clipId)) && serves.length === 0; + return { ...w, serves, partly, orphan, focused: !!focus && Math.abs(w.from - focus.from) <= WIN_EPS && Math.abs(w.to - focus.to) <= WIN_EPS }; + }); + // A draft clip no window holds (and no saved whole recording, which cuts any span). + const uncovered = savedWhole ? [] : rows.filter((r) => r.inDraft && !live.some((w) => holds(w, playedOf(r)))).map((r) => ({ project: r.project, clipId: r.clipId, ...playedOf(r) })); + const focusedWin = focus ? annotated.find((w) => w.focused) ?? null : null; + const desyncedN = windows.filter((w) => w.desynced).length; + const bits = [ + `${live.length} window${live.length === 1 ? "" : "s"}`, + desyncedN && `${desyncedN} set aside (desynced)`, + uncovered.length && `${uncovered.length} clip${uncovered.length === 1 ? "" : "s"} not fetched`, + savedWhole && "the whole recording is saved (any span cuts from it)", + ].filter(Boolean); + return { + key: "windows", + label: "Windows", + pill: uncovered.length || desyncedN ? pill("warn") : live.length ? pill("count", live.length) : savedWhole ? pill("ok") : pill("none"), + line: live.length || uncovered.length || desyncedN || savedWhole ? bits.join(", ") : "No windows cut yet", + windows: annotated, + uncovered, + savedWhole: !!savedWhole, + focus: focus ? { ...focus, name: windowName(focus.from, focus.to), found: !!focusedWin } : null, + }; +} + +// ── used in ────────────────────────────────────────────────────────────────── + +function usedStage({ rows, allRows, focus }) { + const projects = new Set(rows.map((r) => r.project)); + return { + key: "used", + label: "Used in", + pill: rows.length ? pill("count", rows.length) : pill("none"), + line: rows.length + ? `${rows.length} clip${rows.length === 1 ? "" : "s"} in ${projects.size} project${projects.size === 1 ? "" : "s"}${focus && allRows.length !== rows.length ? ` (of ${allRows.length} from this recording)` : ""}` + : focus && allRows.length + ? `No clip plays from this window (${allRows.length} from the recording elsewhere)` + : "No project cuts from it", + rows, + }; +} + +// ── checked ────────────────────────────────────────────────────────────────── + +async function checkedStage({ rows, dirOf }) { + const out = []; + const docs = new Map(); + for (const r of rows) { + const dir = dirOf(r.project); + if (!docs.has(r.project)) docs.set(r.project, await readQuoteCheck(dir)); + const row = docs.get(r.project)?.clips?.[r.clipId] ?? null; + const entry = { start: r.start, end: r.end, cutStart: r.cutStart, cutEnd: r.cutEnd, quote: r.quote ?? "" }; + out.push({ + project: r.project, + clipId: r.clipId, + hasQuote: !!r.quote, + status: row?.status ?? null, + offset: fin(row?.offset) ? row.offset : null, + current: row && r.inDraft ? rowIsCurrent(row, entry) : false, + checkedAt: docs.get(r.project)?.checkedAt ?? null, + }); + } + const current = out.filter((c) => c.current); + const bad = current.filter((c) => c.status !== "ok"); + const quoted = out.filter((c) => c.hasQuote).length; + return { + key: "checked", + label: "Checked", + pill: !out.length ? pill("none") : bad.length ? pill("warn") : quoted && current.length >= quoted ? pill("ok") : current.length ? pill("count", current.length) : pill("none"), + line: !out.length + ? "Nothing to check: no clip uses it" + : bad.length + ? `${bad.map((b) => `${b.clipId} ${b.status}`).join(", ")}` + : current.length + ? `${current.length} of ${quoted || out.length} quote${(quoted || out.length) === 1 ? "" : "s"} heard where the cut plays` + : quoted + ? "Not quote-checked (or the cut changed since)" + : "No clip carries a quote to check", + clips: out, + }; +} + +// ── rendered ───────────────────────────────────────────────────────────────── + +async function renderedStage({ rows, dirOf }) { + const out = []; + for (const r of rows) { + const dir = dirOf(r.project); + for (const v of r.versions) { + const rec = await readRenderRecord(path.join(dir, "takes", v.id)).catch(() => null); + const cut = await readJson(path.join(dir, "takes", v.id, "out", "segments", `${r.clipId}.cut.json`)); + out.push({ project: r.project, clipId: r.clipId, version: v.id, kind: v.kind, state: rec?.state ?? null, seconds: fin(rec?.seconds) ? rec.seconds : null, endedAt: rec?.endedAt ?? rec?.finishedAt ?? null, cut: cut && typeof cut === "object" ? { from: cut.from ?? cut.start ?? null, to: cut.to ?? cut.end ?? null } : null }); + } + if (r.inDraft) { + const cut = await readJson(path.join(dir, "out", "segments", `${r.clipId}.cut.json`)); + if (cut) out.push({ project: r.project, clipId: r.clipId, version: null, kind: "draft", state: "segment", seconds: null, endedAt: null, cut: { from: cut.from ?? cut.start ?? null, to: cut.to ?? cut.end ?? null } }); + } + } + const done = out.filter((x) => x.state === "done"); + return { + key: "rendered", + label: "Rendered", + pill: done.length ? pill("count", done.length) : pill("none"), + line: done.length + ? `In ${done.length} rendered version${done.length === 1 ? "" : "s"}: ${[...new Set(done.map((d) => `${d.project.split("/").pop()} ${d.version}`))].slice(0, 4).join(", ")}${done.length > 4 ? ", …" : ""}` + : out.length + ? "In versions not rendered (or not finished)" + : "Not in any saved version", + renders: out, + }; +} + +// ── published ──────────────────────────────────────────────────────────────── + +async function publishedStage({ rows, dirOf, idn }) { + const out = []; + const byProject = new Map(); + for (const r of rows) { + if (!byProject.has(r.project)) { + const dir = dirOf(r.project); + const m = await readJson(path.join(dir, "video.manifest.json")); + byProject.set(r.project, { links: await readLinkCheck(dir), provenance: m?.provenance ?? null, timeline: Array.isArray(m?.timeline) ? m.timeline : [] }); + } + const p = byProject.get(r.project); + const entry = p.timeline.find((e) => e?.id === r.clipId) ?? null; + const origin = typeof p.provenance?.siteOrigin === "string" && /^https?:\/\//i.test(p.provenance.siteOrigin) ? p.provenance.siteOrigin.replace(/\/+$/, "") : null; + const url = entry?.citeUrl ?? (origin && entry ? archiveMomentUrl({ ...entry, channel: entry.channel ?? idn.ch, ...(idn.siteId && !entry.siteVideo ? { siteVideo: idn.siteId } : {}) }, p.provenance, Math.floor(fin(entry.cutStart) ? entry.cutStart : entry.start ?? 0), { origin }) : null); + const recorded = (p.links?.links ?? []).filter((l) => l.clip === r.clipId); + const now = url ? recorded.find((l) => l.url === url) ?? null : recorded[0] ?? null; + out.push({ project: r.project, clipId: r.clipId, url, state: now?.state ?? (recorded.length ? "changed" : null), fix: now?.fix ?? null, checkedAt: p.links?.checkedAt ?? null }); + } + const dead = out.filter((o) => o.state === "dead"); + const ok = out.filter((o) => o.state === "ok"); + const unverified = out.filter((o) => o.state === "unverified"); + return { + key: "published", + label: "Published", + pill: !out.length ? pill("none") : dead.length ? pill("warn") : ok.length === out.length ? pill("ok") : ok.length ? pill("count", ok.length) : pill("none"), + line: !out.length + ? "Not in any cut, so no link to it" + : dead.length + ? `${dead.length} dead link${dead.length === 1 ? "" : "s"}: ${dead.map((d) => d.clipId).join(", ")}` + : `${ok.length} of ${out.length} link${out.length === 1 ? "" : "s"} open on the site${unverified.length ? `, ${unverified.length} unverified` : ""}${out.some((o) => o.state === null || o.state === "changed") ? ", some never checked" : ""}`, + links: out, + }; +} + +// ── the whole of it ────────────────────────────────────────────────────────── + +/** + * The ingredient's nine stages. + * + * @param {{ channelsDir: string, reportsRoot: string, ch: string, id: string, window?: string | { from: number, to: number } | null, + * index?: Record<string, any> | null, indexFile?: string, writeIndex?: boolean }} o + */ +export async function readIngredient({ channelsDir, reportsRoot, ch, id, window = null, index = null, indexFile, writeIndex = true }) { + if (!isChannelSlug(ch)) throw new Error(`"${ch}" is not a channel slug`); + if (!isVideoId(id)) throw new Error(`"${id}" is not a video id`); + const focus = typeof window === "string" ? parseWindowParam(window) : window && fin(window.from) && fin(window.to) ? window : null; + const idn = await ingredientIdentity({ channelsDir, ch, id }); + const idx = index ?? (await loadUsageIndex({ reportsRoot, channelsDir, ...(indexFile ? { file: indexFile } : {}), write: writeIndex })).index; + const allRows = usesOf(idx, ch, idn.dirId); + const rows = rowsInWindow(allRows, focus); + const dirOf = (project) => path.join(reportsRoot, project); + + const windows = idn.exists ? await listWindows(idn.dir) : []; + const pointer = idn.exists ? await readSavedVideoPointer(idn.dir) : null; + const savedWhole = pointer ? await present(pointer.path) : false; + + const [found, downloaded, transcribed, clock] = await Promise.all([foundStage({ reportsRoot, idn }), downloadedStage({ idn }), transcribedStage({ idn }), clockStage({ idn })]); + const win = windowsStage({ idn, windows, rows: allRows, savedWhole, focus }); + const used = usedStage({ rows, allRows, focus }); + const [checked, rendered, published] = await Promise.all([checkedStage({ rows, dirOf }), renderedStage({ rows, dirOf }), publishedStage({ rows, dirOf, idn })]); + + const title = downloaded.meta?.title ?? transcribed.cues?.title ?? null; + return { + ch, + id: idn.asked, + dirId: idn.dirId, + siteId: idn.siteId, + platform: idn.platform, + exists: idn.exists, + title, + webpageUrl: downloaded.meta?.webpageUrl ?? downloaded.outcome?.webpageUrl ?? null, + duration: transcribed.cues?.duration ?? null, + uploadDate: transcribed.cues?.uploadDate ?? downloaded.meta?.uploadDate ?? null, + notes: idn.notes, + focus: win.focus, + stages: [found, downloaded, transcribed, clock, win, used, checked, rendered, published], + }; +} + +/** The pill as one glyph (the CLI's, and the page's text): ✓, the count, ! or —. */ +export const pillGlyph = (p) => (p?.kind === "ok" ? "✓" : p?.kind === "count" ? String(p.n) : p?.kind === "warn" ? "!" : "—"); diff --git a/umtool/lib/ingredients/stages.test.mjs b/umtool/lib/ingredients/stages.test.mjs @@ -0,0 +1,152 @@ +// node --test umtool/lib/ingredients/stages.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { lastEndOf, readJsonHead, scanHead } from "./heads.mjs"; +import { parseWindowParam, pillGlyph, readIngredient, STAGES } from "./stages.mjs"; + +test("scanHead: the top-level primitives, nested members skipped, a truncated text read as far as it is whole", () => { + const text = JSON.stringify({ id: "abc", title: "A \"quoted\" title", formats: [{ duration: 9, x: "}" }], duration: 120, live: false, n: null, cues: [{ end: 5 }] }); + const all = scanHead(text); + assert.deepEqual(all.fields, { id: "abc", title: 'A "quoted" title', duration: 120, live: false, n: null }); + assert.deepEqual(all.nested, ["formats", "cues"]); + assert.equal(all.complete, true); + const stopped = scanHead(text, { stopKey: "formats" }); + assert.deepEqual(stopped.fields, { id: "abc", title: 'A "quoted" title' }); + // Cut in the middle of the formats array: what came before is still read. + const cut = scanHead(text.slice(0, text.indexOf("duration") + 4)); + assert.deepEqual(cut.fields, { id: "abc", title: 'A "quoted" title' }); + assert.equal(cut.complete, false); + // A number at the very end of the buffer may be cut short: not read. + assert.deepEqual(scanHead('{"a": 12').fields, {}); +}); + +test("parseWindowParam", () => { + assert.deepEqual(parseWindowParam("10.00-40.00"), { from: 10, to: 40 }); + assert.equal(parseWindowParam("40-10"), null); + assert.equal(parseWindowParam("x"), null); +}); + +async function corpus() { + const root = await mkdtemp(path.join(tmpdir(), "stages-")); + const channels = path.join(root, "channels"); + const reports = path.join(root, "reports"); + const vdir = path.join(channels, "chan", "data", "vid"); + await mkdir(path.join(vdir, "clips"), { recursive: true }); + await writeFile(path.join(channels, "chan", "config.json"), JSON.stringify({ platform: "youtube" })); + // A metadata file whose formats push everything past the head. + const formats = Array.from({ length: 4000 }, (_, i) => ({ format_id: String(i), duration: 1, url: "https://x.example/" + "y".repeat(20) })); + await writeFile(path.join(vdir, "metadata.info.json"), JSON.stringify({ id: "vid", title: "The Recording", formats, webpage_url: "https://www.youtube.com/watch?v=vid", duration: 300 })); + const cues = Array.from({ length: 50 }, (_, i) => ({ start: i * 6, end: i * 6 + 5.5, text: `cue ${i}` })); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ version: 2, source: "vtt", title: "The Recording", uploadDate: "20261101", duration: 300, cues })); + await writeFile(path.join(vdir, "transcript.en.vtt"), "WEBVTT\n"); + await writeFile(path.join(vdir, "download-outcome.json"), JSON.stringify({ videoId: "vid", status: "ok", attempts: [{ n: 0 }] })); + await writeFile(path.join(vdir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: "2026-11-01T00:00:00Z" })); + await writeFile(path.join(vdir, "clips", "10.00-40.00.mp4"), Buffer.alloc(100)); + await writeFile(path.join(vdir, "clips", "10.00-40.00.json"), JSON.stringify({ requestedBy: "a cut", clipId: "a1", fetchedAt: "2026-11-02T00:00:00Z" })); + await writeFile(path.join(vdir, "clips", "200.00-230.00.mp4"), Buffer.alloc(50)); + await writeFile(path.join(vdir, "clips", "200.00-230.00.json"), JSON.stringify({ requestedBy: "gone cut", clipId: "zz" })); + const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid", start, end, ...extra }); + const m = (timeline) => ({ provenance: { channelSlug: "chan", siteOrigin: "https://site.example" }, render: {}, timeline }); + const a = path.join(reports, "f", "a"); + await mkdir(path.join(a, "takes", "v1"), { recursive: true }); + await writeFile(path.join(a, "video.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" }), clip("a2", 100, 110, { quote: "another" })]))); + await writeFile(path.join(a, "takes", "v1", "take.json"), "{}"); + await writeFile(path.join(a, "takes", "v1", "base.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" })]))); + await writeFile(path.join(a, "takes", "v1", "preview.mp4"), Buffer.alloc(10)); + await writeFile(path.join(a, "takes", "v1", "render.json"), JSON.stringify({ state: "done", mp4: "preview.mp4", seconds: 8 })); + await writeFile(path.join(a, "quote-check.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-03T00:00:00Z", clips: { a1: { status: "ok", cut: { from: 12, to: 20 }, quote: "the quote" }, a2: { status: "moved", cut: { from: 100, to: 110 }, quote: "another" } } })); + const b = path.join(reports, "f", "b"); + await mkdir(path.join(b, "out"), { recursive: true }); + await writeFile(path.join(b, "video.manifest.json"), JSON.stringify(m([clip("b1", 15, 25)]))); + await writeFile(path.join(b, "out", "links.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-04T00:00:00Z", links: [{ clip: "b1", url: "https://site.example/?v=chan%2Fvid&t=15", state: "ok" }] })); + return { root, channels, reports, vdir }; +} + +async function listTree(dir) { + const out = []; + for (const e of await readdir(dir, { withFileTypes: true, recursive: true })) out.push(path.join(e.parentPath ?? e.path, e.name)); + const st = await Promise.all(out.map((p) => stat(p).then((s) => `${p}:${s.size}:${s.mtimeMs}`))); + return st.sort(); +} + +test("the nine stages of a recording used by two projects, read without writing to the corpus", async () => { + const { root, channels, reports, vdir } = await corpus(); + try { + const before = await listTree(channels); + const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", indexFile: path.join(root, "state", "usage.json") }); + assert.deepEqual(await listTree(channels), before, "nothing under the channels dir changed"); + assert.deepEqual(r.stages.map((s) => s.key), STAGES.map((s) => s.key)); + const by = Object.fromEntries(r.stages.map((s) => [s.key, s])); + assert.equal(r.title, "The Recording"); + assert.equal(r.webpageUrl, null, "webpage_url is past the head: not read"); + assert.equal(by.downloaded.pill.kind, "ok"); + assert.equal(by.downloaded.meta.id, "vid"); + assert.equal(by.transcribed.pill.kind, "ok"); + assert.equal(by.transcribed.cues.lastEnd, 299.5); + assert.ok(Math.abs(by.transcribed.cues.coverage - 299.5 / 300) < 1e-9); + assert.equal(pillGlyph(by.clock.pill), "—"); + // Windows: a2 (100-110) has no window -> the stage warns; the 200-230 window's clip no project uses. + assert.equal(by.windows.pill.kind, "warn"); + assert.deepEqual(by.windows.uncovered.map((u) => u.clipId), ["a2"]); + const w10 = by.windows.windows.find((w) => w.name === "10.00-40.00"); + assert.deepEqual(w10.serves.map((s) => s.clipId).sort(), ["a1", "b1"]); + assert.equal(by.windows.windows.find((w) => w.name === "200.00-230.00").orphan, true); + assert.deepEqual(by.used.rows.map((u) => `${u.project}#${u.clipId}`), ["f/a#a1", "f/a#a2", "f/b#b1"]); + assert.equal(pillGlyph(by.used.pill), "3"); + assert.equal(by.checked.pill.kind, "warn"); + assert.match(by.checked.line, /a2 moved/); + assert.deepEqual(by.rendered.renders.filter((x) => x.state === "done").map((x) => `${x.clipId}@${x.version}`), ["a1@v1"]); + assert.equal(pillGlyph(by.rendered.pill), "1"); + const b1 = by.published.links.find((l) => l.clipId === "b1"); + assert.equal(b1.state, "ok"); + assert.equal(b1.url, "https://site.example/?v=chan%2Fvid&t=15"); + assert.equal(by.published.links.find((l) => l.clipId === "a1").state, null); + void vdir; + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("?window= focuses one window: the stages after it narrow to the clips it plays", async () => { + const { root, channels, reports } = await corpus(); + try { + const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", window: "10.00-40.00", indexFile: path.join(root, "state", "usage.json") }); + const by = Object.fromEntries(r.stages.map((s) => [s.key, s])); + assert.deepEqual(r.focus, { from: 10, to: 40, name: "10.00-40.00", found: true }); + assert.equal(by.windows.windows.filter((w) => w.focused).length, 1); + assert.deepEqual(by.used.rows.map((u) => u.clipId), ["a1", "b1"]); + assert.match(by.used.line, /of 3 from this recording/); + assert.deepEqual(by.checked.clips.map((c) => c.clipId), ["a1", "b1"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("an id the corpus does not hold: every stage says so, nothing throws", async () => { + const { root, channels, reports } = await corpus(); + try { + const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "nope", indexFile: path.join(root, "state", "usage.json") }); + assert.equal(r.exists, false); + assert.equal(r.stages.length, 9); + assert.match(r.stages[1].line, /Not in the corpus/); + assert.equal(r.stages[4].line, "No windows cut yet"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("the head and tail readers read only their ends", async () => { + const { root, vdir } = await corpus(); + try { + const h = await readJsonHead(path.join(vdir, "metadata.info.json")); + assert.ok(h.size > 64 * 1024); + assert.deepEqual(Object.keys(h.fields), ["id", "title"]); + assert.equal(await lastEndOf(path.join(vdir, "transcript.cues.json")), 299.5); + assert.equal(await lastEndOf(path.join(vdir, "nope.json")), null); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -7,6 +7,7 @@ // <REPORTS_ROOT>/.umtool/usage-index.json (UMTOOL_USAGE_INDEX_FILE overrides) // { format: "umtool-usage-index", version: 1, builtAt, // files: { "<abs manifest>": { mtimeMs, size, project, version, kind, clips: [Use] } }, +// dirIds: { "<ch>/<cited id>": { dir, dataMtimeMs? } }, a Rumble/Twitch id's directory, resolved once // byIngredient: { "<ch>/<dir id>": [Row] } } // // Use { ch, video, siteVideo?, clipId, start, end, cutStart, cutEnd, quote? } one clip of one manifest @@ -124,11 +125,27 @@ export async function buildUsageIndex({ reportsRoot, channelsDir, previous = nul const resolve = resolveDir ?? (async (ch, video) => (channelsDir ? await resolveVideoDirId(channelsDir, ch, video).catch(() => video) : video)); + // The directory ids, cached with the index: a Rumble embed id is resolved by reading the heads of the + // channel's metadata files (thousands on a big channel), so a resolution is kept -- for good once it found a + // directory (a directory is never renamed under a recording), and until the channel's data/ changes when it + // found none. Only a Rumble- or Twitch-shaped id ever costs a read (resolveVideoDirId). + const prevDirIds = previous?.format === USAGE_INDEX_FORMAT && previous?.dirIds && typeof previous.dirIds === "object" ? previous.dirIds : {}; + const dirIds = {}; const memo = new Map(); + const costly = (video) => /^v[0-9a-z]{4,9}$/.test(video); + const dataMtime = async (ch) => (channelsDir ? await stat(path.join(channelsDir, ch, "data")).then((s) => Math.round(s.mtimeMs), () => null) : null); const dirIdOf = async (ch, video) => { - const k = `${ch}\u0000${video}`; - if (!memo.has(k)) memo.set(k, await resolve(ch, video)); - return memo.get(k); + const k = `${ch}/${video}`; + if (memo.has(k)) return memo.get(k); + let dir = null; + if (costly(video)) { + const was = prevDirIds[k]; + if (was && typeof was.dir === "string" && (was.dir !== video || was.dataMtimeMs === (await dataMtime(ch)))) dir = was.dir; + if (dir === null) dir = await resolve(ch, video); + dirIds[k] = { dir, ...(dir === video ? { dataMtimeMs: await dataMtime(ch) } : {}) }; + } else dir = await resolve(ch, video); + memo.set(k, dir); + return dir; }; const projects = (await walk(reportsRoot)).filter((p) => p.kind === "report-video" || p.kind === undefined); @@ -188,7 +205,7 @@ export async function buildUsageIndex({ reportsRoot, channelsDir, previous = nul .map((r) => ({ ...r, versions: r.versions.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true })) })) .sort((a, b) => a.project.localeCompare(b.project) || (a.start ?? 0) - (b.start ?? 0) || a.clipId.localeCompare(b.clipId)); } - const index = { format: USAGE_INDEX_FORMAT, version: USAGE_INDEX_VERSION, builtAt: now().toISOString(), files, byIngredient }; + const index = { format: USAGE_INDEX_FORMAT, version: USAGE_INDEX_VERSION, builtAt: now().toISOString(), files, dirIds, byIngredient }; return { index, stats: { manifests: Object.keys(files).length, parsed, reused, dropped, projects: projects.length } }; } @@ -218,7 +235,12 @@ async function writeUsageIndex(file, index) { export async function loadUsageIndex({ reportsRoot, channelsDir, file = usageIndexPath(reportsRoot), write = true, walk, resolveDir }) { const previous = await readUsageIndex(file); const built = await buildUsageIndex({ reportsRoot, channelsDir, previous, ...(walk ? { walk } : {}), ...(resolveDir ? { resolveDir } : {}) }); - const changed = !previous || built.stats.parsed > 0 || built.stats.dropped > 0 || JSON.stringify(previous.byIngredient) !== JSON.stringify(built.index.byIngredient); + const changed = + !previous || + built.stats.parsed > 0 || + built.stats.dropped > 0 || + JSON.stringify(previous.byIngredient) !== JSON.stringify(built.index.byIngredient) || + JSON.stringify(previous.dirIds ?? {}) !== JSON.stringify(built.index.dirIds); if (write && changed) await writeUsageIndex(file, built.index).catch(() => {}); return { ...built, file, written: write && changed }; }