Archilyzer · Source

archilyzer

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

commit 7de532cee1d3bedcb5bff0cf314e8ff9539fe8be
parent 0322c2868ab9d58a8f1a2fc11023f38e7d186111
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:18:51 -0500

umtool: the usage index -- where an ingredient is used (lib/ingredients/usedIn.mjs, lane L5)

The reverse of a manifest's timeline: for one recording, every project clip that cuts from it, in the
working draft and in each saved version (takes/<id>/base.manifest.json, or a legacy rendered take's
takes/<id>/video.manifest.json). Cached in <REPORTS_ROOT>/.umtool/usage-index.json (UMTOOL_USAGE_INDEX_FILE
overrides) and rebuilt incrementally by each manifest's mtime and size; a project the walk no longer finds
drops out. A Rumble clip citing the embed id and one citing the folder slug collapse to one ingredient,
keyed by the directory id (resolveVideoDirId). Unit tests: incremental rebuild, a deleted project, the
Rumble collapse, write: false.

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

Diffstat:
Mpackage.json | 2+-
Aumtool/lib/ingredients/usedIn.mjs | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/usedIn.test.mjs | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 389 insertions(+), 1 deletion(-)

diff --git a/package.json b/package.json @@ -24,7 +24,7 @@ "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", - "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs", + "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -0,0 +1,250 @@ +// WHERE AN INGREDIENT IS USED (umtool redesign, lane L5: the ingredient life-cycle rail). +// +// The reverse of a manifest's timeline: for one recording -- `<channel>/<video>`, +// the corpus's `channels/<ch>/data/<video>/` -- every project clip that cuts +// from it, in the working draft and in each saved version. +// +// <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] } }, +// byIngredient: { "<ch>/<dir id>": [Row] } } +// +// Use { ch, video, siteVideo?, clipId, start, end, cutStart, cutEnd, quote? } one clip of one manifest +// Row { project, clipId, start, end, cutStart, cutEnd, quote, inDraft, +// versions: [{ id, kind, start, end, cutStart, cutEnd }] } one clip of one project +// +// WHICH MANIFESTS. A project's video.manifest.json is the draft (lane L3); each +// take's frozen form is `takes/<id>/base.manifest.json` (a saved version) or, +// for a legacy rendered take, the `takes/<id>/video.manifest.json` the render +// wrote. A take with neither (a patch that follows the draft) is the draft's +// clips again and adds nothing here. +// +// INCREMENTAL by each manifest's mtime and size: an unchanged file's clips are +// read back from the cache, a changed one is parsed again, and a file the walk +// no longer finds (a project deleted, a take pruned) is dropped with it. The +// walk itself is walkProjects (a project is a leaf: nothing under out/ is ever +// listed), so a rebuild with nothing changed is a readdir per folder and a stat +// per manifest. +// +// ONE KEY PER RECORDING. A Rumble recording has two ids -- the folder slug the +// corpus keeps it under and the embed id the archive serves (AGENTS.md); a clip +// may cite either. Each clip's key is the DIRECTORY id (`resolveVideoDirId`: +// an embed id with no directory is looked up in the channel's metadata), so +// the two collapse to one ingredient. Every other id costs nothing to resolve. +// +// Never written under CHANNELS_DIR: the corpus is read, the index lives in +// umtool's own state dir. Plain ESM: `umtool ingredient` runs it under bare node. +import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { walkProjects } from "../projects/walk.mjs"; + +export const USAGE_INDEX_FORMAT = "umtool-usage-index"; +export const USAGE_INDEX_VERSION = 1; +export const USAGE_INDEX_ENV = "UMTOOL_USAGE_INDEX_FILE"; +const MANIFEST = "video.manifest.json"; +const BASE = "base.manifest.json"; +const TAKES = "takes"; +const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const num = (v) => (fin(v) ? v : null); + +/** The cache file for a reports root. */ +export function usageIndexPath(reportsRoot, env = process.env) { + const o = env?.[USAGE_INDEX_ENV]; + if (o) return path.resolve(o); + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "usage-index.json"); +} + +/** `<ch>/<id>`. */ +export const ingredientKey = (ch, id) => `${ch}/${id}`; + +/** + * The clips of one manifest, as uses. A clip with no recording (a local `src` + * file, no video) is no ingredient of the corpus. + * @param {Record<string, any> | null} m + * @returns {{ ch: string, video: string, siteVideo?: string, clipId: string, start: number | null, end: number | null, cutStart: number | null, cutEnd: number | null, quote?: string }[]} + */ +export function usesOfManifest(m) { + const out = []; + for (const e of Array.isArray(m?.timeline) ? m.timeline : []) { + if (e?.type !== "clip" || !e.id) continue; + const ch = typeof e.channel === "string" && e.channel ? e.channel : m?.provenance?.channelSlug; + const video = e.video == null ? "" : String(e.video); + if (!ch || !video || e.src) continue; + out.push({ + ch: String(ch), + video, + ...(typeof e.siteVideo === "string" && e.siteVideo ? { siteVideo: e.siteVideo } : {}), + clipId: String(e.id), + start: num(e.start), + end: num(e.end), + cutStart: num(e.cutStart), + cutEnd: num(e.cutEnd), + ...(typeof e.quote === "string" && e.quote ? { quote: e.quote.slice(0, 300) } : {}), + }); + } + return out; +} + +/** + * The manifests a project holds: its draft, then each take's frozen form. + * @param {string} dir + * @returns {Promise<{ version: string, kind: "draft" | "version" | "rendered", file: string }[]>} + */ +export async function manifestFilesOf(dir) { + const out = [{ version: "draft", kind: /** @type {const} */ ("draft"), file: path.join(dir, MANIFEST) }]; + const takes = await readdir(path.join(dir, TAKES), { withFileTypes: true }).catch(() => []); + for (const t of takes.sort((a, b) => a.name.localeCompare(b.name))) { + if (!TAKE_ID.test(t.name)) continue; + if (!t.isDirectory() && !t.isSymbolicLink()) continue; + const td = path.join(dir, TAKES, t.name); + const base = path.join(td, BASE); + if (await stat(base).then((s) => s.isFile(), () => false)) { + out.push({ version: t.name, kind: "version", file: base }); + continue; + } + const rendered = path.join(td, MANIFEST); + if (await stat(rendered).then((s) => s.isFile(), () => false)) out.push({ version: t.name, kind: "rendered", file: rendered }); + } + return out; +} + +/** + * Build (or bring up to date) the index. + * + * @param {{ reportsRoot: string, channelsDir: string | null, previous?: Record<string, any> | null, + * walk?: (root: string) => Promise<{ id: string, dir: string, kind: string }[]>, + * resolveDir?: (ch: string, video: string) => Promise<string>, now?: () => Date }} o + * @returns {Promise<{ index: Record<string, any>, stats: { manifests: number, parsed: number, reused: number, dropped: number, projects: number } }>} + */ +export async function buildUsageIndex({ reportsRoot, channelsDir, previous = null, walk = walkProjects, resolveDir = null, now = () => new Date() }) { + const prevFiles = previous?.format === USAGE_INDEX_FORMAT && previous?.version === USAGE_INDEX_VERSION && previous.files && typeof previous.files === "object" ? previous.files : {}; + const resolve = + resolveDir ?? + (async (ch, video) => (channelsDir ? await resolveVideoDirId(channelsDir, ch, video).catch(() => video) : video)); + const memo = new Map(); + 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 projects = (await walk(reportsRoot)).filter((p) => p.kind === "report-video" || p.kind === undefined); + const files = {}; + let parsed = 0; + let reused = 0; + for (const p of projects) { + for (const mf of await manifestFilesOf(p.dir)) { + const st = await stat(mf.file).catch(() => null); + if (!st?.isFile()) continue; + const mtimeMs = Math.round(st.mtimeMs); + const was = prevFiles[mf.file]; + if (was && was.mtimeMs === mtimeMs && was.size === st.size && was.project === p.id && was.version === mf.version && Array.isArray(was.clips)) { + files[mf.file] = was; + reused += 1; + continue; + } + let m = null; + try { + m = JSON.parse(await readFile(mf.file, "utf8")); + } catch { + m = null; + } + parsed += 1; + files[mf.file] = { mtimeMs, size: st.size, project: p.id, version: mf.version, kind: mf.kind, clips: usesOfManifest(m) }; + } + } + const dropped = Object.keys(prevFiles).filter((f) => !(f in files)).length; + + // Aggregate: one row per (ingredient, project, clip), its versions beside it. + /** @type {Map<string, Map<string, Record<string, any>>>} */ + const by = new Map(); + for (const f of Object.values(files)) { + for (const u of f.clips) { + const key = ingredientKey(u.ch, await dirIdOf(u.ch, u.video)); + if (!by.has(key)) by.set(key, new Map()); + const rows = /** @type {Map<string, Record<string, any>>} */ (by.get(key)); + const rk = `${f.project}\u0000${u.clipId}`; + let row = rows.get(rk); + if (!row) { + row = { project: f.project, clipId: u.clipId, start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd, quote: u.quote ?? null, inDraft: false, versions: [], cites: [] }; + rows.set(rk, row); + } + if (!row.cites.includes(u.video)) row.cites.push(u.video); + if (u.siteVideo && !row.cites.includes(u.siteVideo)) row.cites.push(u.siteVideo); + if (f.kind === "draft") { + Object.assign(row, { start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd, quote: u.quote ?? null, inDraft: true }); + } else { + row.versions.push({ id: f.version, kind: f.kind, start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd }); + } + } + } + /** @type {Record<string, Record<string, any>[]>} */ + const byIngredient = {}; + for (const [key, rows] of [...by.entries()].sort(([a], [b]) => a.localeCompare(b))) { + byIngredient[key] = [...rows.values()] + .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 }; + return { index, stats: { manifests: Object.keys(files).length, parsed, reused, dropped, projects: projects.length } }; +} + +/** The cached index, or null. */ +export async function readUsageIndex(file) { + try { + const j = JSON.parse(await readFile(file, "utf8")); + return j?.format === USAGE_INDEX_FORMAT ? j : null; + } catch { + return null; + } +} + +async function writeUsageIndex(file, index) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(index) + "\n", "utf8"); + await rename(tmp, file); +} + +/** + * The index, brought up to date and cached. `write: false` reads the cache but + * never writes it (a read-only look at somebody else's tree). + * + * @param {{ reportsRoot: string, channelsDir: string | null, file?: string, write?: boolean, walk?: any, resolveDir?: any }} o + */ +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); + if (write && changed) await writeUsageIndex(file, built.index).catch(() => {}); + return { ...built, file, written: write && changed }; +} + +/** + * The rows for one ingredient. `id` may be either Rumble id: it is resolved to + * its directory first (`dirId`, when the caller has it already). + * @param {Record<string, any>} index + * @param {string} ch + * @param {string} dirId + */ +export function usesOf(index, ch, dirId) { + return index?.byIngredient?.[ingredientKey(ch, dirId)] ?? []; +} + +/** The span a row plays: its cut, else its extent. */ +export const playedOf = (r) => ({ from: fin(r?.cutStart) ? r.cutStart : r?.start ?? null, to: fin(r?.cutEnd) ? r.cutEnd : r?.end ?? null }); + +/** Does [a, b] overlap [from, to]? */ +export const overlaps = (a, b, from, to) => fin(a) && fin(b) && fin(from) && fin(to) && a < to && b > from; + +/** Only the rows a window serves: those whose played span (in any version) overlaps it. */ +export function rowsInWindow(rows, win) { + if (!win) return rows; + return rows.filter((r) => { + const spans = [playedOf(r), ...r.versions.map(playedOf)]; + return spans.some((s) => overlaps(s.from, s.to, win.from, win.to)); + }); +} diff --git a/umtool/lib/ingredients/usedIn.test.mjs b/umtool/lib/ingredients/usedIn.test.mjs @@ -0,0 +1,138 @@ +// node --test umtool/lib/ingredients/usedIn.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { buildUsageIndex, loadUsageIndex, manifestFilesOf, rowsInWindow, usesOf, usesOfManifest } from "./usedIn.mjs"; + +const clip = (id, video, start, end, extra = {}) => ({ type: "clip", id, video, start, end, ...extra }); +const manifest = (timeline, channelSlug = "chan") => ({ schemaVersion: 1, provenance: { channelSlug }, render: {}, timeline }); + +async function project(root, rel, m, takes = {}) { + const dir = path.join(root, rel); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m)); + for (const [id, t] of Object.entries(takes)) { + await mkdir(path.join(dir, "takes", id), { recursive: true }); + await writeFile(path.join(dir, "takes", id, "take.json"), "{}"); + if (t.base) await writeFile(path.join(dir, "takes", id, "base.manifest.json"), JSON.stringify(t.base)); + if (t.rendered) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(t.rendered)); + } + return dir; +} + +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), "usedin-")); + const reports = path.join(root, "reports"); + const channels = path.join(root, "channels"); + await mkdir(reports, { recursive: true }); + // A Rumble channel: its folder is the URL slug v7slug1, its archive (embed) id v7emb01. + await mkdir(path.join(channels, "rumch", "data", "v7slug1"), { recursive: true }); + await writeFile(path.join(channels, "rumch", "config.json"), JSON.stringify({ platform: "rumble" })); + await writeFile(path.join(channels, "rumch", "data", "v7slug1", "metadata.info.json"), JSON.stringify({ id: "v7emb01", title: "t" })); + return { root, reports, channels }; +} + +test("usesOfManifest: clips with a recording, the provenance's channel as the default", () => { + const u = usesOfManifest(manifest([clip("a", "vid", 1, 2), { type: "card", id: "k" }, clip("b", "", 1, 2), clip("c", "v2", 3, 4, { channel: "other", cutStart: 3.5 }), clip("d", "v3", 1, 2, { src: "x.mp4" })])); + assert.deepEqual(u.map((x) => `${x.ch}/${x.video}#${x.clipId}`), ["chan/vid#a", "other/v2#c"]); + assert.equal(u[1].cutStart, 3.5); +}); + +test("manifestFilesOf: the draft, a version's base, a legacy rendered take; a patch-only take adds nothing", async () => { + const { root, reports } = await fixture(); + try { + const dir = await project(reports, "f/p", manifest([]), { v1: { base: manifest([]) }, a2: { rendered: manifest([]) }, b3: {} }); + const files = await manifestFilesOf(dir); + assert.deepEqual(files.map((f) => `${f.version}:${f.kind}:${path.basename(f.file)}`), ["draft:draft:video.manifest.json", "a2:rendered:video.manifest.json", "v1:version:base.manifest.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("two projects, a version, one row per project clip with its versions", async () => { + const { root, reports, channels } = await fixture(); + try { + await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20), clip("a2", "vid", 100, 110, { cutStart: 102, cutEnd: 108 })]), { + v1: { base: manifest([clip("a1", "vid", 11, 19)]) }, + }); + await project(reports, "f/b", manifest([clip("b1", "vid", 15, 25)])); + const { index, stats } = await buildUsageIndex({ reportsRoot: reports, channelsDir: channels }); + assert.equal(stats.projects, 2); + assert.equal(stats.manifests, 3); + const rows = usesOf(index, "chan", "vid"); + assert.deepEqual(rows.map((r) => `${r.project}#${r.clipId}`), ["f/a#a1", "f/a#a2", "f/b#b1"]); + const a1 = rows[0]; + assert.equal(a1.inDraft, true); + assert.equal(a1.start, 10); + assert.deepEqual(a1.versions.map((v) => `${v.id}:${v.kind}:${v.start}`), ["v1:version:11"]); + // A window 100-130 serves a2 only; 0-30 serves a1 and b1. + assert.deepEqual(rowsInWindow(rows, { from: 100, to: 130 }).map((r) => r.clipId), ["a2"]); + assert.deepEqual(rowsInWindow(rows, { from: 0, to: 30 }).map((r) => r.clipId), ["a1", "b1"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("incremental: an unchanged manifest is reused, a changed one parsed again, a deleted project drops out", async () => { + const { root, reports, channels } = await fixture(); + const file = path.join(root, "state", "usage-index.json"); + try { + const a = await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20)])); + await project(reports, "f/b", manifest([clip("b1", "vid", 15, 25)])); + const first = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file }); + assert.equal(first.stats.parsed, 2); + assert.equal(first.written, true); + + const again = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file }); + assert.deepEqual([again.stats.parsed, again.stats.reused, again.written], [0, 2, false]); + + // f/a's draft changes (a new mtime): only it is read again. + await writeFile(path.join(a, "video.manifest.json"), JSON.stringify(manifest([clip("a1", "vid", 10, 20), clip("a9", "vid", 50, 55)]))); + const later = new Date(Date.now() + 5000); + await utimes(path.join(a, "video.manifest.json"), later, later); + const changed = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file }); + assert.deepEqual([changed.stats.parsed, changed.stats.reused], [1, 1]); + assert.deepEqual(usesOf(changed.index, "chan", "vid").map((r) => r.clipId), ["a1", "a9", "b1"]); + + // f/b is deleted: its rows go with it. + await rm(path.join(reports, "f", "b"), { recursive: true, force: true }); + const gone = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file }); + assert.equal(gone.stats.dropped, 1); + assert.deepEqual(usesOf(gone.index, "chan", "vid").map((r) => `${r.project}#${r.clipId}`), ["f/a#a1", "f/a#a9"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("Rumble: a clip citing the embed id and one citing the folder slug are ONE ingredient, keyed by the folder", async () => { + const { root, reports, channels } = await fixture(); + try { + await project(reports, "f/emb", manifest([clip("e1", "v7emb01", 10, 20)], "rumch")); + await project(reports, "f/slug", manifest([clip("s1", "v7slug1", 30, 40, { siteVideo: "v7emb01" })], "rumch")); + const { index } = await buildUsageIndex({ reportsRoot: reports, channelsDir: channels }); + assert.deepEqual(Object.keys(index.byIngredient), ["rumch/v7slug1"]); + const rows = usesOf(index, "rumch", "v7slug1"); + assert.deepEqual(rows.map((r) => `${r.project}#${r.clipId}`), ["f/emb#e1", "f/slug#s1"]); + assert.deepEqual(rows[0].cites, ["v7emb01"]); + assert.deepEqual(rows[1].cites, ["v7slug1", "v7emb01"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("write: false never writes the cache", async () => { + const { root, reports, channels } = await fixture(); + const file = path.join(root, "state", "usage-index.json"); + try { + await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20)])); + const r = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file, write: false }); + assert.equal(r.written, false); + assert.equal(usesOf(r.index, "chan", "vid").length, 1); + const { readUsageIndex } = await import("./usedIn.mjs"); + assert.equal(await readUsageIndex(file), null); + } finally { + await rm(root, { recursive: true, force: true }); + } +});