Archilyzer · Source

archilyzer

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

commit 508f99776691a855df905234e91684e4344b2c7f
parent 6975de5305629cd7f20a7468f140baae29899669
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 01:44:23 -0500

umtool: a project's channels tree first, the corpus behind it

With `provenance.channelsDir: ".shadow-channels"` post items, cue files and
the build's corpus-window tier read only the shadow (report.mjs channelsDirFor,
build-video), and nothing overrode it: rev 9's cut lane copied three
channels' posts, three cue files and the editor's windows into the shadow
and rendered with CHANNELS_DIR=<shadow>.

sources.mjs channelsLayersFor: the project's own tree first, the corpus
(transcripts/channels) behind it -- unless `provenance.channelsFallback:
false` or CHANNELS_FALLBACK=0 (the shadow alone, as before). Each kind that
falls back is said once per run (noteChannelsFallback):

- posts: postItemFromArchive, posts reel (each channel from the first tree
  holding its posts; captures and the archive's avatars from the same),
  posts add (firstLayerWith).
- cues: report.mjs cuePathFor (every umtool caller), the build's cue source
  (createCueSource channelsDirs: a later tree only when the first has no cue
  file; each tree's reachability checked on its own).
- windows: resolveLocalSource / corpusWindowsOf `fallbackChannelsDir` (the
  corpus tiers only -- never the project's raw cache twice), the build's
  localSources and the clip bench.

Tests on temp dirs (channels-layers.test.mjs); report-video.md says it.

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

Diffstat:
Mumtool/docs/report-video.md | 14++++++++++++++
Mumtool/lib/projects/report.mjs | 30+++++++++++++++++++++++++++---
Mumtool/lib/report/postReel.mjs | 26++++++++++++++++++--------
Mumtool/lib/report/postsCli.mjs | 7+++++--
Mumtool/report-to-video/build-video.mjs | 26+++++++++++++++++++-------
Aumtool/report-to-video/channels-layers.test.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/cues.mjs | 44+++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/sources.mjs | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
8 files changed, 280 insertions(+), 30 deletions(-)

diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1866,6 +1866,20 @@ preference: cut the same moment from a live mirror (via a `CHANNELS_DIR` shadow directory — but check the archive's alignment statement first, because mirrors are not assumed to share a clock), or convert the clip to a quote card. +### A project's own channels tree, and the corpus behind it + +A project that names its own channels tree (`provenance.channelsDir`, or a +`.shadow-channels/` beside its manifest, which `make-shadow-channels.sh` builds) reads +it FIRST -- and the real corpus (`transcripts/channels`, `CHANNELS_DIR`) for anything +the tree lacks: a channel's posts archive (post items: `timeline insert post:…`, +`posts reel`, `posts add`), a clip's `transcript.cues.json` (umtool's checks, the +bench, the build's cue source) and a cached window (the build's corpus tier, the clip +bench). So a shadow made before a channel was added to the corpus no longer needs that +channel copied into it. Each kind that falls back says so once per run +(`posts: … read from …`, `cues: …`, `windows: …`). `provenance.channelsFallback: false` +(or `CHANNELS_FALLBACK=0` in the environment) turns the fallback off: the shadow alone, +as before (sources.mjs `channelsLayersFor`). + ## The ledger, and why it must be adjudicated `ledger[]` is the claim set the rail and the closing cards read. Beside the diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -7,11 +7,15 @@ // and neither parses JSON. import { postItemSeconds } from "umtool-report-to-video/post-item"; import { readdir, readFile, stat } from "node:fs/promises"; +import { existsSync } from "node:fs"; import path from "node:path"; import { DEFAULT_VARIANT, cachedWindowsFor, fetchSpans } from "umtool-report-to-video/build-video"; import { SHADOW_CHANNELS as SOURCES_SHADOW_CHANNELS, channelsDirFor as sourcesChannelsDirFor, + channelsFallbackOn, + channelsLayersFor as sourcesChannelsLayersFor, + noteChannelsFallback, corpusWindowsOf, ffprobeSource, } from "umtool-report-to-video/sources"; @@ -90,6 +94,15 @@ export function channelsDirFor(dir, manifest, { shadowExists = false } = {}) { return sourcesChannelsDirFor(dir, manifest, { shadowExists, fallback: GLOBAL_CHANNELS_DIR() }); } +/** + * The channels trees this project reads, in order (sources.mjs channelsLayersFor): + * its own (channelsDirFor) and the global corpus behind it, unless the fallback + * is off (`provenance.channelsFallback: false`, CHANNELS_FALLBACK=0). + */ +export function channelsLayersFor(dir, manifest, { shadowExists = false } = {}) { + return sourcesChannelsLayersFor(dir, manifest, { shadowExists, fallback: GLOBAL_CHANNELS_DIR() }); +} + export const hasShadowChannels = (dir) => stat(path.join(dir, SHADOW_CHANNELS)).then((s) => s.isDirectory(), () => false); @@ -558,7 +571,9 @@ export const clipWindowDirs = async ( if (Number.isFinite(duration) && duration > 0) return { duration }; return file ? probeContainer(file) : null; }; - const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe })).filter((w) => + // The corpus behind the project's channels tree, for a video its tree has no window of (channelsLayersFor). + const behind = channelsDir && channelsFallbackOn(m) && path.resolve(GLOBAL_CHANNELS_DIR()) !== path.resolve(root) ? GLOBAL_CHANNELS_DIR() : null; + const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe, fallbackChannelsDir: behind })).filter((w) => readable(w.path), ); if (windows.length) out.push({ video: e.video, windows }); @@ -601,13 +616,22 @@ export async function noCuesFix(m, e, file) { return `Build it: pnpm ops build-cues --json '${json}' --wait`; } -export const cuePathFor = (m, e, channelsDir) => { +export const cuePathFor = (m, e, channelsDir, fallbackChannelsDir = channelsDir && channelsFallbackOn(m) ? GLOBAL_CHANNELS_DIR() : null) => { const chan = channelFor(m, e); // A clip with its own media (`src`, `cues`) names no corpus video: there is // no cue file to find, and path.join(undefined) would throw. if (!chan || e.video == null) return null; // The record's directory: a Twitch v<n> is data/<n>/ (release 23 F1b). - return path.join(resolveVideoDirSync(channelsDir ?? GLOBAL_CHANNELS_DIR(), chan, e.video), "transcript.cues.json"); + const own = path.join(resolveVideoDirSync(channelsDir ?? GLOBAL_CHANNELS_DIR(), chan, e.video), "transcript.cues.json"); + // The corpus behind the project's channels tree (channelsLayersFor), when its own has no cue file for it. + if (fallbackChannelsDir && path.resolve(fallbackChannelsDir) !== path.resolve(channelsDir ?? GLOBAL_CHANNELS_DIR()) && !existsSync(own)) { + const behind = path.join(resolveVideoDirSync(fallbackChannelsDir, chan, e.video), "transcript.cues.json"); + if (existsSync(behind)) { + noteChannelsFallback("cues", `cues: ${chan}/${e.video} has no transcript.cues.json under ${channelsDir} -- read from ${fallbackChannelsDir} (the corpus behind the project's channels tree)`); + return behind; + } + } + return own; }; // --------------------------------------------------------------------------- diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -39,7 +39,8 @@ import path from "node:path"; import { promisify } from "node:util"; import { POST_MEDIA_MAX, POST_PARENTS_FILL, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; import { ARCHIVE_AVATARS_DIR, ARCHIVE_AVATARS_FILE, AVATARS_DIR, AVATAR_EXT_RE, avatarEntryOf, handleKey } from "umtool-report-to-video/post-avatars"; -import { channelsDirFor, readManifest } from "../projects/report.mjs"; +import { channelsDirFor, channelsLayersFor, readManifest } from "../projects/report.mjs"; +import { firstLayerWith } from "umtool-report-to-video/sources"; import { withEditNotes } from "./edit-guard.mjs"; import { addArchiveAvatars, insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; @@ -421,14 +422,21 @@ export async function postsReel(project, o) { if (o.limit !== null && o.limit !== undefined && !(Number.isInteger(o.limit) && o.limit > 0)) throw new Error("--limit takes a whole number of posts"); const manifest = await readManifest(project.dir); if (!manifest) throw new Error(`${project.id} has no manifest`); - const channelsDir = o.channelsDir ?? channelsDirFor(project.dir, manifest); + const layers = o.channelsDir ? [o.channelsDir] : channelsLayersFor(project.dir, manifest); + const channelsDir = layers[0] ?? channelsDirFor(project.dir, manifest); const rows = []; const handles = []; + // Each channel from the first tree that holds its posts: the project's, else the corpus behind it. + const rootOf = new Map(); + const root = async (slug) => { + if (!rootOf.has(slug)) rootOf.set(slug, layers.length > 1 ? await firstLayerWith(layers, [slug, "posts"], { kind: "posts" }) : channelsDir); + return rootOf.get(slug); + }; for (const c of channels) { - const got = await readPostsArchive(channelsDir, c); - if (!got.length) throw new Error(`${c} has no posts archive under ${channelsDir} (channels/${c}/posts/*.jsonl) — is it a social channel?`); + const got = await readPostsArchive(await root(c), c); + if (!got.length) throw new Error(`${c} has no posts archive under ${layers.join(" or ")} (channels/${c}/posts/*.jsonl) — is it a social channel?`); rows.push(...got); - const h = await channelHandle(channelsDir, c); + const h = await channelHandle(await root(c), c); if (h) handles.push(h); } // Every channel's rows by id, for the parents, the quoted post and a repost's original. @@ -437,7 +445,7 @@ export async function postsReel(project, o) { const captures = new Map(); const capture = async (slug, id) => { const k = `${slug}/${id}`; - if (!captures.has(k)) captures.set(k, await captureOf(channelsDir, slug, id)); + if (!captures.has(k)) captures.set(k, await captureOf(await root(slug), slug, id)); return captures.get(k); }; // "With media": the post's capture (or a repost's original's) holds an attachment. @@ -475,7 +483,8 @@ export async function postsReel(project, o) { dropped += made.dropped; } // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of. - const store = await archiveAvatars(channelsDir, channels); + const store = new Map(); + for (const c of channels) for (const [k, v] of await archiveAvatars(await root(c), [c])) if (!store.has(k)) store.set(k, v); const avatars = store.size ? await avatarsToCopy(manifest, entries, store, o.dryRun ? async (_f, rel) => rel : (from, rel) => copyInto(project.dir, from, rel)) : {}; const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped, avatars: Object.keys(avatars) }; if (o.dryRun) return { ...summary, entries, dryRun: true, result: null, editNotes: null }; @@ -505,7 +514,8 @@ export async function postsReel(project, o) { */ export async function postItemFromArchive(project, manifest, slug, postId, { id = null, channelsDir = null } = {}) { if (!SLUG_RE.test(slug)) throw new Error(`"${slug}" is not a channel slug`); - const dir = channelsDir ?? channelsDirFor(project.dir, manifest); + // The project's channels tree first, the corpus behind it for a channel it lacks (sources.mjs channelsLayersFor). + const dir = channelsDir ?? await firstLayerWith(channelsLayersFor(project.dir, manifest), [slug, "posts"], { kind: "posts" }); const rows = await readPostsArchive(dir, slug); const index = new Map(rows.map((r) => [r.id, r])); const row = index.get(String(postId)); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -397,8 +397,11 @@ export async function addPostFromArchive(project, { slug, postId, attach = null, if (!SLUG_RE.test(slug) || !POST_ID_RE.test(postId)) throw new CliError(`not <archive-channel>/<postId>: ${slug}/${postId}`); const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); - // The corpus the project reads (provenance.channelsDir), else the global one. - const channelsDir = channelsDirFor(project.dir, manifest); + // The corpus the project reads (provenance.channelsDir), else the global one -- and the global one behind a + // project's own tree for a channel that tree lacks (sources.mjs channelsLayersFor). + const { channelsLayersFor } = await import("../projects/report.mjs"); + const { firstLayerWith } = await import("umtool-report-to-video/sources"); + const channelsDir = await firstLayerWith(channelsLayersFor(project.dir, manifest), [slug, "posts"], { kind: "posts" }) ?? channelsDirFor(project.dir, manifest); const found = await findPostRow(channelsDir, slug, postId); if (!found.row) { throw new Error( diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -144,7 +144,7 @@ import { cutArgs } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; // Where a clip's media is ALREADY on disk -- the build's raw cache, the // editor's corpus windows, the saved source -- asked before anything fetches. import { - SHADOW_CHANNELS, WIN_EPS as SRC_EPS, audioUse, channelsDirFor, findContainingWindow, rawWindowName, + SHADOW_CHANNELS, WIN_EPS as SRC_EPS, audioUse, channelsDirFor, channelsLayersFor, findContainingWindow, rawWindowName, resolveLocalSource, } from "./sources.mjs"; // A clip whose media is a file beside the manifest (`src`, `cues`). @@ -1045,7 +1045,7 @@ export function virtualEntry(entry, clock) { * so `--no-network`'s up-front pass and the clip's own fetch probe a saved * container once between them. */ -export function localSources({ rawDir, channelsDir, channelSlug = null, probe } = {}) { +export function localSources({ rawDir, channelsDir, channelSlug = null, probe, fallbackChannelsDir = null, log = undefined } = {}) { const memo = new Map(); const slugOf = (entry) => entry.channel ?? channelSlug ?? null; return { @@ -1059,7 +1059,7 @@ export function localSources({ rawDir, channelsDir, channelSlug = null, probe } if (memo.has(key)) return memo.get(key); const hit = await resolveLocalSource( { video: entry.video, slug, from: span.from, to: span.to }, - { rawDir, channelsDir, exact, probe, audio }, + { rawDir, channelsDir, exact, probe, audio, fallbackChannelsDir, log }, ); // Hits only: a miss is about to be fetched into the raw cache, and the // next clip asking for the same span must find that file. @@ -6643,12 +6643,24 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // bench reads for this project (sources.mjs channelsDirFor): the manifest's // own `provenance.channelsDir`, a `.shadow-channels/` beside it, else the // corpus the cue reader defaults to. - const channelsDir = opts.channelsDir ?? channelsDirFor(manifestDir, whole, { - shadowExists: await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false), - fallback: DEFAULT_CHANNELS_DIR, - }); + const shadowExists = await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false); + const channelsDir = opts.channelsDir ?? channelsDirFor(manifestDir, whole, { shadowExists, fallback: DEFAULT_CHANNELS_DIR }); + // THE SHADOW FIRST, THE CORPUS AFTER (sources.mjs channelsLayersFor): a project's own channels tree, and the + // corpus behind it for any cue file or cached window it lacks -- each kind said once; off with + // provenance.channelsFallback: false or CHANNELS_FALLBACK=0. + const layers = opts.channelsDir ? [opts.channelsDir] : channelsLayersFor(manifestDir, whole, { shadowExists, fallback: DEFAULT_CHANNELS_DIR }); + if (layers.length > 1) { + CUES = createCueSource({ + siteOrigin: opts.siteOrigin ?? process.env.SITE_ORIGIN ?? siteOriginFromManifest(whole), + resolveSiteIds: opts.resolveSiteIds === true, + prefer: opts.cueSource ?? "auto", + log: (m) => EMIT("log", { message: m }), + channelsDirs: layers, + }); + } dirs.local = localSources({ rawDir: dirs.rawDir, channelsDir, channelSlug: provenance?.channelSlug ?? null, probe: opts.probe, + fallbackChannelsDir: layers[1] ?? null, log: (m) => EMIT("note", { message: m }), }); FX_CHANNELS_DIR = channelsDir; // Read only for a cut that plays post items: a cut without them publishes nothing it could blank. diff --git a/umtool/report-to-video/channels-layers.test.mjs b/umtool/report-to-video/channels-layers.test.mjs @@ -0,0 +1,83 @@ +// The shadow first, the corpus after (sources.mjs channelsLayersFor; rev 9, 6 Nov): a project's own channels tree +// (`provenance.channelsDir`, a `.shadow-channels/`) read first, the real corpus behind it for anything it lacks -- +// posts, cue files, cached windows -- each kind said once; off with `provenance.channelsFallback: false` or +// CHANNELS_FALLBACK=0. Temp dirs only. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; + +import { + channelsFallbackOn, channelsLayersFor, firstLayerWith, resetChannelsFallbackNotes, resolveLocalSource, +} from "./sources.mjs"; +import { createCueSource } from "./cues.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-channels-layers-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const PROJECT = path.join(ROOT, "project"); +const SHADOW = path.join(PROJECT, ".shadow-channels"); +const CORPUS = path.join(ROOT, "transcripts", "channels"); +const put = async (file, body = "x") => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, body); +}; + +test("channelsLayersFor: the project's tree, then the corpus -- unless the manifest or the environment turns it off", () => { + const declared = { provenance: { channelsDir: ".shadow-channels" } }; + assert.deepEqual(channelsLayersFor(PROJECT, declared, { fallback: CORPUS, env: {} }), [SHADOW, CORPUS]); + assert.deepEqual(channelsLayersFor(PROJECT, {}, { shadowExists: true, fallback: CORPUS, env: {} }), [SHADOW, CORPUS]); + assert.deepEqual(channelsLayersFor(PROJECT, {}, { fallback: CORPUS, env: {} }), [CORPUS], "no tree of its own: the corpus alone"); + assert.deepEqual(channelsLayersFor(PROJECT, { provenance: { channelsDir: ".shadow-channels", channelsFallback: false } }, { fallback: CORPUS, env: {} }), [SHADOW]); + assert.deepEqual(channelsLayersFor(PROJECT, declared, { fallback: CORPUS, env: { CHANNELS_FALLBACK: "0" } }), [SHADOW]); + assert.equal(channelsFallbackOn({}, {}), true); +}); + +test("firstLayerWith: the first tree holding the path -- a later one said ONCE per kind; none: the first (its own miss)", async () => { + resetChannelsFallbackNotes(); + await put(path.join(SHADOW, "him-x", "posts", "a.jsonl")); + await put(path.join(CORPUS, "her-x", "posts", "a.jsonl")); + const said = []; + const log = (m) => said.push(m); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["him-x", "posts"], { kind: "posts", log }), SHADOW); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["her-x", "posts"], { kind: "posts", log }), CORPUS); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["her-x", "posts"], { kind: "posts", log }), CORPUS); + assert.equal(said.length, 1, "said once"); + assert.match(said[0], /posts: her-x\/posts is not in .*shadow-channels -- read from .*transcripts\/channels/); + assert.equal(await firstLayerWith([SHADOW, CORPUS], ["nobody-x", "posts"], { kind: "posts", log }), SHADOW); + assert.equal(await firstLayerWith([SHADOW], ["her-x", "posts"], { kind: "posts", log }), SHADOW, "the fallback off: the shadow alone"); +}); + +test("resolveLocalSource: a cached window the project's tree lacks is read from the corpus behind it (corpus tiers only)", async () => { + resetChannelsFallbackNotes(); + await put(path.join(CORPUS, "chan", "data", "vid9", "clips", "10.00-30.00.mp4")); + const said = []; + const hit = await resolveLocalSource({ video: "vid9", slug: "chan", from: 12, to: 20 }, { channelsDir: SHADOW, fallbackChannelsDir: CORPUS, log: (m) => said.push(m), probe: async () => null }); + assert.equal(hit?.kind, "corpus-window"); + assert.equal(hit.path, path.join(CORPUS, "chan", "data", "vid9", "clips", "10.00-30.00.mp4")); + assert.match(said[0], /windows: chan\/vid9 12-20 is not in .* -- read from /); + assert.equal(await resolveLocalSource({ video: "vid9", slug: "chan", from: 12, to: 20 }, { channelsDir: SHADOW, probe: async () => null }), null, "no fallback: the shadow alone, as before"); +}); + +test("createCueSource channelsDirs: a cue file the project's tree lacks is read from the corpus behind it, said once", async () => { + const cues = { cues: [{ start: 0, end: 1, text: "hi" }], duration: 1 }; + await put(path.join(CORPUS, "chan", "data", "vid7", "transcript.cues.json"), JSON.stringify(cues)); + await put(path.join(SHADOW, "chan", "data", "vid8", "transcript.cues.json"), JSON.stringify({ ...cues, duration: 2 })); + const said = []; + const src = createCueSource({ channelsDirs: [SHADOW, CORPUS], prefer: "local", log: (m) => said.push(m), cacheDir: path.join(ROOT, "cache") }); + assert.equal((await src.load("chan", "vid8")).duration, 2, "the shadow's own"); + assert.equal((await src.load("chan", "vid7")).duration, 1, "the corpus behind it"); + await src.load("chan", "vid7"); + assert.equal(said.filter((m) => /^cues:/.test(m)).length, 1); + // The shadow alone (the fallback off): a miss, as before. + const alone = createCueSource({ channelsDirs: [SHADOW], prefer: "local", cacheDir: path.join(ROOT, "cache") }); + await assert.rejects(alone.load("chan", "vid7"), /no local cues for chan\/vid7/); +}); + +test("cuePathFor: a clip's cue file from the corpus when the project's tree has none", async () => { + const { cuePathFor } = await import("../lib/projects/report.mjs"); + const m = { provenance: { channelSlug: "chan" } }; + assert.equal(cuePathFor(m, { video: "vid8" }, SHADOW, CORPUS), path.join(SHADOW, "chan", "data", "vid8", "transcript.cues.json")); + assert.equal(cuePathFor(m, { video: "vid7" }, SHADOW, CORPUS), path.join(CORPUS, "chan", "data", "vid7", "transcript.cues.json")); + assert.equal(cuePathFor(m, { video: "vid7" }, SHADOW, null), path.join(SHADOW, "chan", "data", "vid7", "transcript.cues.json"), "off: the shadow's path"); +}); diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -229,7 +229,10 @@ export function createJsonCache({ } export function createCueSource({ - channelsDir = DEFAULT_CHANNELS_DIR, + channelsDir: ownChannelsDir = DEFAULT_CHANNELS_DIR, + // The trees to read local cues from, in order (sources.mjs channelsLayersFor: the project's, then the corpus + // behind it). Absent: `channelsDir` alone. + channelsDirs = null, siteOrigin = null, cacheDir = DEFAULT_CACHE_DIR, fetchImpl = globalThis.fetch, @@ -240,6 +243,9 @@ export function createCueSource({ resolveSiteIds = false, } = {}) { const { getJson } = createJsonCache({ cacheDir, fetchImpl, log }); + const layers = Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [ownChannelsDir]; + const channelsDir = layers[0]; + let saidFallback = false; async function channelEntry(origin, channelSlug) { const corpus = await getJson(`${origin}/corpus.json`); @@ -368,7 +374,7 @@ export function createCueSource({ ); } - async function checkChannelReachable(channelSlug) { + async function checkChannelReachable(channelsDir, channelSlug) { const channelDir = path.join(channelsDir, channelSlug); const dataDir = path.join(channelDir, "data"); const fail = (detail) => { @@ -441,21 +447,41 @@ export function createCueSource({ if (!link.isDirectory()) fail(`${dataDir} is neither a directory nor a symlink`); } - function assertChannelReachable(channelSlug) { - // One check per channel per run, cached as a promise so a rejection replays - // for every clip of that channel instead of re-statting for each. - let pending = checkedChannels.get(channelSlug); + function assertChannelReachable(channelsDir, channelSlug) { + // One check per channel per tree per run, cached as a promise so a rejection + // replays for every clip of that channel instead of re-statting for each. + const key = `${channelsDir}\u0000${channelSlug}`; + let pending = checkedChannels.get(key); if (!pending) { - pending = checkChannelReachable(channelSlug); - checkedChannels.set(channelSlug, pending); + pending = checkChannelReachable(channelsDir, channelSlug); + checkedChannels.set(key, pending); } return pending; } async function fromLocal(channelSlug, videoId) { + // The project's tree first; a later layer (the corpus behind it) only when that one has no cue file for it. + let lastErr = null; + for (let i = 0; i < layers.length; i += 1) { + try { + const got = await fromLocalIn(layers[i], channelSlug, videoId); + if (i > 0 && !saidFallback) { + saidFallback = true; + log(`cues: ${channelSlug}/${videoId} is not under ${layers[0]} -- read from ${layers[i]} (the corpus behind the project's channels tree; said once per run)`); + } + return got; + } catch (err) { + if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") throw err; + lastErr = err; + } + } + throw lastErr; + } + + async function fromLocalIn(channelsDir, channelSlug, videoId) { // Throws a CueLookupError — which carries no `code`, so `load`'s ENOENT // fallback rethrows it rather than reaching for the archive. - await assertChannelReachable(channelSlug); + await assertChannelReachable(channelsDir, channelSlug); // 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"); diff --git a/umtool/report-to-video/sources.mjs b/umtool/report-to-video/sources.mjs @@ -60,6 +60,7 @@ // root arrives as an argument (see umtool/lib/paths.mjs on why that matters to // the Next build). import path from "node:path"; +import { stat } from "node:fs/promises"; import { AUDIO_ONLY_PLATFORMS, CORPUS_TIERS, @@ -182,6 +183,15 @@ export const TIERS = [{ kind: "raw-cache", windows: rawCacheWindows }, ...CORPUS * windowStart: number, windowEnd: number, height?: number }>} */ export async function resolveLocalSource(want, config = {}) { + const hit = await resolveLocalSourceIn(want, config); + // The corpus behind the project's channels tree (channelsLayersFor): its windows when the project's has none. + if (hit || !config.fallbackChannelsDir || config.exact) return hit; + const behind = await resolveLocalSourceIn(want, { ...config, channelsDir: config.fallbackChannelsDir, kinds: (config.kinds ?? CORPUS_TIERS.map((t) => t.kind)).filter((k) => k !== "raw-cache") }); + if (behind) noteChannelsFallback("windows", `windows: ${want.slug ?? "?"}/${want.video} ${want.from}-${want.to} is not in ${config.channelsDir} -- read from ${config.fallbackChannelsDir} (the corpus behind the project's channels tree)`, config.log); + return behind; +} + +async function resolveLocalSourceIn(want, config = {}) { const { video, slug = null, from, to } = want; const { rawDir = null, channelsDir = null, exact = false, probe, kinds = null, audio = false } = config; if (!video || !Number.isFinite(from) || !Number.isFinite(to)) return null; @@ -216,7 +226,13 @@ export async function resolveLocalSource(want, config = {}) { * Not the audio tier: many transcribed videos keep their sound, and a * bench that called each of those "fetched" would never offer a fetch. */ -export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource }) { +export async function corpusWindowsOf({ video, slug, channelsDir, probe = ffprobeSource, fallbackChannelsDir = null }) { + const own = await corpusWindowsIn({ video, slug, channelsDir, probe }); + if (own.length || !fallbackChannelsDir) return own; + return corpusWindowsIn({ video, slug, channelsDir: fallbackChannelsDir, probe }); +} + +async function corpusWindowsIn({ video, slug, channelsDir, probe }) { const ctx = { video, slug, channelsDir, probe }; const out = []; for (const tier of CORPUS_TIERS) { @@ -245,3 +261,65 @@ export function channelsDirFor(dir, manifest, { shadowExists = false, fallback = if (shadowExists) return path.join(/* turbopackIgnore: true */ dir, SHADOW_CHANNELS); return fallback; } + +// ---- the shadow first, the corpus after ---------------------------------------- +// +// A project's own channels tree (`provenance.channelsDir`, a `.shadow-channels/`) +// is read FIRST; the real corpus (`fallback`, transcripts/channels) is read for +// anything the shadow lacks -- a channel added to the corpus after the shadow +// was made, a post, a cue file, a cached window (rev 9, 6 Nov: the cut lane had +// to copy three channels' posts, three cue files and the editor's windows into +// the shadow, and render with CHANNELS_DIR=<shadow>). Each kind that falls back +// says so once per run. Off: `provenance.channelsFallback: false`, or +// CHANNELS_FALLBACK=0 -- the shadow alone, as before. + +/** The environment switch that turns the corpus fallback off ("0"). */ +export const CHANNELS_FALLBACK_ENV = "CHANNELS_FALLBACK"; + +/** Is the corpus fallback on for this manifest (default yes)? */ +export function channelsFallbackOn(manifest, env = process.env) { + if (String(env?.[CHANNELS_FALLBACK_ENV] ?? "") === "0") return false; + return manifest?.provenance?.channelsFallback !== false; +} + +/** + * The channels trees a project reads, in order: its own (channelsDirFor) and, + * when that is not the corpus and the fallback is on, the corpus after it. + * + * @returns {string[]} + */ +export function channelsLayersFor(dir, manifest, { shadowExists = false, fallback = null, env = process.env } = {}) { + const first = channelsDirFor(dir, manifest, { shadowExists, fallback }); + if (!first) return fallback ? [fallback] : []; + const out = [first]; + if (fallback && path.resolve(fallback) !== path.resolve(first) && channelsFallbackOn(manifest, env)) out.push(fallback); + return out; +} + +const fallbackNoted = new Set(); + +/** Say ONCE per run per kind that a kind was read from the corpus behind the shadow. */ +export function noteChannelsFallback(kind, line, log = (m) => process.stderr.write(`${m}\n`)) { + if (fallbackNoted.has(kind)) return false; + fallbackNoted.add(kind); + log(line); + return true; +} + +/** (Tests: forget what was said.) */ +export const resetChannelsFallbackNotes = () => fallbackNoted.clear(); + +/** + * The first of `layers` that holds `<layer>/<...rel>` -- or the first layer + * when none does (its own "not there" is the error a caller reports). A layer + * after the first noted once for `kind`. + */ +export async function firstLayerWith(layers, rel, { kind = "files", log } = {}) { + for (let i = 0; i < layers.length; i += 1) { + if (await stat(path.join(/* turbopackIgnore: true */ layers[i], ...rel)).then(() => true, () => false)) { + if (i > 0) noteChannelsFallback(kind, `${kind}: ${rel.join("/")} is not in ${layers[0]} -- read from ${layers[i]} (the corpus behind the project's channels tree; provenance.channelsFallback: false or ${CHANNELS_FALLBACK_ENV}=0 turns this off)`, log); + return layers[i]; + } + } + return layers[0] ?? null; +}