// 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//data//`, and optionally one clip window of // it (`?window=-`). Nine stages, each read from files that already exist: // // found data//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/-.{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 /quote-check.json rows for those clips (rowIsCurrent) // rendered /takes//render.json for the versions holding them, out/segments/.cut.json // published /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 { logicalEntries } from "yt-dlp-transcript-common/lib/storedText-read.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 { listTakes } from "../report/takes.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}, 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, `-` 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); } // LOGICAL (common/lib/storedText-read.mjs): a caption stored as `.zst` is a caption. const vtts = logicalEntries(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 = logicalEntries(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, savedAway = null, 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)", savedAway && `the saved whole recording does not answer (${savedAway}): its drive is not mounted, so nothing cuts from it now`, ].filter(Boolean); return { key: "windows", label: "Windows", pill: uncovered.length || desyncedN || savedAway ? pill("warn") : live.length ? pill("count", live.length) : savedWhole ? pill("ok") : pill("none"), line: live.length || uncovered.length || desyncedN || savedWhole || savedAway ? bits.join(", ") : "No windows cut yet", windows: annotated, uncovered, savedWhole: !!savedWhole, savedUnreachable: savedAway, 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 = []; const takesOf = new Map(); for (const r of rows) { const dir = dirOf(r.project); // A take rendered before render.json existed is known by its preview (listTakes: the file and its size). if (!takesOf.has(r.project)) takesOf.set(r.project, new Map(((await listTakes(dir).catch(() => null))?.takes ?? []).map((t) => [t.id, t]))); for (const v of r.versions) { const rec = await readRenderRecord(path.join(dir, "takes", v.id)).catch(() => null); const take = takesOf.get(r.project).get(v.id) ?? null; const state = rec?.state ?? (take?.previewSize ? "done" : null); const seconds = fin(rec?.seconds) ? rec.seconds : fin(take?.seconds) ? take.seconds : 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, label: take?.label ?? null, state, seconds, endedAt: rec?.endedAt ?? rec?.finishedAt ?? take?.builtAt ?? 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" : out.every((o) => o.state === null) ? `${out.length} link${out.length === 1 ? "" : "s"} to it, never checked` : 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 | 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, savedAway: pointer && !savedWhole ? pointer.path : null, 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" ? "!" : "—");