Archilyzer · Source

archilyzer

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

commit b44826296784176fac168d4a3e60c2b589c521b0
parent e9877855e779c7bce967ee8da72c838a87a5b96c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 21:35:12 -0500

Merge lane/ingredient-rail: an ingredient's life cycle -- one recording or clip window across nine stages, Found to Published, with each stage's action (operator, 9 Nov: "the stage rail could be good for viewing a downloaded clip or other video ingredient to see its entire life cycle")

Redesign L5. /ingredients/<channel>/<id> (?window=, ?stage=) and `umtool ingredient`: Found, Downloaded,
Transcribed, Clock, Windows, Used in, Checked, Rendered, Published, each a pill and a panel, read-only over the corpus
(big files by their heads only). Used in comes from a usage index over every project's draft and versions
(<REPORTS_ROOT>/.umtool/usage-index.json, incremental; a Rumble embed id and its folder are one ingredient). Actions are
two steps (plan says what, what it costs and which queue; start must carry the plan's key), same-origin only, and an
unreachable media drive reads "Not now", never "not downloaded". Entry points: the clip bench, Play's row, and the
editor's video page "Open in umtool".

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

Diffstat:
Meditor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx | 9++++++---
Mpackage.json | 2+-
Aumtool/app/api/ingredients/action/route.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/ingredients/[channel]/[id]/page.tsx | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 5+++++
Aumtool/components/ingredients/IngredientRail.tsx | 528+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/BenchShell.tsx | 8++++++++
Mumtool/components/projects/review/PlayCut.tsx | 16+++++++++++++++-
Mumtool/docs/cli.md | 1+
Mumtool/docs/knobs.md | 34++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub-fetch-windows.mjs | 3++-
Mumtool/e2e/fixtures/editor-stub.mjs | 4+++-
Aumtool/e2e/fixtures/ingredient-rail-fixture.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 5+++++
Aumtool/e2e/ingredient-rail.spec.ts | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.test.mjs | 6++++++
Mumtool/lib/hrefs.ts | 12++++++++++++
Aumtool/lib/ingredients.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/actions.mjs | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/actions.test.mjs | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/cli.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/heads.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/stages.mjs | 570+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/stages.test.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/usedIn.mjs | 276+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/ingredients/usedIn.test.mjs | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/benchData.ts | 6+++++-
Mumtool/lib/report/fetchWindows.mjs | 3+++
Mumtool/lib/report/playView.mjs | 2++
29 files changed, 2962 insertions(+), 8 deletions(-)

diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -106,7 +106,10 @@ type Props = { nextHref?: string; position?: { index: number; total: number }; // The umtool front door, when UMTOOL_URL is set on the editor. One link: - // "open in umtool" scaffolds a report video from this exact video. + // "open in umtool" opens this recording's life cycle there + // (/ingredients/<slug>/<id>: found, downloaded, transcribed, its windows, + // every cut that uses it, checked, rendered, published), where "make a + // video from it" scaffolds a report video from it. umtoolUrl?: string | null; // The transcription pool is paused (getWorkerPool().isPaused(), read by the // page): the Transcribe rows offer "Transcribe now (workers paused)". @@ -208,13 +211,13 @@ export function VideoPanel({ {umtoolUrl && ( <div className="text-sm"> <a - href={`${umtoolUrl}/?from=${encodeURIComponent(`${slug}/${videoId}`)}`} + href={`${umtoolUrl}/ingredients/${encodeURIComponent(slug)}/${encodeURIComponent(videoId)}`} className="underline" data-umtool-link > Open in umtool </a> - <span className="text-muted-foreground"> — start a report video from this recording</span> + <span className="text-muted-foreground"> — this recording&apos;s life cycle: its windows, every cut that uses it, what was checked, rendered and published</span> </div> )} <PipelineStatusStrip 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/app/api/ingredients/action/route.ts b/umtool/app/api/ingredients/action/route.ts @@ -0,0 +1,67 @@ +import { CHANNELS_DIR, REPORTS_ROOT } from "@/lib/paths"; +import { jobView, runningJob, startJob } from "@/lib/jobs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; +import { EditorError, editorConfig } from "@/lib/report/fetchWindows.mjs"; +import { ActionError, parseClipList, planAction, quoteCheckArgv, startAction } from "@/lib/ingredients/actions.mjs"; +import { resolveProject } from "@/lib/projects/core.mjs"; + +export const dynamic = "force-dynamic"; + +// THE INGREDIENT RAIL'S ACTIONS (lane L5; lib/ingredients/actions.mjs): a stage's one click, in two steps. +// +// POST { action, ch, id, step: "plan", project?, clips?, window?, fix? } +// -> { action, what, cost: "network" | "gpu" | "disk" | null, queue, start: { route, body }, plan? } +// what the action will do, what it costs and which queue it lands on (the editor's own dry run for +// fetch-windows and persist-videos); the page shows it and asks +// POST { ...start.body, step: "start" } +// persist | transcribe | fetch | evict -> { ok, action, jobIds, message } the editor's ops, asked here +// quote-check -> 202 { ok, job } `umtool quote-check` on the job runner +// (links: the plan's start names /api/report/links, umtool's own link check) +// +// The token never reaches the browser; the editor decides queues, pacing and whole-recording downloads. +const headers = { "cache-control": "no-store" }; + +export async function POST(request: Request) { + // Another site's page may not start a download, a transcription or an evict: a cross-site or foreign-Origin + // POST is refused (sameOrigin.mjs), and the body must be JSON -- which a no-cors form post cannot send. + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403, headers }); + if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? "")) return Response.json({ error: "the body must be application/json" }, { status: 415, headers }); + const refused = refuseCaller(request, "/api/ingredients/action"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers }); + const req = { + action: String(b.action ?? ""), + ch: String(b.ch ?? ""), + id: String(b.id ?? ""), + ...(b.project !== undefined ? { project: String(b.project) } : {}), + ...(b.clips !== undefined ? { clips: b.clips as string[] } : {}), + ...(b.window !== undefined ? { window: String(b.window) } : {}), + ...(b.fix === true ? { fix: true } : {}), + ...(typeof b.key === "string" ? { key: b.key } : {}), + }; + const ctx = { cfg: editorConfig(), reportsRoot: REPORTS_ROOT, channelsDir: CHANNELS_DIR }; + try { + if (b.step === "plan") return Response.json(await planAction(req, ctx), { headers }); + if (b.step !== "start") return Response.json({ error: 'step is "plan" or "start"' }, { status: 400, headers }); + if (req.action === "quote-check") { + const r = await resolveProject(String(req.project ?? ""), REPORTS_ROOT); + if (!r?.project) return Response.json({ error: `no project "${req.project}"` }, { status: 404, headers }); + const clips = parseClipList(req.clips) as string[]; + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind}) — check the quotes when it is done`, running: jobView(running) }, { status: 409, headers }); + const argv = quoteCheckArgv(UMTOOL_DIR, r.project.id, clips); + const job = startJob(`quote-check ${r.project.id} ${clips.join(",")}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quote check: ${clips.join(", ")} (${r.project.id})`, argv, timeoutMs: 60 * 60_000 }], { project: r.project.id }); + return Response.json({ ok: true, action: "quote-check", job: jobView(job), jobIds: [job.id], message: `quote check started (${job.id})` }, { status: 202, headers }); + } + if (req.action === "links") return Response.json({ error: "a link check starts at /api/report/links" }, { status: 400, headers }); + return Response.json(await startAction(req, ctx), { headers }); + } catch (e) { + if (e instanceof ActionError) return Response.json({ error: e.message }, { status: (e as ActionError & { status: number }).status, headers }); + if (e instanceof EditorError) return Response.json({ error: e.message }, { status: (e as EditorError & { status: number }).status, headers }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} diff --git a/umtool/app/ingredients/[channel]/[id]/page.tsx b/umtool/app/ingredients/[channel]/[id]/page.tsx @@ -0,0 +1,50 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import AppShell from "@/components/shell/AppShell"; +import IngredientRail from "@/components/ingredients/IngredientRail"; +import { readIngredient } from "@/lib/ingredients"; +import { isChannelSlug, isVideoId } from "@/lib/ingredients/stages.mjs"; +import { editorConfig } from "@/lib/report/fetchWindows.mjs"; +import { workHref } from "@/lib/hrefs"; + +export const dynamic = "force-dynamic"; + +// ONE INGREDIENT'S LIFE CYCLE (lane L5; operator, 9 Nov 2026): /ingredients/<channel>/<video>[?window=<from>-<to>] +// [&stage=<key>]. A recording of the corpus across its nine stages -- found, downloaded, transcribed, clock, +// windows, used in, checked, rendered, published -- each read from the files that exist +// (lib/ingredients/stages.mjs; `umtool ingredient` prints the same). Either Rumble id finds it. Read-only over +// the corpus; each stage's action goes through the editor's or umtool's own (app/api/ingredients/action). + +type Params = { channel: string; id: string }; +type Search = { window?: string; stage?: string }; + +export async function generateMetadata({ params }: { params: Promise<Params> }): Promise<Metadata> { + const { channel, id } = await params; + return { title: `${channel}/${id} · life cycle · umtool` }; +} + +export default async function IngredientPage({ params, searchParams }: { params: Promise<Params>; searchParams: Promise<Search> }) { + const { channel, id } = await params; + // Next hands the segments over decoded already: decoding again would turn a literal % into something else. + const ch = channel; + const vid = id; + if (!isChannelSlug(ch) || !isVideoId(vid)) notFound(); + const search = await searchParams; + const data = await readIngredient(ch, vid, typeof search.window === "string" ? search.window : null); + const keys = data.stages.map((s) => s.key); + const firstWarn = data.stages.find((s) => s.pill.kind === "warn")?.key; + const initial = + typeof search.stage === "string" && keys.includes(search.stage) ? search.stage : data.focus ? "windows" : (firstWarn ?? (data.stages[5].rows.length ? "used" : "downloaded")); + const editor = editorConfig(); + return ( + <div className="flex h-full flex-col"> + <AppShell + active="work" + crumbs={[{ href: workHref(), label: "Work" }, { label: ch }, { label: data.title ? `${vid} · ${data.title}` : vid }]} + /> + <main className="deck-main flex-1 p-4" data-ingredient-page=""> + <IngredientRail data={data} initialStage={initial} editorUrl={editor.url || null} /> + </main> + </div> + ); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -139,6 +139,7 @@ // repeats <project> [--match id|file|audio] · combo <project> [<item>] k=v|off the combo counter // attach <project> [<item>…|--all] a capture's media onto post items that carry none // umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel +// umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] a recording's life cycle, nine stages (/ingredients) import process from "node:process"; import { PROJECT_KINDS, @@ -1138,6 +1139,8 @@ function usage() { " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;", " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's", " the Posts table's writer (updatePosts); <post> is x-<postId> or the bare <postId>", + " umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] one recording's life cycle:", + " found, downloaded, transcribed, clock, windows, used in, checked, rendered, published (/ingredients)", "", `reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`, "", @@ -1252,6 +1255,8 @@ const COMMANDS = { posts: async () => process.exit(await (await import("../lib/report/postsCli.mjs")).postsCommand(argv.slice(argv.indexOf("posts") + 1))), // The candidates inbox (UI notes item 14): proposals only -- lib/report/candidatesCli.mjs. candidates: async () => process.exit(await (await import("../lib/report/candidatesCli.mjs")).candidatesCommand(argv.slice(argv.indexOf("candidates") + 1))), + // One recording's life cycle (lane L5, the ingredient rail): lib/ingredients/cli.mjs. + ingredient: async () => process.exit(await (await import("../lib/ingredients/cli.mjs")).ingredientCommand(argv.slice(argv.indexOf("ingredient") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), diff --git a/umtool/components/ingredients/IngredientRail.tsx b/umtool/components/ingredients/IngredientRail.tsx @@ -0,0 +1,528 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { clipBenchHref, createHref, ingredientHref, playHref, projectHref } from "@/lib/hrefs"; +import { researchCasePipelineHref, researchHref } from "@/lib/research/hrefs"; +import type { + CheckedStage, + ClockStage, + DownloadedStage, + FoundStage, + Ingredient, + Pill, + PublishedStage, + RenderedStage, + TranscribedStage, + UsedStage, + WindowsStage, +} from "@/lib/ingredients"; + +// THE INGREDIENT RAIL (lane L5): one recording's nine stages across the top, the selected stage's panel below. +// Each pill is ✓, a count, ! or —; each panel reads its stage's files (lib/ingredients/stages.mjs) and offers +// its one action, which says what it costs and which queue it lands on before it runs. + +const GLYPH = (p: Pill) => (p.kind === "ok" ? "✓" : p.kind === "count" ? String(p.n ?? "") : p.kind === "warn" ? "!" : "—"); +const PILL_CLASS: Record<Pill["kind"], string> = { + ok: "border-seam-2 text-kept", + count: "border-seam-2 text-meter", + warn: "border-doubt text-doubt", + none: "border-seam text-muted-2", +}; + +const hms = (sec: number | null | undefined) => { + if (sec === null || sec === undefined || !Number.isFinite(sec)) return "?"; + const t = Math.max(0, Math.floor(sec)); + 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}`; +}; +const span = (a: number | null | undefined, b: number | null | undefined) => `${hms(a)}–${hms(b)}`; +const mb = (n: number | null | undefined) => (n === null || n === undefined ? "?" : n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : `${(n / 1e6).toFixed(1)} MB`); +const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "—"); + +export default function IngredientRail({ data, initialStage, editorUrl }: { data: Ingredient; initialStage: string; editorUrl: string | null }) { + const [sel, setSel] = useState(initialStage); + const choose = (key: string) => { + setSel(key); + try { + const u = new URL(window.location.href); + u.searchParams.set("stage", key); + window.history.replaceState(null, "", u.toString()); + } catch { + // The address is a convenience. + } + }; + const [found, downloaded, transcribed, clock, windows, used, checked, rendered, published] = data.stages; + const stage = data.stages.find((s) => s.key === sel) ?? data.stages[0]; + const ingredient = { ch: data.ch, id: data.dirId }; + + return ( + <div className="space-y-3" data-ingredient={`${data.ch}/${data.dirId}`}> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[12.5px]" data-ingredient-head=""> + <span className="font-mono text-[13px] font-medium text-text"> + {data.ch}/{data.dirId} + </span> + {data.siteId && ( + <span className="font-mono text-[12px] text-text-2" data-ingredient-site-id={data.siteId} title="a Rumble recording has two ids: its folder (the URL slug) and the embed id the archive serves"> + archive id {data.siteId} + </span> + )} + {data.platform && <span className="text-muted-2">{data.platform}</span>} + {data.duration !== null && <span className="text-muted-2">{hms(data.duration)}</span>} + {data.uploadDate && <span className="text-muted-2">{data.uploadDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")}</span>} + <span className="ml-auto flex flex-wrap items-center gap-x-3 gap-y-1"> + {data.webpageUrl && ( + <a href={data.webpageUrl} target="_blank" rel="noreferrer" className="ink-link"> + its page ↗ + </a> + )} + {editorUrl && data.exists && ( + <a href={`${editorUrl}/channels/${encodeURIComponent(data.ch)}/videos/${encodeURIComponent(data.dirId)}`} target="_blank" rel="noreferrer" className="ink-link" data-ingredient-editor=""> + in the editor ↗ + </a> + )} + <Link href={createHref({ from: `${data.ch}/${data.dirId}` })} prefetch={false} className="ink-link"> + make a video from it + </Link> + </span> + </div> + {data.notes.map((n) => ( + <p key={n} className="m-0 text-[12px] text-doubt-text" data-ingredient-note=""> + {n} + </p> + ))} + {data.focus && ( + <p className="m-0 flex flex-wrap items-center gap-2 text-[12px] text-text-2" data-ingredient-focus={data.focus.name}> + Window <span className="font-mono">{data.focus.name}</span> + {data.focus.found ? "" : " — no such window on disk"} + <span className="text-muted-2">· the stages after Windows show the clips it plays</span> + <Link href={ingredientHref(data.ch, data.id)} prefetch={false} className="ink-link"> + the whole recording + </Link> + </p> + )} + + <ol className="grid grid-cols-3 gap-1 md:grid-cols-9" role="tablist" aria-label="Life cycle" data-ingredient-rail=""> + {data.stages.map((s, i) => ( + <li key={s.key} className="relative flex"> + {i > 0 && <span aria-hidden="true" className="absolute -left-1 top-1/2 hidden h-px w-1 bg-seam-2 md:block" />} + <button + type="button" + role="tab" + aria-selected={s.key === stage.key} + data-stage={s.key} + data-pill={s.pill.kind} + data-pill-text={GLYPH(s.pill)} + onClick={() => choose(s.key)} + title={s.line} + className={cn( + "flex w-full items-center justify-between gap-1 rounded-[3px] border px-1.5 py-1.5 text-left text-[12px] transition-[color,background-color,border-color]", + s.key === stage.key ? "border-muted bg-panel-2 text-text" : "border-seam bg-panel text-text-2 hover:border-seam-2 hover:text-text", + )} + > + <span className="truncate font-medium">{s.label}</span> + <span className={cn("min-w-[1.3rem] shrink-0 rounded-[3px] border px-1 text-center text-[11.5px] font-semibold tabular-nums leading-[18px]", PILL_CLASS[s.pill.kind])}>{GLYPH(s.pill)}</span> + </button> + </li> + ))} + </ol> + + <section className="rounded-[3px] border border-seam bg-panel px-4 py-3" role="tabpanel" data-stage-panel={stage.key} aria-label={stage.label}> + <div className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="micro">{stage.label}</h2> + <p className="m-0 text-[12.5px] text-text" data-stage-line=""> + {stage.line} + </p> + </div> + {stage.key === "found" && <FoundPanel s={found} ch={data.ch} />} + {stage.key === "downloaded" && <DownloadedPanel s={downloaded} ingredient={ingredient} platform={data.platform} />} + {stage.key === "transcribed" && <TranscribedPanel s={transcribed} ingredient={ingredient} exists={data.exists} />} + {stage.key === "clock" && <ClockPanel s={clock} />} + {stage.key === "windows" && <WindowsPanel s={windows} ingredient={ingredient} ch={data.ch} id={data.id} />} + {stage.key === "used" && <UsedPanel s={used} />} + {stage.key === "checked" && <CheckedPanel s={checked} ingredient={ingredient} />} + {stage.key === "rendered" && <RenderedPanel s={rendered} />} + {stage.key === "published" && <PublishedPanel s={published} ingredient={ingredient} />} + </section> + </div> + ); +} + +// ── the action: plan, confirm, start ───────────────────────────────────────── + +type Plan = { action: string; what: string; cost: "network" | "gpu" | "disk" | null; queue: string; unreachable?: string; start: { route: string; body: Record<string, unknown> } | null }; +const COST: Record<string, string> = { network: "costs network", gpu: "costs GPU", disk: "deletes a cached file" }; + +function Action({ label, body, testid }: { label: string; body: Record<string, unknown>; testid: string }) { + const router = useRouter(); + const [plan, setPlan] = useState<Plan | null>(null); + const [busy, setBusy] = useState(false); + const [result, setResult] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const post = async (route: string, b: Record<string, unknown>) => { + const res = await fetch(route, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) }); + const j = await res.json().catch(() => ({})); + if (!res.ok || j?.error) throw new Error(String(j?.error ?? `HTTP ${res.status}`)); + return j; + }; + const ask = async () => { + setBusy(true); + setError(null); + setResult(null); + try { + setPlan((await post("/api/ingredients/action", { ...body, step: "plan" })) as Plan); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + const start = async () => { + if (!plan?.start) return; + setBusy(true); + setError(null); + try { + const j = await post(plan.start.route, plan.start.body); + setResult(String(j?.message ?? (j?.ok ? "done" : "started")) + (j?.fixed?.length ? ` — ${j.fixed.length} link(s) fixed` : "")); + setPlan(null); + router.refresh(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + return ( + <div className="space-y-1.5" data-action={testid}> + <button type="button" disabled={busy || !!plan} onClick={ask} className={buttonVariants({ variant: "outline", size: "sm" })} data-action-ask={testid}> + {label}… + </button> + {plan && ( + <div + className="max-w-[760px] space-y-1.5 rounded-[3px] border border-seam-2 bg-panel-2 px-3 py-2 text-[12px]" + data-action-confirm={testid} + data-action-cost={plan.cost ?? "none"} + data-action-unreachable={plan.unreachable ? "1" : undefined} + > + <p className={cn("m-0", plan.unreachable ? "text-doubt-text" : "text-text")}>{plan.what}</p> + {!plan.unreachable && ( + <p className="m-0 text-text-2"> + {plan.cost && <span className="mr-2 font-medium text-doubt-text">{COST[plan.cost]}</span>} + lands on <span className="font-mono" data-action-queue="">{plan.queue}</span> + </p> + )} + <div className="flex gap-2"> + {plan.start && ( + <button type="button" disabled={busy} onClick={start} className={buttonVariants({ variant: "outline", size: "sm" })} data-action-start={testid}> + Start + </button> + )} + <button type="button" disabled={busy} onClick={() => setPlan(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Cancel + </button> + </div> + </div> + )} + {result && ( + <p className="m-0 text-[12px] text-text-2" role="status" data-action-result={testid}> + {result} + </p> + )} + {error && ( + <p className="m-0 text-[12px] text-reject-text" role="alert" data-action-error={testid}> + {error} + </p> + )} + </div> + ); +} + +// ── the panels ─────────────────────────────────────────────────────────────── + +const Empty = ({ children }: { children: React.ReactNode }) => <p className="m-0 text-[12px] text-muted-2">{children}</p>; +const Rows = ({ children, ...p }: React.ComponentProps<"ul">) => ( + <ul className="m-0 max-h-[calc(100vh-330px)] min-h-0 list-none space-y-1 overflow-y-auto p-0 text-[12px]" {...p}> + {children} + </ul> +); +const Facts = ({ rows }: { rows: [string, React.ReactNode][] }) => ( + <dl className="m-0 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-0.5 text-[12px]"> + {rows.map(([k, v]) => ( + <div key={k} className="contents"> + <dt className="text-muted-2">{k}</dt> + <dd className="m-0 min-w-0 truncate text-text-2">{v}</dd> + </div> + ))} + </dl> +); + +function FoundPanel({ s, ch }: { s: FoundStage; ch: string }) { + return ( + <div className="space-y-2"> + {!s.findClips && !s.marks.length && !s.candidates.length && <Empty>No search mark, case window or clip-finder run names it.</Empty>} + <Rows data-found=""> + {s.findClips && ( + <li data-found-row="find-clips"> + The clip finder ({day(s.findClips.at)}): {s.findClips.segments} segment{s.findClips.segments === 1 ? "" : "s"} —{" "} + <Link href={projectHref(s.findClips.project)} prefetch={false} className="ink-link"> + {s.findClips.project} + </Link> + </li> + )} + {s.marks.map((m) => ( + <li key={m.session} data-found-row="mark"> + Research: <span className="text-text">{m.state}</span> in “{m.query ?? m.session}” ({day(m.at)}) —{" "} + <Link href={researchHref({ q: m.query ?? undefined, channels: [ch] })} prefetch={false} className="ink-link"> + open in Research + </Link> + </li> + ))} + {s.candidates.map((c) => ( + <li key={`${c.case}:${c.key}`} data-found-row="candidate"> + Case {c.case}: window {span(c.from, c.to)} ({c.hits} hit{c.hits === 1 ? "" : "s"}) —{" "} + <Link href={researchCasePipelineHref(c.case, "candidates")} prefetch={false} className="ink-link"> + its candidates + </Link> + </li> + ))} + </Rows> + <Link href={researchHref({ channels: [ch] })} prefetch={false} className={buttonVariants({ variant: "outline", size: "sm" })} data-found-open=""> + Find in Research + </Link> + </div> + ); +} + +function DownloadedPanel({ s, ingredient, platform }: { s: DownloadedStage; ingredient: { ch: string; id: string }; platform: string | null }) { + return ( + <div className="flex flex-wrap gap-x-8 gap-y-3"> + <div className="min-w-[320px] flex-1"> + <Facts + rows={[ + ["metadata", s.meta ? `${s.meta.title ?? s.meta.id ?? "?"} (${mb(s.meta.bytes)}, its head read)` : "none"], + ["download", s.outcome ? `${s.outcome.status}, ${s.outcome.attempts} attempt${s.outcome.attempts === 1 ? "" : "s"}${s.outcome.finishedAt ? `, ${day(s.outcome.finishedAt)}` : ""}` : "no outcome recorded"], + ["availability", s.availability ? `${s.availability.availability} (checked ${day(s.availability.checkedAt)})` : "never checked"], + ["history", s.history ? `${s.history.count} metadata rewrite${s.history.count === 1 ? "" : "s"}, last ${day(s.history.lastAt)} by ${s.history.lastBy ?? "?"}` : "none"], + ["saved video", s.saved ? `${s.saved.file}${s.saved.height ? ` (${s.saved.height}p)` : ""}${s.saved.reachable ? "" : " — NOT ANSWERING"}` : "not saved"], + ["imported", s.imported ? `${s.imported.count} landing${s.imported.count === 1 ? "" : "s"} (${s.imported.via ?? "?"}), ${day(s.imported.lastAt)}` : "—"], + ["captions", s.captions?.length ? s.captions.join(", ") : "none"], + ]} + /> + </div> + <div className="min-w-[260px] flex-1 space-y-2"> + <p className="micro m-0">Media</p> + {s.media.length ? ( + <Rows data-media=""> + {s.media.map((m) => ( + <li key={m.name} className="font-mono"> + {m.name} {mb(m.bytes)} + {m.link ? (m.reachable ? " → media tier" : " → media tier, NOT ANSWERING") : ""} + </li> + ))} + </Rows> + ) : ( + <Empty>No audio or source video in the video dir.</Empty> + )} + <Action label={platform === "rumble" ? "Persist the whole recording" : "Persist source video"} testid="persist" body={{ action: "persist", ...ingredient }} /> + </div> + </div> + ); +} + +function TranscribedPanel({ s, ingredient, exists }: { s: TranscribedStage; ingredient: { ch: string; id: string }; exists: boolean }) { + return ( + <div className="flex flex-wrap gap-x-8 gap-y-3"> + <div className="min-w-[320px] flex-1"> + <Facts + rows={[ + ["cues", s.cues ? `${s.cues.source ?? "?"}${s.cues.format ? ` (${s.cues.format})` : ""}, ${mb(s.cues.bytes)}` : "none"], + ["reach", s.cues ? `last cue ends ${hms(s.cues.lastEnd)} of ${hms(s.cues.duration)}${s.cues.coverage !== null ? ` (${Math.round(s.cues.coverage * 100)}%)` : ""}` : "—"], + ["made by", s.outcome ? `${s.outcome.worker ?? "?"}, ${day(s.outcome.at)}${s.outcome.salvaged ? " — a SALVAGE: gaps where the audio did not decode" : ""}` : "—"], + ["timed words", s.words ? `words.json (${mb(s.words.bytes)})` : "none"], + ["pinned", s.pin ? "transcript-pin.json" : "no"], + ["caption files", s.captions?.length ? s.captions.join(", ") : "none"], + ]} + /> + </div> + {exists && ( + <div className="min-w-[260px] flex-1"> + <Action label={s.cues ? "Transcribe again" : "Transcribe"} testid="transcribe" body={{ action: "transcribe", ...ingredient }} /> + </div> + )} + </div> + ); +} + +function ClockPanel({ s }: { s: ClockStage }) { + if (!s.clock) return <Empty>A Rumble recording gets one when its whole recording is saved and a window is cut from it.</Empty>; + return ( + <Facts + rows={[ + ["map", `${s.clock.id}: ${s.clock.ok ? "ok" : "NOT ok"}, ${s.clock.segments} segment${s.clock.segments === 1 ? "" : "s"}${s.clock.steps ? `, ${s.clock.steps} step${s.clock.steps === 1 ? "" : "s"}` : ""}`], + ["between", `${s.clock.source ?? "?"} (the cues' clock) → ${s.clock.target ?? "?"}`], + ["residual", s.clock.residualMs !== null ? `${s.clock.residualMs} ms` : "?"], + ["guarantee", "umtool quote-check, per clip"], + ]} + /> + ); +} + +function WindowsPanel({ s, ingredient, ch, id }: { s: WindowsStage; ingredient: { ch: string; id: string }; ch: string; id: string }) { + const byProject = new Map<string, string[]>(); + for (const u of s.uncovered) byProject.set(u.project, [...(byProject.get(u.project) ?? []), u.clipId]); + return ( + <div className="space-y-2"> + {s.windows.length === 0 && !s.uncovered.length && <Empty>No windows cut yet.</Empty>} + {s.windows.length > 0 && ( + <Rows data-windows=""> + {s.windows.map((w) => ( + <li + key={w.file} + data-window={w.name} + data-window-focused={w.focused ? "1" : undefined} + className={cn("flex flex-wrap items-center gap-x-3 gap-y-1 rounded-[3px] border px-2 py-1", w.focused ? "border-signal" : "border-seam")} + > + <Link href={ingredientHref(ch, id, w)} prefetch={false} className="font-mono text-text hover:underline"> + {span(w.from, w.to)} + </Link> + <span className="text-muted-2">{mb(w.bytes)}</span> + {w.desynced && <span className="text-doubt-text">set aside: its picture runs off its sound</span>} + {w.sidecar && ( + <span className="text-text-2"> + for {w.sidecar.clipId ?? "?"} ({w.sidecar.requestedBy ?? "?"}){w.sidecar.source ? `, from the ${w.sidecar.source}` : ""} + {w.sidecar.clock ? `, through clock ${w.sidecar.clock.id}${w.sidecar.clock.certain ? "" : " (NOT certain)"}` : ""} + {w.sidecar.syncOk === false ? ", sync NOT ok" : ""} + </span> + )} + <span className="text-text-2"> + {w.serves.length ? `cuts ${w.serves.map((x) => `${x.project.split("/").pop()} ${x.clipId}`).join(", ")}` : w.orphan ? "no project uses it now" : "cuts no clip"} + </span> + <span className="ml-auto"> + <Action label="Evict" testid={`evict-${w.file}`} body={{ action: "evict", ...ingredient, window: w.file }} /> + </span> + </li> + ))} + </Rows> + )} + {s.uncovered.length > 0 && ( + <div className="space-y-1.5" data-uncovered=""> + <p className="m-0 text-[12px] text-text-2"> + Not fetched: {s.uncovered.map((u) => `${u.project} ${u.clipId} (${span(u.from, u.to)})`).join(", ")} + </p> + {[...byProject.entries()].map(([project, clips]) => ( + <Action key={project} label={`Fetch ${clips.length === 1 ? clips[0] : `${clips.length} windows`} for ${project.split("/").pop()}`} testid={`fetch-${project}`} body={{ action: "fetch", ...ingredient, project, clips }} /> + ))} + </div> + )} + </div> + ); +} + +function UsedPanel({ s }: { s: UsedStage }) { + if (!s.rows.length) return <Empty>No project cuts from it.</Empty>; + return ( + <Rows data-used=""> + {s.rows.map((r) => ( + <li key={`${r.project}#${r.clipId}`} data-used-row={`${r.project}#${r.clipId}`} className="flex flex-wrap items-baseline gap-x-3"> + <Link href={projectHref(r.project)} prefetch={false} className="text-text hover:underline"> + {r.project} + </Link> + <Link href={clipBenchHref(r.project, r.clipId)} prefetch={false} className="ink-link font-mono" data-used-open=""> + {r.clipId} + </Link> + <span className="font-mono text-text-2"> + {span(r.start, r.end)} + {r.cutStart !== null || r.cutEnd !== null ? ` (cut ${span(r.cutStart ?? r.start, r.cutEnd ?? r.end)})` : ""} + </span> + <span className="text-muted-2">{[r.inDraft ? "draft" : null, ...r.versions.map((v) => v.id)].filter(Boolean).join(", ")}</span> + {r.quote && <span className="min-w-0 flex-1 truncate text-muted-2">“{r.quote}”</span>} + </li> + ))} + </Rows> + ); +} + +function CheckedPanel({ s, ingredient }: { s: CheckedStage; ingredient: { ch: string; id: string } }) { + if (!s.clips.length) return <Empty>No clip uses it, so there is no quote to check.</Empty>; + const byProject = new Map<string, string[]>(); + for (const c of s.clips) if (c.hasQuote) byProject.set(c.project, [...(byProject.get(c.project) ?? []), c.clipId]); + return ( + <div className="space-y-2"> + <Rows data-checked=""> + {s.clips.map((c) => ( + <li key={`${c.project}#${c.clipId}`} data-checked-row={`${c.project}#${c.clipId}`} data-status={c.status ?? ""} className="flex flex-wrap gap-x-3"> + <span className="text-text">{c.project}</span> + <span className="font-mono">{c.clipId}</span> + <span className={cn(c.current && c.status !== "ok" ? "text-doubt-text" : "text-text-2")}> + {!c.hasQuote ? "no quote" : c.status ? `${c.status}${c.offset !== null && c.status !== "ok" ? ` (${c.offset > 0 ? "+" : ""}${c.offset.toFixed(1)} s)` : ""}${c.current ? "" : " — stale: the cut changed since"}` : "not checked"} + </span> + </li> + ))} + </Rows> + {[...byProject.entries()].map(([project, clips]) => ( + <Action key={project} label={`Check quotes in ${project.split("/").pop()}`} testid={`quote-check-${project}`} body={{ action: "quote-check", ...ingredient, project, clips }} /> + ))} + </div> + ); +} + +function RenderedPanel({ s }: { s: RenderedStage }) { + if (!s.renders.length) return <Empty>Not in any saved version yet.</Empty>; + return ( + <Rows data-rendered=""> + {s.renders.map((r) => ( + <li key={`${r.project}#${r.clipId}@${r.version ?? "draft"}`} data-rendered-row={`${r.project}#${r.clipId}@${r.version ?? "draft"}`} className="flex flex-wrap gap-x-3"> + <span className="text-text">{r.project}</span> + <span className="font-mono">{r.clipId}</span> + <span className="text-text-2"> + {r.version ? `version ${r.version}${r.label ? ` (${r.label})` : ""}` : "the draft's segment"}: {r.state ?? "not rendered"} + {r.seconds !== null ? `, ${hms(r.seconds)}` : ""} + {r.cut ? `, cut ${span(r.cut.from, r.cut.to)}` : ""} + </span> + <Link href={playHref(r.project, r.version ? { take: r.version, clip: r.clipId } : { clip: r.clipId })} prefetch={false} className="ink-link" data-rendered-play=""> + play it at this clip + </Link> + </li> + ))} + </Rows> + ); +} + +function PublishedPanel({ s, ingredient }: { s: PublishedStage; ingredient: { ch: string; id: string } }) { + if (!s.links.length) return <Empty>Not in any cut, so nothing links to it.</Empty>; + const projects = [...new Set(s.links.map((l) => l.project))]; + return ( + <div className="space-y-2"> + <Rows data-published=""> + {s.links.map((l) => ( + <li key={`${l.project}#${l.clipId}`} data-published-row={`${l.project}#${l.clipId}`} data-state={l.state ?? ""} className="flex flex-wrap gap-x-3"> + <span className="text-text">{l.project}</span> + <span className="font-mono">{l.clipId}</span> + <span className={cn(l.state === "dead" ? "text-reject-text" : "text-text-2")}>{l.state ?? "never checked"}</span> + {l.url && ( + <a href={l.url} target="_blank" rel="noreferrer" className="ink-link min-w-0 truncate"> + {l.url} + </a> + )} + {l.fix && <span className="text-muted-2">fix: {l.fix}</span>} + </li> + ))} + </Rows> + <div className="flex flex-wrap gap-3"> + {projects.map((p) => ( + <Action key={p} label={`Check links in ${p.split("/").pop()}`} testid={`links-${p}`} body={{ action: "links", ...ingredient, project: p }} /> + ))} + {projects + .filter((p) => s.links.some((l) => l.project === p && l.state === "dead" && l.fix)) + .map((p) => ( + <Action key={`fix-${p}`} label={`Fix dead links in ${p.split("/").pop()}`} testid={`links-fix-${p}`} body={{ action: "links", ...ingredient, project: p, fix: true }} /> + ))} + </div> + </div> + ); +} diff --git a/umtool/components/projects/bench/BenchShell.tsx b/umtool/components/projects/bench/BenchShell.tsx @@ -71,6 +71,7 @@ export function BenchTop({ note, phone = "shown", slot = false, + life = null, }: { /** The piece this bench belongs to: "← <its name>". */ back: BenchLink; @@ -94,6 +95,8 @@ export function BenchTop({ * portal a control into (the clip bench's "Back to the cut"). Hidden while empty. */ slot?: boolean; + /** The source's life cycle (lane L5, /ingredients/<ch>/<id>): a small link beside the bench's kind. */ + life?: BenchLink | null; }) { return ( <header @@ -128,6 +131,11 @@ export function BenchTop({ <span className="micro" data-bench-kind=""> {kind} </span> + {life && ( + <Link href={life.href} prefetch={false} data-bench-life="" className="text-[11.5px] text-muted-2 hover:text-text" {...life.attrs}> + {life.label} + </Link> + )} {pos && ( <span data-bench-pos={`${pos.index}/${pos.total}`} className="font-mono text-[12.5px] font-medium text-text-2"> {pos.index} of {pos.total} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -7,7 +7,7 @@ import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { NoteThread } from "@/components/notes/NoteThread"; import type { Anchor, CutAsk, Note } from "@/lib/annotations/types"; -import { clipBenchHref, openInDraftHref, postBenchHref } from "@/lib/hrefs"; +import { clipBenchHref, ingredientHref, openInDraftHref, postBenchHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; @@ -116,6 +116,8 @@ export type PlayEntry = { dateLabel?: string | null; section?: unknown; channel?: string | null; + /** The channel it cuts from (its own, else the provenance's): the life cycle's address (lane L5). */ + sourceChannel?: string | null; quote?: string | null; video?: string; start?: number; @@ -1390,6 +1392,18 @@ export default function PlayCut({ > {postNow ? "Edit this post" : "Edit this clip"} </button> + {/* The clip's source across its life cycle (lane L5): found, downloaded, … published. */} + {item?.clip && entry?.video && entry.sourceChannel && ( + <Link + href={ingredientHref(entry.sourceChannel, entry.video)} + prefetch={false} + data-play-life="" + className="text-[11.5px] text-muted-2 hover:text-text" + title="this clip's recording across its life cycle: found, downloaded, transcribed, its windows, every cut that uses it, checked, rendered, published" + > + Life cycle + </Link> + )} <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud=""> {tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />} {schedule?.factcheck && ( diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -135,6 +135,7 @@ Inbox cannot disagree about what is wrong with one. | `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project> [--replace] [--json]` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`; built in: `plain-deck` `huck-deck` `ember-deck` `archive-catalog` `basic`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build (a basic cut's chrome is not checked); `--replace` also clears the manifest's own value of every key the preset sets, after an undo point (`revisions/…-auto-before-preset-replace`), and prints what went ([knobs.md](knobs.md#look-presets)) | | `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) | | `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` | +| `ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]` | **one recording's life cycle**, the twin of `/ingredients/<channel>/<video>` ([knobs.md](knobs.md#an-ingredients-life-cycle-the-rail)): nine stages — found, downloaded, transcribed, clock, windows, used in, checked, rendered, published — each **✓**, a count, **!** or **—**, and its line, then every project clip that cuts from it (the draft and each saved version, from the usage index `<REPORTS_ROOT>/.umtool/usage-index.json`). A Rumble recording answers to its folder slug or its embed id; both are printed. `--window`: one clip window, the stages after it narrowed to the clips it plays. `--used-in`: the clips alone. `--json`: the page's object. Read-only over the corpus. **Exit 0 · 1 failed · 2 usage** | | `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render | | `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself | | `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -377,6 +377,40 @@ The Rumble mapping is ONE helper (`lib/report/shareLine.mjs` `siteVideoFor`, ove `citeUrl` that was the dead link moves with it); and `umtool timeline insert <rumble-channel>/<folder>@…`, which writes the inserted clip with its `siteVideo`. A clip that pins `siteVideo` is never looked up. +## An ingredient's life cycle (the rail) + +`/ingredients/<channel>/<video>` is one recording of the corpus across its whole life: nine stages across the top, +each a pill — **✓** (done), **a count**, **!** (needs you) or **—** (nothing yet) — and the selected stage's panel +below. `?window=<from>-<to>` (a clip window's own name) focuses one window: it is lit, and the stages after it +(Used in, Checked, Rendered, Published) narrow to the clips it plays. A Rumble recording answers to its folder slug +or its embed id, and the head shows both. Every stage reads files that already exist, read-only over the corpus +(`lib/ingredients/stages.mjs`: `metadata.info.json` and `transcript.cues.json` by their ends, never whole): + +| Stage | Read from | Its action | From a terminal | Route | +|---|---|---|---|---| +| Found | `find-clips.json`; research sessions' marks; research cases' `candidates.jsonl` | Find in Research; the case's candidates | `umtool ingredient <ch>/<id>` | — | +| Downloaded | the metadata's head, `metadata.history.json`, `download-outcome.json`, `availability.json`, `saved-video.json`, `media-import.json`, the media files and their links | **Persist source video** (Rumble: the whole recording) | `pnpm ops persist-videos --json '{"items":[{"slug":…,"id":…}]}'` | `POST /api/ops/persist-videos` (editor) | +| Transcribed | the cues' head and tail (source, reach), the `.vtt` files, `transcript-pin.json`, `transcribe-outcome.json`, `words.json` | **Transcribe** (the GPU) | `pnpm ops transcribe-one --json '{"slug":…,"id":…}'` | `POST /api/ops/transcribe-one` (editor) | +| Clock | `clock.json` (`describeClock`) | — | `umtool ingredient <ch>/<id>` | — | +| Windows | `clips/<from>-<to>.*` and their sidecars, cross-checked against the usage index: a draft clip no window holds, a window asked for a clip no project uses | **Fetch** the clips no window holds (the project's own fetch body, narrowed to them); **Evict** one window | `umtool fetch <p>` · `pnpm ops evict-clips --json '{"slug":…,"id":…,"windows":["<from>-<to>"]}'` | `POST /api/ops/fetch-windows` · `POST /api/ops/evict-clips` (editor) | +| Used in | the usage index: every project clip that cuts from it, in the draft and in each saved version | each clip opens its bench | `umtool ingredient <ch>/<id> --used-in [--json]` | — | +| Checked | each project's `quote-check.json` rows for those clips (a row the cut has moved past reads stale) | **Check quotes** (the GPU) | `umtool quote-check <p> --clips a,b` | `POST /api/ingredients/action` (a umtool job) | +| Rendered | each version's `render.json` (else its preview), `out/segments/<clip>.cut.json` | play the version at that clip | `umtool take status <p> --id <v>` | — | +| Published | each project's `out/links.json` rows for those clips, the archive moment | **Check links**; **Fix dead links** | `umtool links <p> [--fix]` | `POST /api/report/links {project, fix?}` | + +Every action ASKS first: `POST /api/ingredients/action {action, ch, id, step: "plan", project?, clips?, window?}` +answers what it will do, what it costs (network, the GPU, a deleted cache file) and the queue it lands on — the +editor's own dry run for fetch-windows and persist-videos — and nothing starts until **Start** posts the plan's +`start` (`step: "start"`). The editor decides the queue, the pacing and a whole-recording download. + +THE USAGE INDEX (`lib/ingredients/usedIn.mjs`) is `<REPORTS_ROOT>/.umtool/usage-index.json` (`UMTOOL_USAGE_INDEX_FILE` +moves it): every report-video project's `video.manifest.json` (the draft) and each take's frozen form +(`takes/<id>/base.manifest.json`, a saved version, or a legacy rendered take's `takes/<id>/video.manifest.json`), +rebuilt incrementally by each manifest's mtime and size; a project deleted drops out. A clip citing a Rumble embed id +and one citing the folder slug are one ingredient, keyed by the folder (`resolveVideoDirId`, its answer kept in the +index). The way in: the clip bench's head (**Life cycle**), Play's row for the clip on screen (**Life cycle**), and the +editor's video page (**Open in umtool**). + ## Sections, split and flash-forward (editing the cut) Under the deck a cut's **sections are its markers** (`render.chrome.deck.markers`): §0 runs to the first marker's diff --git a/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs b/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs @@ -23,7 +23,8 @@ import path from "node:path"; // spec's cache lookup finds — specs must stay order-independent. And the // article chain's `windows` step relies on that 404 to stop (article-iterations.spec). // basicyt: the quick-clip job's recording (basic-mode-fixture.mjs), a channel of its own for the same reason. -export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt"]); +// railchan: the ingredient rail's recording (ingredient-rail-fixture.mjs), which no other spec reads. +export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt", "railchan"]); const fwJobs = new Map(); let next = 1; diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -1313,7 +1313,9 @@ const server = http.createServer((req, res) => { // THE CASE PIPELINE'S GAP BUTTONS (release 38 lane A, case-pipeline.spec.ts): the editor's own actions, // recorded and answered as queued -- download-missing, transcribe-bucket, persist-videos (its dryRun answers // the buckets) and channel-priority's focus. - if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority"].includes(url.pathname)) { + // The ingredient rail's (lane L5, ingredient-rail.spec.ts): transcribe-one and a targeted evict-clips, recorded and + // answered as queued the same way -- nothing is transcribed and no window is deleted. + if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority", "/api/ops/transcribe-one", "/api/ops/evict-clips"].includes(url.pathname)) { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { diff --git a/umtool/e2e/fixtures/ingredient-rail-fixture.mjs b/umtool/e2e/fixtures/ingredient-rail-fixture.mjs @@ -0,0 +1,83 @@ +// What ingredient-rail.spec.ts reads (lane L5, the ingredient life-cycle rail): one recording of the +// fixture corpus used by TWO projects, and a Rumble recording cited by its embed id. +// +// channels/railchan/ a YouTube channel of its own (fetch-windows serves it: editor-stub-fetch-windows.mjs) +// data/railvid/ metadata.info.json (its webpage_url past a 64 KB formats array: the head reader never sees it), +// transcript.cues.json (300 s, 50 cues), transcript.en.vtt, download-outcome.json, availability.json, +// metadata.history.json, find-clips.json (the clip finder found it: rail-a), +// clips/10.00-40.00.mp4 (+ sidecar: asked for rail-a's ra1), clips/200.00-230.00.mp4 (+ sidecar: +// asked for a clip no project has now -- the orphan) +// channels/railrumble/ platform rumble: data/v7rslug1/ is the URL slug, its metadata's id the +// embed id v7rembd1, which rail-r cites +// +// reports/rail-a ra1 railvid 12-20 (quote; ok in quote-check.json), ra2 railvid 100-110 (quote; no window holds it) +// takes/v1: a saved version (base.manifest.json) holding ra1, rendered (render.json done, preview.mp4) +// reports/rail-b rb1 railvid 15-25, its QR link checked ok (out/links.json) +// reports/rail-r rr1 railrumble/v7rembd1 30-40 +// +// The site the QRs link is http://127.0.0.1:9 (cut-integrity-fixture's placeholder): a link check there is +// refused at once, on this machine. The spec WRITES (a link check rewrites rail-b's out/links.json; a quote +// check may write rail-a's quote-check.json): these projects are its own. +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const RAIL_SITE = "http://127.0.0.1:9"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); +}; + +/** @param {{ reports: string, channels: string, manifest: Function, cachedWindow: string }} o */ +export function makeIngredientRailFixture({ reports, channels, manifest, cachedWindow }) { + // ── the corpus ── + const ch = path.join(channels, "railchan"); + write(ch, "config.json", { platform: "youtube" }); + const v = path.join(ch, "data", "railvid"); + const formats = Array.from({ length: 1500 }, (_, i) => ({ format_id: String(i), url: `https://media.example/${"x".repeat(40)}/${i}` })); + write(v, "metadata.info.json", JSON.stringify({ id: "railvid", title: "The Rail Recording", formats, webpage_url: "https://www.youtube.com/watch?v=railvid", duration: 300 })); + const cues = Array.from({ length: 50 }, (_, i) => ({ start: i * 6, end: i * 6 + 5.5, text: `the rail recording says line ${i}.` })); + write(v, "transcript.cues.json", JSON.stringify({ version: 2, source: "vtt", vttFile: "transcript.en.vtt", transcriptFormat: "vtt", id: "railvid", channelSlug: "railchan", title: "The Rail Recording", uploadDate: "20261101", duration: 300, platform: "youtube", cues })); + write(v, "transcript.en.vtt", "WEBVTT\n\n00:00:00.000 --> 00:00:05.500\nthe rail recording says line 0.\n"); + write(v, "download-outcome.json", { videoId: "railvid", webpageUrl: "https://www.youtube.com/watch?v=railvid", status: "ok", startedAt: "2026-11-01T10:00:00.000Z", finishedAt: "2026-11-01T10:00:20.000Z", attempts: [{ n: 0, kind: "primary" }] }); + write(v, "availability.json", { checkedAt: "2026-11-02T00:00:00.000Z", availability: "public", history: [] }); + write(v, "metadata.history.json", { entries: [{ at: "2026-11-03T00:00:00.000Z", by: "refresh", from: { sha256: "a", bytes: 1 }, to: { sha256: "b", bytes: 2 }, changed: {}, added: {}, removed: {}, counters: {}, volatile: [] }] }); + write(v, "find-clips.json", { version: 1, at: "2026-11-04T00:00:00.000Z", jobId: "job-1", project: "reports/rail-a", url: "/projects/reports/rail-a/clip-editor", created: true, segments: [{ id: "s1", from: 0, to: 120 }], steps: [] }); + mkdirSync(path.join(v, "clips"), { recursive: true }); + copyFileSync(cachedWindow, path.join(v, "clips", "10.00-40.00.mp4")); + write(path.join(v, "clips"), "10.00-40.00.json", { requestedBy: "umtool:reports/rail-a", clipId: "ra1", reason: "The Rail A Fixture", fetchedAt: "2026-11-05T00:00:00.000Z", bytes: 1 }); + copyFileSync(cachedWindow, path.join(v, "clips", "200.00-230.00.mp4")); + write(path.join(v, "clips"), "200.00-230.00.json", { requestedBy: "umtool:reports/gone", clipId: "gone1", fetchedAt: "2026-11-05T00:00:00.000Z" }); + + const rch = path.join(channels, "railrumble"); + write(rch, "config.json", { platform: "rumble" }); + const rv = path.join(rch, "data", "v7rslug1"); + write(rv, "metadata.info.json", JSON.stringify({ id: "v7rembd1", title: "The Rumble Rail Recording", webpage_url: "https://rumble.com/v7rslug1-the-rumble-rail-recording.html" })); + write(rv, "transcript.cues.json", JSON.stringify({ version: 2, source: "whisper", id: "v7rembd1", title: "The Rumble Rail Recording", duration: 120, cues: [{ start: 0, end: 4, text: "rumble." }] })); + + // ── the projects ── + const origin = { siteOrigin: RAIL_SITE, channelSlug: "railchan" }; + const a = manifest("rail-a", "The Rail A Fixture", origin, [ + { type: "clip", id: "ra1", video: "railvid", start: 12, end: 20, cite: 12, section: 0, quote: "the rail recording says line 2." }, + { type: "clip", id: "ra2", video: "railvid", start: 100, end: 110, cite: 100, section: 0, quote: "the rail recording says line 17." }, + ]); + const aDir = path.join(reports, "rail-a"); + write(aDir, "video.manifest.json", a); + const base = manifest("rail-a", "The Rail A Fixture", origin, [a.timeline[0]]); + const take = path.join(aDir, "takes", "v1"); + write(take, "base.manifest.json", base); + write(take, "take.json", { id: "v1", group: "takes", order: 1, label: "Version 1", kind: "different", preview: "preview.mp4", window: "full", style: null, patch: null, version: true, draft: true, seconds: 8, builtAt: "2026-11-06T00:00:00.000Z" }); + copyFileSync(cachedWindow, path.join(take, "preview.mp4")); + write(take, "render.json", { version: 1, state: "done", project: "reports/rail-a", take: "v1", mp4: "preview.mp4", seconds: 8, startedAt: "2026-11-06T00:00:00.000Z", endedAt: "2026-11-06T00:01:00.000Z", exitCode: 0, stage: "done", percent: 100 }); + write(aDir, "quote-check.json", { version: 1, checkedAt: "2026-11-06T12:00:00.000Z", clips: { ra1: { status: "ok", offset: 0.02, against: "cues", cut: { from: 12, to: 20 }, quote: "the rail recording says line 2." } } }); + + const bDir = path.join(reports, "rail-b"); + write(bDir, "video.manifest.json", manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }])); + write(path.join(bDir, "out"), "links.json", { version: 1, checkedAt: "2026-11-07T00:00:00.000Z", fetched: 1, origins: {}, links: [{ clip: "rb1", url: `${RAIL_SITE}/?v=railchan%2Frailvid&t=15`, state: "ok", origin: RAIL_SITE }] }); + + const rDir = path.join(reports, "rail-r"); + write(rDir, "video.manifest.json", manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: RAIL_SITE, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }])); + return { aDir, bDir, rDir }; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -67,6 +67,7 @@ import { makePostComboFixture } from "./post-combo-fixture.mjs"; import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs"; import { makeInstrumentsFixture } from "./instruments-fixture.mjs"; import { makeIntroPlayFixture } from "./intro-play-fixture.mjs"; +import { makeIngredientRailFixture } from "./ingredient-rail-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -2089,6 +2090,10 @@ writeFileSync(ptFile, JSON.stringify(pt, null, 2) + "\n"); // sound of its own, and a whole-cut version v1 the spec switches the intro off and on in. WRITABLE, its own. makeIntroPlayFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture }); +// THE INGREDIENT RAIL (ingredient-rail.spec.ts, lane L5): one recording (railchan/railvid) used by two projects, +// its windows, a saved version, a quote check and a link check; a Rumble recording cited by its embed id. WRITABLE, its own. +makeIngredientRailFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); + // The measure's instruments (instruments.spec.ts): the Play cut with the dial, the odometer and // the trail on, and a built schedule carrying a measure slice (instruments-fixture.mjs). await makeInstrumentsFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture }); diff --git a/umtool/e2e/ingredient-rail.spec.ts b/umtool/e2e/ingredient-rail.spec.ts @@ -0,0 +1,224 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE INGREDIENT LIFE-CYCLE RAIL (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"): /ingredients/<ch>/<id> +// shows one recording across nine stages -- found, downloaded, transcribed, clock, windows, used in, checked, +// rendered, published -- each a pill (✓, a count, ! or —) and a panel, and each stage's action says what it +// costs and where it lands before it posts to the editor's (stubbed) or umtool's own route. +// +// Fixture: e2e/fixtures/ingredient-rail-fixture.mjs -- railchan/railvid used by reports/rail-a (ra1, ra2; a saved +// version v1 holding ra1, rendered) and reports/rail-b (rb1); railrumble/v7rslug1 (embed id v7rembd1) cited by +// reports/rail-r. WRITES (rail-b's links.json, maybe rail-a's quote-check.json): its own. +// +// INGREDIENT_SHOTS (a directory): the page's screenshots at 1366×768 go there too. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const SHOTS = process.env.INGREDIENT_SHOTS ?? null; +const RAIL = urls.ingredientHref("railchan", "railvid"); + +type StubRequest = { route?: string; slug?: string; id?: string; items?: { slug: string; id: string; clipId?: string }[]; dryRun?: boolean; windows?: string[] }; +const stubLog = (): StubRequest[] => { + try { + return JSON.parse(readFileSync(STUB_LOG, "utf8")) as StubRequest[]; + } catch { + return []; + } +}; +const railAsks = (route: string) => + stubLog().filter((r) => r.route === route && (r.slug === "railchan" || (r.items ?? []).some((i) => i.slug === "railchan"))); + +const shot = async (page: Page, name: string) => { + await page.screenshot({ path: test.info().outputPath(name) }); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name) }); +}; + +const pill = (page: Page, key: string) => page.locator(`[data-ingredient-rail] [data-stage="${key}"]`); +const openStage = async (page: Page, key: string) => { + await pill(page, key).click(); + await expect(page.locator(`[data-stage-panel="${key}"]`)).toBeVisible(); +}; + +/** Ask, read the confirmation (cost, queue), Start, and wait for the answer. */ +async function runAction(page: Page, id: string, { cost, queue }: { cost: string; queue?: RegExp }) { + await page.locator(`[data-action-ask="${id}"]`).click(); + const confirm = page.locator(`[data-action-confirm="${id}"]`); + await expect(confirm).toBeVisible({ timeout: 20_000 }); + await expect(confirm).toHaveAttribute("data-action-cost", cost); + if (queue) await expect(confirm.locator("[data-action-queue]")).toHaveText(queue); + await confirm.locator(`[data-action-start="${id}"]`).click(); + await expect(page.locator(`[data-action-result="${id}"]`)).toBeVisible({ timeout: 30_000 }); + await expect(page.locator(`[data-action-error="${id}"]`)).toHaveCount(0); +} + +test.beforeEach(async ({ page }) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1366, height: 768 }); +}); + +test("all nine pills render: ✓, a count, ! or — from the files that exist, and the page fits 1366×768", async ({ page }) => { + await page.goto(RAIL); + await expect(page.locator("[data-ingredient]")).toHaveAttribute("data-ingredient", "railchan/railvid"); + const rail = page.locator("[data-ingredient-rail] [data-stage]"); + await expect(rail).toHaveCount(9); + await expect(rail).toHaveText([/Found/, /Downloaded/, /Transcribed/, /Clock/, /Windows/, /Used in/, /Checked/, /Rendered/, /Published/]); + const want: Record<string, [string, string]> = { + found: ["count", "1"], + downloaded: ["ok", "✓"], + transcribed: ["ok", "✓"], + clock: ["none", "—"], + windows: ["warn", "!"], + used: ["count", "3"], + checked: ["count", "1"], + rendered: ["count", "1"], + published: ["count", "1"], + }; + for (const [key, [kind, text]] of Object.entries(want)) { + await expect(pill(page, key), key).toHaveAttribute("data-pill", kind); + await expect(pill(page, key), key).toHaveAttribute("data-pill-text", text); + } + // The first stage that warns is the one open: two windows, one clip no window holds. + await expect(page.locator('[data-stage-panel="windows"]')).toBeVisible(); + await expect(page.locator("[data-stage-line]")).toHaveText("2 windows, 1 clip not fetched"); + await expect(page.locator('[data-window="200.00-230.00"]')).toContainText("no project uses it now"); + await expect(page.locator("[data-uncovered]")).toContainText("reports/rail-a ra2"); + // The stage with no data says so in one line. + await openStage(page, "clock"); + await expect(page.locator("[data-stage-line]")).toContainText("No time map"); + // Downloaded read the metadata's head only: its title, not the webpage_url past the formats. + await openStage(page, "downloaded"); + await expect(page.locator('[data-stage-panel="downloaded"]')).toContainText("The Rail Recording"); + await expect(page.locator('[data-stage-panel="downloaded"]')).toContainText("1 metadata rewrite"); + await openStage(page, "transcribed"); + await expect(page.locator("[data-stage-line]")).toContainText("vtt, 100% of 5:00"); + // App-like: no page scroll at 1366×768. + expect(await page.evaluate(() => document.documentElement.scrollHeight <= window.innerHeight + 1)).toBe(true); + await openStage(page, "windows"); + await shot(page, "ingredient-rail.png"); +}); + +test("Used in lists both projects, each clip a link to its bench, the saved version beside the draft", async ({ page }) => { + await page.goto(RAIL); + await openStage(page, "used"); + const rows = page.locator("[data-used-row]"); + await expect(rows).toHaveCount(3); + await expect(page.locator('[data-used-row="reports/rail-a#ra1"]')).toContainText("draft, v1"); + await expect(page.locator('[data-used-row="reports/rail-a#ra2"]')).toContainText("draft"); + await expect(page.locator('[data-used-row="reports/rail-b#rb1"]')).toContainText("reports/rail-b"); + await expect(page.locator('[data-used-row="reports/rail-a#ra1"] [data-used-open]')).toHaveAttribute("href", urls.clipBenchHref("reports/rail-a", "ra1")); + await expect(page.locator("[data-stage-line]")).toHaveText("3 clips in 2 projects"); + await shot(page, "ingredient-used.png"); + // Rendered: the version v1 holds ra1, rendered; Play opens it at that clip. + await openStage(page, "rendered"); + await expect(page.locator('[data-rendered-row="reports/rail-a#ra1@v1"]')).toContainText("version v1"); + await expect(page.locator('[data-rendered-row="reports/rail-a#ra1@v1"] [data-rendered-play]')).toHaveAttribute("href", urls.playHref("reports/rail-a", { take: "v1", clip: "ra1" })); + // Checked and Published read the projects' own files. + await openStage(page, "checked"); + await expect(page.locator('[data-checked-row="reports/rail-a#ra1"]')).toHaveAttribute("data-status", "ok"); + await expect(page.locator('[data-checked-row="reports/rail-a#ra2"]')).toContainText("not checked"); + await openStage(page, "published"); + await expect(page.locator('[data-published-row="reports/rail-b#rb1"]')).toHaveAttribute("data-state", "ok"); + await expect(page.locator('[data-published-row="reports/rail-a#ra1"]')).toContainText("never checked"); +}); + +test("?window= focuses one window: it is lit, and the stages after it narrow to the clips it plays", async ({ page }) => { + await page.goto(urls.ingredientHref("railchan", "railvid", { from: 10, to: 40 })); + await expect(page.locator("[data-ingredient-focus]")).toHaveAttribute("data-ingredient-focus", "10.00-40.00"); + await expect(page.locator('[data-stage-panel="windows"]')).toBeVisible(); + await expect(page.locator("[data-window-focused]")).toHaveCount(1); + await expect(page.locator('[data-window="10.00-40.00"]')).toHaveAttribute("data-window-focused", "1"); + await expect(page.locator('[data-window="10.00-40.00"]')).toContainText("cuts rail-a ra1, rail-b rb1"); + await expect(pill(page, "used")).toHaveAttribute("data-pill-text", "2"); + await openStage(page, "used"); + await expect(page.locator("[data-used-row]")).toHaveCount(2); + await expect(page.locator('[data-used-row="reports/rail-a#ra2"]')).toHaveCount(0); + await expect(page.locator("[data-stage-line]")).toHaveText("2 clips in 2 projects (of 3 from this recording)"); + await expect(page.locator("[data-checked-row]")).toHaveCount(0); // the checked panel is not open + await openStage(page, "checked"); + await expect(page.locator("[data-checked-row]")).toHaveCount(2); + await shot(page, "ingredient-window.png"); +}); + +test("Rumble: the folder slug and the embed id open the same recording, and the page shows both", async ({ page }) => { + for (const id of ["v7rembd1", "v7rslug1"]) { + await page.goto(urls.ingredientHref("railrumble", id)); + await expect(page.locator("[data-ingredient]")).toHaveAttribute("data-ingredient", "railrumble/v7rslug1"); + await expect(page.locator("[data-ingredient-site-id]")).toHaveAttribute("data-ingredient-site-id", "v7rembd1"); + await expect(pill(page, "used")).toHaveAttribute("data-pill-text", "1"); + } + await openStage(page, "used"); + await expect(page.locator('[data-used-row="reports/rail-r#rr1"]')).toBeVisible(); + await openStage(page, "downloaded"); + await expect(page.locator('[data-action-ask="persist"]')).toHaveText("Persist the whole recording…"); +}); + +test("the entry points: the clip bench's Life cycle and Play's clip row link the clip's recording", async ({ page }) => { + await page.goto(urls.clipBenchHref("reports/rail-a", "ra1")); + await expect(page.locator("[data-bench-top] [data-bench-life]")).toHaveAttribute("href", RAIL); + await page.goto(urls.playHref("reports/rail-a", { clip: "ra1" })); + await expect(page.locator("[data-play-life]")).toHaveAttribute("href", RAIL, { timeout: 30_000 }); +}); + +test("each action asks first -- what it costs, the queue it lands on -- then posts to the right route", async ({ page, request }) => { + await page.goto(RAIL); + // Downloaded: persist-videos, the editor's dry run first. + await openStage(page, "downloaded"); + const persists = railAsks("persist-videos").length; + await runAction(page, "persist", { cost: "network", queue: /railchan channel's download queue/ }); + const persist = railAsks("persist-videos").slice(persists); + expect(persist.map((r) => !!r.dryRun)).toEqual([true, false]); + expect(persist[1].items).toEqual([{ slug: "railchan", id: "railvid" }]); + + // Transcribed: transcribe-one, on the GPU. + await openStage(page, "transcribed"); + const transcribes = railAsks("transcribe-one").length; + await runAction(page, "transcribe", { cost: "gpu", queue: /transcribe-one:railchan:railvid/ }); + expect(railAsks("transcribe-one").slice(transcribes)).toMatchObject([{ slug: "railchan", id: "railvid" }]); + + // Windows: fetch-windows for the clip no window holds (rail-a's own body, narrowed to it), then a targeted evict. + await openStage(page, "windows"); + const fetches = railAsks("fetch-windows").length; + await runAction(page, "fetch-reports/rail-a", { cost: "network", queue: /clips:youtube/ }); + const fetch = railAsks("fetch-windows").slice(fetches); + expect(fetch.map((r) => !!r.dryRun)).toEqual([true, false]); + expect(fetch[1].items?.map((i) => `${i.slug}/${i.id}#${i.clipId}`)).toEqual(["railchan/railvid#ra2"]); + const evicts = railAsks("evict-clips").length; + await runAction(page, "evict-200.00-230.00.mp4", { cost: "disk" }); + expect(railAsks("evict-clips").slice(evicts)).toMatchObject([{ slug: "railchan", id: "railvid", windows: ["200.00-230.00"] }]); + + // Published: umtool's own link check (/api/report/links) -- the site refuses at once, so the link is unverified. + await openStage(page, "published"); + const links = page.waitForRequest((r) => r.url().endsWith("/api/report/links") && r.method() === "POST"); + await runAction(page, "links-reports/rail-b", { cost: "network" }); + expect((await links).postDataJSON()).toEqual({ project: "reports/rail-b" }); + await expect(page.locator('[data-published-row="reports/rail-b#rb1"]')).toHaveAttribute("data-state", "unverified", { timeout: 15_000 }); + + // Checked: a quote check, a umtool job (its transcriptions the editor's); it is let finish before the next spec. + await openStage(page, "checked"); + await runAction(page, "quote-check-reports/rail-a", { cost: "gpu", queue: /umtool's job runner/ }); + await expect(page.locator('[data-action-result="quote-check-reports/rail-a"]')).toContainText("quote check started"); + await expect + .poll(async () => ((await (await request.get("/api/jobs")).json()) as { running: unknown }).running, { timeout: 90_000 }) + .toBeNull(); +}); + +test("another site's page may not start an action: a foreign Origin is refused, and so is a body that is not JSON", async ({ request }) => { + const body = { action: "transcribe", ch: "railchan", id: "railvid", step: "plan" }; + const foreign = await request.post("/api/ingredients/action", { data: body, headers: { origin: "http://evil.example", "sec-fetch-site": "cross-site" } }); + expect(foreign.status()).toBe(403); + const form = await request.post("/api/ingredients/action", { data: JSON.stringify(body), headers: { "content-type": "text/plain" } }); + expect(form.status()).toBe(415); + // A start without the plan's key is refused before the editor is asked. + const asked = railAsks("transcribe-one").length; + const keyless = await request.post("/api/ingredients/action", { data: { ...body, step: "start" } }); + expect(keyless.status()).toBe(400); + expect(railAsks("transcribe-one").length).toBe(asked); +}); diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -138,3 +138,9 @@ test("Play the cut ↔ the clip bench: Edit this clip carries the way back, Back assert.equal(H.playHref("a/b", { at: 3 }), "/projects/a/b/play"); assert.equal(H.playHref("a/b", { take: "t1", note: "n" }), "/projects/a/b/play?take=t1&note=n"); }); + +test("ingredientHref: /ingredients/<ch>/<id>, a window as its two-decimal name", () => { + assert.equal(H.ingredientHref("MommaOcco", "n8G_ysDV2bA"), "/ingredients/MommaOcco/n8G_ysDV2bA"); + assert.equal(H.ingredientHref("MommaOcco", "n8G_ysDV2bA", { from: 1290, to: 1365 }), "/ingredients/MommaOcco/n8G_ysDV2bA?window=1290.00-1365.00"); + assert.equal(H.ingredientHref("a b", "x/y", null), "/ingredients/a%20b/x%2Fy"); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -535,3 +535,15 @@ export function toolsHref(): string { export function songToolsHref(): string { return "/tools/song"; } + +// ── ingredients (lane L5) ─────────────────────────────────────────────────── + +/** + * ONE RECORDING'S LIFE CYCLE (lib/ingredients/stages.mjs): `/ingredients/<channel>/<video>`, and with `win` one + * of its clip windows (`?window=<from>-<to>`, the window's own two-decimal name). Either Rumble id finds it. + */ +export function ingredientHref(ch: string, id: string, win?: { from: number; to: number } | null): string { + return withQuery(`/ingredients/${encodeURIComponent(ch)}/${encodeURIComponent(id)}`, { + window: win && Number.isFinite(win.from) && Number.isFinite(win.to) ? `${win.from.toFixed(2)}-${win.to.toFixed(2)}` : null, + }); +} diff --git a/umtool/lib/ingredients.ts b/umtool/lib/ingredients.ts @@ -0,0 +1,134 @@ +import { CHANNELS_DIR, REPORTS_ROOT } from "./paths"; +import { loadUsageIndex } from "./ingredients/usedIn.mjs"; +import { readIngredient as readAt, STAGES as STAGE_LIST } from "./ingredients/stages.mjs"; + +// The app's view of lib/ingredients/ (lane L5, the ingredient life-cycle rail), typed and bound to the roots. +// The readers, the file formats and the rules are there (plain ESM, unit-tested); `umtool ingredient` prints +// the same object. SERVER ONLY. +// +// The usage index is memoised for a few seconds on globalThis (every bundle shares one copy, the rail-counts +// lesson): a rebuild is a walk and a stat per manifest, and a page asks once per render. A write here clears it. + +export type PillKind = "ok" | "count" | "warn" | "none"; +export type Pill = { kind: PillKind; n?: number }; +export type UseRow = { + project: string; + clipId: string; + start: number | null; + end: number | null; + cutStart: number | null; + cutEnd: number | null; + quote: string | null; + inDraft: boolean; + cites: string[]; + versions: { id: string; kind: "version" | "rendered"; start: number | null; end: number | null; cutStart: number | null; cutEnd: number | null }[]; +}; +export type WindowRow = { + name: string; + file: string; + from: number; + to: number; + bytes: number; + mtime: string; + desynced: boolean; + focused: boolean; + orphan: boolean; + serves: { project: string; clipId: string }[]; + partly: { project: string; clipId: string }[]; + sidecar: { + requestedBy: string | null; + manifest: string | null; + clipId: string | null; + reason: string | null; + fetchedAt: string | null; + source: string | null; + syncOk: boolean | null; + clock: { id: string | null; offset: number | null; certain: boolean } | null; + } | null; +}; +type Base = { key: string; label: string; pill: Pill; line: string }; +export type Stage = Base & Record<string, unknown>; +export type FoundStage = Base & { + findClips: { at: string | null; project: string; url: string | null; segments: number; segment: string | null; created: boolean } | null; + marks: { session: string; query: string | null; state: string; at: string | null }[]; + candidates: { case: string; key: string | null; from: number | null; to: number | null; title: string | null; hits: number }[]; +}; +export type DownloadedStage = Base & { + meta: { bytes: number; id: string | null; title: string | null; webpageUrl: string | null; uploadDate: string | null; extractor: string | null } | null; + history?: { count: number; lastAt: string | null; lastBy: string | null } | null; + outcome?: { status: string; finishedAt: string | null; attempts: number; webpageUrl: string | null; error: string | null } | null; + availability?: { availability: string; checkedAt: string | null } | null; + saved?: { file: string; height: number | null; reachable: boolean } | null; + imported?: { count: number; lastAt: string | null; via: string | null } | null; + media: { name: string; link: boolean; reachable: boolean; bytes: number | null }[]; + captions?: string[]; + problems?: string[]; +}; +export type TranscribedStage = Base & { + cues: { bytes: number; source: string | null; format: string | null; vttFile: string | null; engine: string | null; platform: string | null; title: string | null; uploadDate: string | null; duration: number | null; lastEnd: number | null; coverage: number | null } | null; + pin?: Record<string, unknown> | null; + outcome?: { at: string | null; worker: string | null; durationMs: number | null; salvaged: boolean } | null; + words?: { bytes: number } | null; + captions?: string[]; +}; +export type ClockStage = Base & { + clock: { id: string; ok: boolean; source: string | null; target: string | null; segments: number; steps: number; residualMs: number | null; measuredAt: string | null } | null; +}; +export type WindowsStage = Base & { + windows: WindowRow[]; + uncovered: { project: string; clipId: string; from: number | null; to: number | null }[]; + savedWhole: boolean; + /** The saved whole recording's path when its drive does not answer, else null. */ + savedUnreachable: string | null; + focus: { from: number; to: number; name: string; found: boolean } | null; +}; +export type UsedStage = Base & { rows: UseRow[] }; +export type CheckedStage = Base & { clips: { project: string; clipId: string; hasQuote: boolean; status: string | null; offset: number | null; current: boolean; checkedAt: string | null }[] }; +export type RenderedStage = Base & { + renders: { project: string; clipId: string; version: string | null; kind: string; label: string | null; state: string | null; seconds: number | null; endedAt: string | null; cut: { from: number | null; to: number | null } | null }[]; +}; +export type PublishedStage = Base & { links: { project: string; clipId: string; url: string | null; state: string | null; fix: string | null; checkedAt: string | null }[] }; + +export type Ingredient = { + ch: string; + id: string; + dirId: string; + siteId: string | null; + platform: string | null; + exists: boolean; + title: string | null; + webpageUrl: string | null; + duration: number | null; + uploadDate: string | null; + notes: string[]; + focus: { from: number; to: number; name: string; found: boolean } | null; + stages: [FoundStage, DownloadedStage, TranscribedStage, ClockStage, WindowsStage, UsedStage, CheckedStage, RenderedStage, PublishedStage]; +}; + +export const STAGES = STAGE_LIST as { key: string; label: string }[]; + +const MEMO_MS = 5_000; +const KEY = Symbol.for("umtool.usage-index"); +type Memo = { at: number; value: Promise<Record<string, unknown>> } | null; +const store = globalThis as unknown as Record<symbol, Memo>; + +export function clearUsageIndex(): void { + store[KEY] = null; +} + +export function usageIndex(): Promise<Record<string, unknown>> { + const m = store[KEY]; + if (m && Date.now() - m.at < MEMO_MS) return m.value; + const value = loadUsageIndex({ reportsRoot: REPORTS_ROOT, channelsDir: CHANNELS_DIR }).then((r) => r.index as Record<string, unknown>); + const entry = { at: Date.now(), value }; + store[KEY] = entry; + value.catch(() => { + if (store[KEY] === entry) store[KEY] = null; + }); + return value; +} + +/** One recording's nine stages (lib/ingredients/stages.mjs), or null for a channel or id that is not one. */ +export async function readIngredient(ch: string, id: string, window: string | null = null): Promise<Ingredient> { + return (await readAt({ channelsDir: CHANNELS_DIR, reportsRoot: REPORTS_ROOT, ch, id, window, index: await usageIndex() })) as Ingredient; +} diff --git a/umtool/lib/ingredients/actions.mjs b/umtool/lib/ingredients/actions.mjs @@ -0,0 +1,266 @@ +// THE RAIL'S ACTIONS (lane L5): one click on a stage runs its action through an action that already exists -- +// the editor's ops for what touches the corpus, umtool's own for what touches a project. Nothing here downloads, +// transcribes or deletes by itself: it builds the editor's body and asks. +// +// persist Downloaded POST /api/ops/persist-videos {items:[{slug, id}]} the channel's download queue; +// a Rumble recording is saved whole +// transcribe Transcribed POST /api/ops/transcribe-one {slug, id} the GPU (the editor's worker pool) +// fetch Windows POST /api/ops/fetch-windows {items, requestedBy, …} one paced job per platform queue: +// the project's own body (projectFetchBody), narrowed to this recording's unfetched clips +// evict Windows POST /api/ops/evict-clips {slug, id, windows:[name]} targeted: that one window +// quote-check Checked `umtool quote-check <project> --clips …` on the app's job runner (the route starts it) +// links Published POST /api/report/links {project, fix?} umtool's own link check +// +// Two steps, always: `plan` says what the action does, what it costs (network, the GPU, the disk) and which +// queue it lands on -- for fetch-windows and persist-videos the editor's own dry run answers -- and the page +// asks before it `start`s. An action that costs neither still says what it does. +// +// Plain ESM; the route (app/api/ingredients/action) is its only caller. +import { createHash } from "node:crypto"; +import { lstat, readlink, stat } from "node:fs/promises"; +import path from "node:path"; +import { resolveProject } from "../projects/core.mjs"; +import { askEditorOps, postFetchWindows, projectFetchBody, summarizeAnswer } from "../report/fetchWindows.mjs"; +import { audioFilesOf, present, readSavedVideoPointer } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; +import { ingredientIdentity, isChannelSlug, isVideoId, listWindows } from "./stages.mjs"; + +export const ACTIONS = ["persist", "transcribe", "fetch", "evict", "quote-check", "links"]; +const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; + +export class ActionError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; + +async function projectOf(id, reportsRoot) { + const r = await resolveProject(String(id ?? ""), reportsRoot); + if (!r?.project) throw new ActionError(`no project "${id}"`, 404); + return r.project; +} + +function clipList(v) { + const list = (Array.isArray(v) ? v : String(v ?? "").split(",")).map((s) => String(s).trim()).filter(Boolean); + if (!list.length) throw new ActionError("name the clips (clips: [ids])"); + for (const c of list) if (!CLIP_ID.test(c)) throw new ActionError(`"${c}" is not a clip id`); + return [...new Set(list)]; +} + +/** + * A KEY FOR WHAT THE PLAN SHOWED: `start` carries it back, and the action is re-read and refused when it no + * longer matches (a fetch body that changed, a window refetched or set aside since the page asked). + */ +const keyOf = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 16); +const fetchKey = (body) => keyOf(body.items.map((i) => [String(i.id), i.from, i.to, String(i.clipId ?? "")]).sort()); +const evictKey = (w, twins) => keyOf([w.file, w.bytes, w.mtime, ...twins.map((t) => [t.file, t.bytes, t.mtime])]); +const plainKey = (action, idn) => keyOf([action, idn.ch, idn.dirId]); + +/** + * AN UNMOUNTED DRIVE IS NOT A MISSING FILE (AGENTS.md, "A channel's media may live on another drive"): a media + * link that does not resolve, the channel's media/ linked to a drive not answering, a saved video whose file does + * not answer. A plan that read those as "absent" would offer to download again what is only out of reach, so the + * plan says which drive, costs nothing and offers no Start, and a start is refused. null when everything answers. + * @param {Awaited<ReturnType<typeof ingredientIdentity>>} idn + * @param {{ saved?: boolean }} [o] also the saved-video store's file (persist) + */ +export async function unreachableOf(idn, { saved = false } = {}) { + const channelMedia = path.join(idn.dir, "..", "..", "media"); + if (idn.mediaDrive === "missing") { + const to = await readlink(channelMedia).catch(() => null); + return `the channel's media drive does not answer (${idn.ch}/media -> ${to ?? "?"}): mount it, or re-point its location on /storage`; + } + if (!idn.exists) return null; + const dangling = []; + for (const a of await audioFilesOf(idn.dir)) { + const l = await lstat(a.path).catch(() => null); + if (l?.isSymbolicLink() && !(await stat(a.path).catch(() => null))) dangling.push(`${a.name} -> ${(await readlink(a.path).catch(() => null)) ?? "?"}`); + } + if (dangling.length) return `its media does not answer (${dangling.join(", ")}): the drive it lives on is not mounted`; + if (saved) { + const pointer = await readSavedVideoPointer(idn.dir); + if (pointer && !(await present(pointer.path))) return `its saved video does not answer (${pointer.path}): the saved-video store's drive is not mounted`; + } + return null; +} + +const unreachablePlan = (action, why) => ({ action, what: `Not now: ${why}`, cost: null, queue: "—", unreachable: why, start: null }); + +/** The fetch-windows bodies for the named clips of one project, narrowed to this recording (one per project). */ +async function fetchBodyFor(project, clips, idn) { + const { body, skipped } = await projectFetchBody(project, { localIds: true }); + const want = new Set(clips); + const items = body.items.filter((it) => it.slug === idn.ch && String(it.id) === idn.dirId && want.has(String(it.clipId))); + if (!items.length) { + const why = skipped.filter((s) => want.has(s.clipId)).map((s) => `${s.clipId}: ${s.why}`); + throw new ActionError(`no window of ${idn.ch}/${idn.dirId} to fetch for ${clips.join(", ")}${why.length ? ` (${why.join("; ")})` : ""}`); + } + return { ...body, requestedBy: `${body.requestedBy} (ingredient rail)`, items }; +} + +/** + * What an action will do, before it does it. + * + * @param {{ action: string, ch: string, id: string, project?: string, clips?: string[] | string, window?: string, fix?: boolean }} req + * @param {{ cfg: { url: string, token: string, fetch?: typeof fetch }, reportsRoot: string, channelsDir: string }} ctx + * @returns {Promise<{ action: string, what: string, cost: "network" | "gpu" | "disk" | null, queue: string, start: { route: string, body: Record<string, any> }, plan?: any }>} + */ +export async function planAction(req, ctx) { + const { action } = req; + if (!ACTIONS.includes(action)) throw new ActionError(`action is one of ${ACTIONS.join(", ")}`); + if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording"); + const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id }); + const self = (extra = {}) => ({ route: "/api/ingredients/action", body: { action, ch: idn.ch, id: idn.dirId, ...extra, step: "start" } }); + const rumble = idn.platform === "rumble"; + + if (action === "persist") { + const away = await unreachableOf(idn, { saved: true }); + if (away) return unreachablePlan(action, away); + const body = { items: [{ slug: idn.ch, id: idn.dirId }] }; + const plan = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { ...body, dryRun: true } }); + // The editor's plan buckets each item: { saved: {count, items}, toFetch, noUrl, unknown, willFetch }. + const buckets = plan?.plan ?? plan?.buckets ?? {}; + const count = (k) => (Array.isArray(buckets?.[k]) ? buckets[k].length : Number(buckets?.[k]?.count ?? 0) || 0); + const already = count("saved"); + return { + action, + what: already + ? `The source video is already saved: the editor will skip it` + : `Download the source video to the saved-video store${rumble ? " -- on Rumble the WHOLE recording, saved once (the editor's whole-recording rule)" : ""}`, + cost: already ? null : "network", + queue: `the ${idn.ch} channel's download queue (the editor's)`, + plan: { saved: already, toFetch: count("toFetch"), noUrl: count("noUrl"), unknown: count("unknown") }, + start: self({ key: plainKey(action, idn) }), + }; + } + + if (action === "transcribe") { + const away = await unreachableOf(idn); + if (away) return unreachablePlan(action, away); + const audio = idn.exists ? (await Promise.all((await audioFilesOf(idn.dir)).map(async (a) => ((await present(a.path)) ? a.name : null)))).filter(Boolean) : []; + return { + action, + what: audio.length + ? `Transcribe ${audio[0]} through the editor's worker pool (an existing transcript is replaced by the new one)` + : `Download the audio, then transcribe it (a YouTube video with English captions has those fetched instead)`, + cost: "gpu", + queue: audio.length ? `transcribe-one:${idn.ch}:${idn.dirId}` : `the ${idn.ch} channel's platform queue for the download, then transcribe-one:${idn.ch}:${idn.dirId}`, + start: self({ key: plainKey(action, idn) }), + }; + } + + if (action === "fetch") { + const project = await projectOf(req.project, ctx.reportsRoot); + const clips = clipList(req.clips); + const body = await fetchBodyFor(project, clips, idn); + const answer = await postFetchWindows(ctx.cfg, body, { dryRun: true }); + const groups = Array.isArray(answer?.groups) ? answer.groups : []; + const queues = [...new Set(groups.map((g) => g.queueKey).filter(Boolean))]; + const cached = Array.isArray(answer?.cached) ? answer.cached.length : Number(answer?.cached ?? 0) || 0; + return { + action, + what: `Fetch ${plural(body.items.length, "window")} for ${project.id} (${clips.join(", ")})${rumble ? " -- Rumble: cut from the whole recording, which the editor saves once" : ""}${cached ? `; ${cached} already on disk` : ""}`, + cost: "network", + queue: queues.length ? queues.join(", ") : "the editor's paced fetch queue for the platform", + plan: { summary: summarizeAnswer(answer) }, + start: self({ project: project.id, clips, key: fetchKey(body) }), + }; + } + + if (action === "evict") { + const { w, twins } = await evictTarget(idn, req.window); + const mb = (b) => `${(b / 1e6).toFixed(1)} MB`; + return { + action, + what: + `Delete the cached window ${w.file} (${mb(w.bytes)})` + + // The editor's targeted evict names the `<from>-<to>` stem, and a set-aside twin of the span goes with it. + (twins.length ? `, and with it ${twins.map((t) => `${t.file} (${mb(t.bytes)})`).join(", ")}: the editor evicts a span's set-aside twin with it` : "") + + `. A window is a cache: it can be fetched again, and that fetch is the cost. Nothing knows whether a project still cites it`, + cost: "disk", + queue: "an evict-clips job on the editor", + start: self({ window: w.file, key: evictKey(w, twins) }), + }; + } + + if (action === "quote-check") { + const project = await projectOf(req.project, ctx.reportsRoot); + const clips = clipList(req.clips); + return { + action, + what: `Check ${clips.join(", ")} in ${project.id}: each clip's seconds transcribed by the editor, its quote found in them (writes ${project.id}/quote-check.json)`, + cost: "gpu", + queue: "umtool's job runner (one job at a time); the transcriptions on the editor's transcribe queue", + start: self({ project: project.id, clips }), + }; + } + + // links + const project = await projectOf(req.project, ctx.reportsRoot); + return { + action, + what: req.fix === true + ? `Rewrite each dead link of ${project.id} the last check knows the fix for, then check every link again` + : `Check that each clip QR of ${project.id} opens on its site (the archive's corpus.json, the channel's manifest, the shard's record)`, + cost: "network", + queue: "this umtool, one request at a time to the site (cached)", + start: { route: "/api/report/links", body: { project: project.id, ...(req.fix === true ? { fix: true } : {}) } }, + }; +} + +/** + * Do it: the editor-bound actions (persist, transcribe, fetch, evict). quote-check is started by the route on + * the app's job runner; links goes to /api/report/links. + * @returns {Promise<{ ok: true, action: string, jobIds: string[], message: string, answer?: any }>} + */ +export async function startAction(req, ctx) { + const { action } = req; + if (!["persist", "transcribe", "fetch", "evict"].includes(action)) throw new ActionError(`${action} is not started here`); + if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording"); + const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id }); + if (typeof req.key !== "string" || !req.key) throw new ActionError("start carries the plan's key: ask for the plan first"); + const changed = () => new ActionError("it changed since the plan was shown: ask again", 409); + if (action === "persist" || action === "transcribe") { + const away = await unreachableOf(idn, { saved: action === "persist" }); + if (away) throw new ActionError(`refused: ${away}`, 409); + if (req.key !== plainKey(action, idn)) throw changed(); + } + const ids = (a) => [...new Set([...(Array.isArray(a?.jobIds) ? a.jobIds : []), ...(a?.jobId ? [a.jobId] : [])].map(String))]; + if (action === "persist") { + const a = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { items: [{ slug: idn.ch, id: idn.dirId }] } }); + return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `persist started (${ids(a).join(", ")})` : "nothing to persist: already saved", answer: a }; + } + if (action === "transcribe") { + const a = await askEditorOps(ctx.cfg, "/api/ops/transcribe-one", { method: "POST", body: { slug: idn.ch, id: idn.dirId } }); + return { ok: true, action, jobIds: ids(a), message: a?.instead === "captions" ? String(a.message ?? "captions fetched instead") : `transcription queued (${ids(a).join(", ")})`, answer: a }; + } + if (action === "fetch") { + const project = await projectOf(req.project, ctx.reportsRoot); + const body = await fetchBodyFor(project, clipList(req.clips), idn); + if (req.key !== fetchKey(body)) throw changed(); + const a = await postFetchWindows(ctx.cfg, body); + return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `fetch started (${ids(a).join(", ")})` : "nothing to fetch: every window is on disk or in flight", answer: summarizeAnswer(a) }; + } + const { w, twins } = await evictTarget(idn, req.window); + if (req.key !== evictKey(w, twins)) throw changed(); + const a = await askEditorOps(ctx.cfg, "/api/ops/evict-clips", { method: "POST", body: { slug: idn.ch, id: idn.dirId, windows: [w.name] } }); + return { ok: true, action, jobIds: ids(a), message: `evicting ${w.name} (${ids(a).join(", ")})`, answer: a }; +} + +/** The window a targeted evict names, EXACTLY by its file, and the set-aside twin of its span that goes with it. */ +async function evictTarget(idn, file) { + const f = String(file ?? ""); + const all = idn.exists ? await listWindows(idn.dir) : []; + const w = all.find((x) => x.file === f); + if (!w) throw new ActionError(`no window file "${f}" in ${idn.ch}/${idn.dirId}/clips/`, 404); + return { w, twins: all.filter((x) => x !== w && x.name === w.name) }; +} + +/** The argv of a quote check of some of a project's clips (the route runs it on the app's job runner). */ +export function quoteCheckArgv(umtoolDir, project, clips) { + return [process.execPath, path.join(umtoolDir, "bin", "umtool.mjs"), "quote-check", project, "--clips", clips.join(",")]; +} + +export { clipList as parseClipList }; diff --git a/umtool/lib/ingredients/actions.test.mjs b/umtool/lib/ingredients/actions.test.mjs @@ -0,0 +1,136 @@ +// node --test umtool/lib/ingredients/actions.test.mjs +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { planAction, startAction } from "./actions.mjs"; +import { readIngredient } from "./stages.mjs"; + +/** An editor that records what it was asked and answers like the real one would, enough for these tests. */ +function editor() { + const asked = []; + const fetch = async (url, init) => { + const body = init?.body ? JSON.parse(init.body) : null; + const route = new URL(url).pathname; + asked.push({ route, body }); + let answer = { ok: true, jobId: `job-${asked.length}` }; + if (route === "/api/ops/fetch-windows") answer = body.dryRun ? { ok: true, dryRun: true, groups: [{ platform: "youtube", queueKey: "clips:youtube", items: body.items }], cached: [], inFlight: [], unresolved: [] } : { ok: true, jobs: [], jobIds: ["fw-1"], jobId: "fw-1", groups: [], cached: [], inFlight: [], unresolved: [], refused: [] }; + if (route === "/api/ops/persist-videos" && body.dryRun) answer = { ok: true, dryRun: true, plan: { saved: { count: 0, items: [] }, toFetch: { count: 1, items: [] }, willFetch: 1 } }; + return new Response(JSON.stringify(answer), { status: 200, headers: { "content-type": "application/json" } }); + }; + return { asked, cfg: { url: "http://editor.test", token: "t", fetch } }; +} + +async function corpus() { + const root = await mkdtemp(path.join(tmpdir(), "actions-")); + const channels = path.join(root, "channels"); + const reports = path.join(root, "reports"); + const v = path.join(channels, "chan", "data", "vid"); + await mkdir(path.join(v, "clips"), { recursive: true }); + await writeFile(path.join(channels, "chan", "config.json"), JSON.stringify({ platform: "youtube" })); + await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: "vid", title: "t" })); + await writeFile(path.join(v, "clips", "10.00-40.00.mp4"), Buffer.alloc(100)); + await writeFile(path.join(v, "clips", "10.00-40.00.desynced.mp4"), Buffer.alloc(70)); + await writeFile(path.join(v, "clips", "50.00-60.00.mp4"), Buffer.alloc(10)); + const a = path.join(reports, "f", "a"); + await mkdir(a, { recursive: true }); + await writeFile(path.join(a, "video.manifest.json"), JSON.stringify({ provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline: [{ type: "clip", id: "a1", video: "vid", start: 100, end: 110 }] })); + return { root, channels, reports, v, a }; +} + +test("an unmounted media drive: transcribe and persist plan 'not now', name the drive, offer no Start, and a start is refused", async () => { + const { root, channels, reports, v } = await corpus(); + try { + // The channel's media/ links to a drive that is not there; the audio is a link into it. + await symlink(path.join(root, "gone-drive", "chan", "media"), path.join(channels, "chan", "media")); + await symlink("../../media/vid/audio.mp3", path.join(v, "audio.mp3")); + const { cfg, asked } = editor(); + const ctx = { cfg, reportsRoot: reports, channelsDir: channels }; + for (const action of ["transcribe", "persist"]) { + const plan = await planAction({ action, ch: "chan", id: "vid" }, ctx); + assert.equal(plan.cost, null, action); + assert.equal(plan.start, null, action); + assert.match(plan.unreachable, /media drive does not answer .*gone-drive/, action); + await assert.rejects(startAction({ action, ch: "chan", id: "vid", key: "x" }, ctx), (e) => e.status === 409 && /refused: the channel's media drive/.test(e.message)); + } + assert.deepEqual(asked, [], "the editor was never asked"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a dangling audio link alone (the channel's media/ fine) is 'not now' too -- never 'download the audio'", async () => { + const { root, channels, reports, v } = await corpus(); + try { + await mkdir(path.join(channels, "chan", "media"), { recursive: true }); + await symlink("../../media/vid/audio.mp3", path.join(v, "audio.mp3")); + const { cfg } = editor(); + const plan = await planAction({ action: "transcribe", ch: "chan", id: "vid" }, { cfg, reportsRoot: reports, channelsDir: channels }); + assert.match(plan.what, /^Not now: its media does not answer \(audio\.mp3 -> \.\.\/\.\.\/media\/vid\/audio\.mp3\)/); + assert.equal(plan.start, null); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a saved video whose drive is gone: persist is 'not now', and the Windows stage says it does not answer", async () => { + const { root, channels, reports, v } = await corpus(); + try { + await writeFile(path.join(v, "saved-video.json"), JSON.stringify({ dir: path.join(root, "gone-store", "chan"), file: "vid.mp4" })); + const { cfg } = editor(); + const plan = await planAction({ action: "persist", ch: "chan", id: "vid" }, { cfg, reportsRoot: reports, channelsDir: channels }); + assert.match(plan.unreachable, /saved video does not answer/); + const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", indexFile: path.join(root, "state", "u.json") }); + const win = r.stages.find((s) => s.key === "windows"); + assert.equal(win.pill.kind, "warn"); + assert.match(win.line, /the saved whole recording does not answer/); + assert.equal(win.savedWhole, false); + assert.equal(win.uncovered.length, 1, "nothing cuts from an unreachable recording: the clip is not covered"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("start carries the plan's key: none, or a stale one, is refused before the editor is asked", async () => { + const { root, channels, reports, a } = await corpus(); + try { + const { cfg, asked } = editor(); + const ctx = { cfg, reportsRoot: reports, channelsDir: channels }; + const plan = await planAction({ action: "fetch", ch: "chan", id: "vid", project: "f/a", clips: ["a1"] }, ctx); + assert.equal(plan.start.body.key.length, 16); + await assert.rejects(startAction({ ...plan.start.body, key: undefined }, ctx), /ask for the plan first/); + // The clip moves after the plan was shown: the fetch would differ, so the start is refused. + await writeFile(path.join(a, "video.manifest.json"), JSON.stringify({ provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline: [{ type: "clip", id: "a1", video: "vid", start: 200, end: 210 }] })); + await assert.rejects(startAction(plan.start.body, ctx), (e) => e.status === 409 && /changed since the plan was shown/.test(e.message)); + const again = await planAction({ action: "fetch", ch: "chan", id: "vid", project: "f/a", clips: ["a1"] }, ctx); + const r = await startAction(again.start.body, ctx); + assert.deepEqual(r.jobIds, ["fw-1"]); + const starts = asked.filter((x) => x.route === "/api/ops/fetch-windows" && !x.body.dryRun); + assert.equal(starts.length, 1); + assert.deepEqual(starts[0].body.items.map((i) => [i.from, i.to, i.clipId]), [[197, 213, "a1"]]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("evict names one window by its FILE, says its set-aside twin goes with it, and refuses a window changed since", async () => { + const { root, channels, reports, v } = await corpus(); + try { + const { cfg, asked } = editor(); + const ctx = { cfg, reportsRoot: reports, channelsDir: channels }; + await assert.rejects(planAction({ action: "evict", ch: "chan", id: "vid", window: "10.00-40.00" }, ctx), /no window file/); + const plan = await planAction({ action: "evict", ch: "chan", id: "vid", window: "10.00-40.00.mp4" }, ctx); + assert.match(plan.what, /^Delete the cached window 10\.00-40\.00\.mp4 .*and with it 10\.00-40\.00\.desynced\.mp4/); + const lone = await planAction({ action: "evict", ch: "chan", id: "vid", window: "50.00-60.00.mp4" }, ctx); + assert.doesNotMatch(lone.what, /and with it/); + // Refetched since (other bytes under the same name): the key no longer matches. + await writeFile(path.join(v, "clips", "50.00-60.00.mp4"), Buffer.alloc(99)); + await assert.rejects(startAction(lone.start.body, ctx), (e) => e.status === 409); + const ok = await startAction(plan.start.body, ctx); + assert.equal(ok.ok, true); + assert.deepEqual(asked.at(-1), { route: "/api/ops/evict-clips", body: { slug: "chan", id: "vid", windows: ["10.00-40.00"] } }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/ingredients/cli.mjs b/umtool/lib/ingredients/cli.mjs @@ -0,0 +1,78 @@ +// `umtool ingredient <ch>/<id> [--window a-b] [--used-in] [--json]` (lane L5): one recording's life cycle -- +// the CLI twin of /ingredients/<ch>/<id> (lib/ingredients/stages.mjs reads it; the page renders the same object). +// Either Rumble id finds the recording, and both are printed. Read-only over the corpus; the usage index it +// brings up to date lives in umtool's state dir (<REPORTS_ROOT>/.umtool/usage-index.json). +// +// Plain ESM: the CLI runs it under bare node. +import { CHANNELS_DIR, REPORTS_ROOT } from "../paths.mjs"; +import { parseWindowParam, pillGlyph, readIngredient, spanText } from "./stages.mjs"; + +export const INGREDIENT_USAGE = [ + "usage: umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]", + " a recording's life cycle, nine stages: found, downloaded, transcribed, clock, windows, used in, checked,", + " rendered, published -- each ✓, a count, ! or —, and its line. A Rumble recording answers to its folder", + " slug or its embed id. --window: one clip window (its <from>-<to> name); the stages after it narrow to", + " the clips it plays. --used-in: every project clip that cuts from it (draft and saved versions), alone.", + " --json: the page's object. The page: /ingredients/<channel>/<video>.", +].join("\n"); + +class CliError extends Error {} + +/** + * @param {string[]} args the words after `ingredient` + * @param {{ reportsRoot?: string, channelsDir?: string, out?: (s: string) => void, err?: (s: string) => void }} [o] + * @returns {Promise<number>} + */ +export async function ingredientCommand(args, { reportsRoot = REPORTS_ROOT, channelsDir = CHANNELS_DIR, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--window") { + if (i + 1 >= args.length) throw new CliError("--window needs <from>-<to>"); + flags.set(a, args[++i]); + } else if (a === "--json" || a === "--used-in" || a === "--help") flags.set(a, true); + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (flags.has("--help") || words.length !== 1) { + (flags.has("--help") ? out : err)(INGREDIENT_USAGE); + return flags.has("--help") ? 0 : 2; + } + const m = /^([^/]+)\/([^/@]+)$/.exec(words[0]); + if (!m) throw new CliError(`"${words[0]}" is not <channel>/<video>`); + const win = flags.has("--window") ? parseWindowParam(flags.get("--window")) : null; + if (flags.has("--window") && !win) throw new CliError(`--window "${flags.get("--window")}" is not <from>-<to>`); + const r = await readIngredient({ channelsDir, reportsRoot, ch: m[1], id: m[2], window: win }); + const used = r.stages.find((s) => s.key === "used"); + if (flags.has("--used-in")) { + if (flags.has("--json")) out(JSON.stringify(used.rows, null, 2)); + else if (!used.rows.length) out(used.line); + else for (const u of used.rows) out(useLine(u)); + return 0; + } + if (flags.has("--json")) { + out(JSON.stringify(r, null, 2)); + return 0; + } + out(`${r.ch}/${r.dirId}${r.siteId ? ` (the archive's id: ${r.siteId})` : ""}${r.platform ? ` · ${r.platform}` : ""}${r.title ? ` · ${r.title}` : ""}`); + if (r.focus) out(`window ${r.focus.name}${r.focus.found ? "" : " (no such window on disk)"}`); + for (const n of r.notes) out(`note: ${n}`); + for (const s of r.stages) out(`${pillGlyph(s.pill).padStart(3)} ${s.label.padEnd(12)} ${s.line}`); + if (used.rows.length) { + out(""); + for (const u of used.rows) out(useLine(u)); + } + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +const useLine = (u) => { + const play = u.cutStart != null || u.cutEnd != null ? ` (cut ${spanText(u.cutStart ?? u.start, u.cutEnd ?? u.end)})` : ""; + const where = [u.inDraft ? "draft" : null, ...u.versions.map((v) => v.id)].filter(Boolean).join(", "); + return ` ${u.project} ${u.clipId} ${spanText(u.start, u.end)}${play} [${where}]`; +}; 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,570 @@ +// 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 { 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>` -> {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, 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<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, 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" ? "!" : "—"); 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 @@ -0,0 +1,276 @@ +// 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] } }, +// 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 +// 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)); + // 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}/${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); + 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, dirIds, 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 } : {}) }); + // byIngredient is a function of the files' clips and the directory ids alone: with no manifest parsed or + // dropped and the same directory answers, it is what was written -- no need to compare the whole index. + const changed = !previous || built.stats.parsed > 0 || built.stats.dropped > 0 || !sameDirIds(previous.dirIds, built.index.dirIds); + if (write && changed) await writeUsageIndex(file, built.index).catch(() => {}); + return { ...built, file, written: write && changed }; +} + +/** Do two dirIds maps agree, entry by entry? */ +function sameDirIds(a, b) { + const ka = Object.keys(a ?? {}); + if (ka.length !== Object.keys(b ?? {}).length) return false; + return ka.every((k) => b[k] && b[k].dir === a[k]?.dir && (b[k].dataMtimeMs ?? null) === (a[k]?.dataMtimeMs ?? null)); +} + +/** + * 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 }); + } +}); diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -1,5 +1,5 @@ import { notFound } from "next/navigation"; -import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; +import { projectsHref, clipBenchHref, ingredientHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; import type { ClipBenchData } from "@/components/projects/ClipBench"; import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell"; import { @@ -41,6 +41,8 @@ export type BenchTopSpec = { next: BenchLink | null; keys: BenchKey[]; note: string; + /** The clip's source, across its life cycle (lane L5). */ + life?: BenchLink | null; }; /** @@ -296,6 +298,8 @@ export async function clipBenchData( ], // Which source is playing. note: `${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`, + // Its source's life cycle: found, downloaded, … published (lane L5). + life: entry.channel && entry.video ? { href: ingredientHref(String(entry.channel), String(entry.video)), label: "Life cycle" } : null, }; return { data, top }; } diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -469,3 +469,6 @@ export async function followRun(cfg, projectDir, run) { } return states; } + +/** One request to the editor's ops (`ask` above): the ingredient rail's other editor actions (lib/ingredients/actions.mjs). */ +export { ask as askEditorOps }; diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -208,6 +208,8 @@ export async function playViewWith(project, { take = null, bare = false, postFor dateLabel: dateKey === null ? null : /^\d{1,2}\s+[A-Za-z]{3}/.test(onscreenDate) ? onscreenDate : dateKeyLabel(dateKey), section: e.section ?? null, channel: typeof e.channel === "string" ? e.channel : null, + // The channel the clip cuts from, the provenance's when the clip names none: its life cycle's address (lane L5). + sourceChannel: typeof e.channel === "string" && e.channel ? e.channel : typeof selected.provenance?.channelSlug === "string" ? selected.provenance.channelSlug : null, heading: text(e.onscreen?.title) || text(e.title) || text(e.quote) || e.id, date: text(e.date) || text(e.onscreen?.title) || null, quote: text(e.quote) || null,