commit 604b858bc2ae3b30a9f05425d3de81e107beb97c
parent 0dee7b7dca3540f99fe12b8f4d94883e021e50c9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 19:38:44 -0500
umtool: /ingredients/<ch>/<id> -- the ingredient rail, its panels and its actions (lane L5)
One recording's nine stages across the top (✓ / a count / ! / —), the selected stage's panel below;
?window=<from>-<to> focuses one clip window (the stages after Windows show the clips it plays),
?stage= keeps the selection. Either Rumble id finds the recording and the head shows both. Each
stage's action asks POST /api/ingredients/action {step: "plan"} first -- what it does, what it costs
(network, GPU, a deleted cache file) and the queue it lands on, from the editor's own dry run for
fetch-windows and persist-videos -- and starts only on Start: persist-videos, transcribe-one,
fetch-windows (the project's own body, narrowed to this recording's unfetched clips) and targeted
evict-clips through the editor; quote-check as a umtool job; link check / fix through
/api/report/links. ingredientHref(ch, id, win?) in lib/hrefs.ts; lib/report/fetchWindows.mjs exports
its editor ask (askEditorOps) for the rail's other ops.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 983 insertions(+), 0 deletions(-)
diff --git a/umtool/app/api/ingredients/action/route.ts b/umtool/app/api/ingredients/action/route.ts
@@ -0,0 +1,60 @@
+import { CHANNELS_DIR, REPORTS_ROOT } from "@/lib/paths";
+import { jobView, runningJob, startJob } from "@/lib/jobs";
+import { refuseCaller } from "@/lib/report/caller";
+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) {
+ 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 } : {}),
+ };
+ 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,49 @@
+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: `${decodeURIComponent(channel)}/${decodeURIComponent(id)} · life cycle · umtool` };
+}
+
+export default async function IngredientPage({ params, searchParams }: { params: Promise<Params>; searchParams: Promise<Search> }) {
+ const { channel, id } = await params;
+ const ch = decodeURIComponent(channel);
+ const vid = decodeURIComponent(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/components/ingredients/IngredientRail.tsx b/umtool/components/ingredients/IngredientRail.tsx
@@ -0,0 +1,519 @@
+"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-2 rounded-[3px] border px-2 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.6rem] shrink-0 rounded-[3px] border px-1 text-center font-mono text-[11.5px] 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; start: { route: string; body: Record<string, unknown> } };
+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) 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"}>
+ <p className="m-0 text-text">{plan.what}</p>
+ <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">
+ <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.name}`} body={{ action: "evict", ...ingredient, window: w.name }} />
+ </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/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¬e=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,132 @@
+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;
+ 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,202 @@
+// 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 path from "node:path";
+import { resolveProject } from "../projects/core.mjs";
+import { askEditorOps, postFetchWindows, projectFetchBody, summarizeAnswer } from "../report/fetchWindows.mjs";
+import { audioFilesOf, present } 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)];
+}
+
+/** 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 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: { route: "/api/ingredients/action", body: { action, ch: idn.ch, id: idn.dirId, step: "start" } },
+ };
+ }
+
+ if (action === "transcribe") {
+ 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(),
+ };
+ }
+
+ 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 }),
+ };
+ }
+
+ if (action === "evict") {
+ const name = String(req.window ?? "");
+ const w = (idn.exists ? await listWindows(idn.dir) : []).find((x) => x.name === name || x.file === name);
+ if (!w) throw new ActionError(`no window "${name}" in ${idn.ch}/${idn.dirId}/clips/`, 404);
+ return {
+ action,
+ what: `Delete the cached window ${w.name} (${(w.bytes / 1e6).toFixed(1)} MB). 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.name }),
+ };
+ }
+
+ 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 });
+ 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);
+ 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 name = String(req.window ?? "");
+ const w = (idn.exists ? await listWindows(idn.dir) : []).find((x) => x.name === name);
+ if (!w) throw new ActionError(`no window "${name}" in ${idn.ch}/${idn.dirId}/clips/`, 404);
+ 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 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/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 };