Archilyzer · Source

archilyzer

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

commit 280211755350c4d7f98cc486cbb4164f93786cae
parent 415349706703163fb7a97553dfdd5f2f6bcc1841
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 03:19:18 -0500

umtool: the source backlog on a report video's page (UI notes item 16) -- Sources · Prioritize · Re-sweep when complete

The Overview tab's sources line: for each channel the cut cites (a clip's siteChannel, else its
channel, else the provenance's), "<channel> <transcribed>/<listed> transcribed · <held> held",
from the editor's own snapshot counts (GET /api/ops/channel/<slug>, which now also answers
`report.undownloaded`, the listed-and-not-downloaded count the snapshot keeps top-level),
never a walk of the disk; complete when nothing listed is left to download and nothing held to
transcribe (lib/report/sourceBacklog.mjs; the editor half in sourceBacklog.ts).

Prioritize asks the editor's POST /api/ops/channel-priority for its focus (every lane leads with
it), the channels already in focus kept, never writing settings; a site focus is refused in
words (the editor's to change).

Re-sweep when complete is the refresh check's pattern (lib/inbox/refresh.ts): a watch beside
the project (<project>/source-watch.json, one writer, temp + rename, never overwritten unread)
over the cited channels the editor archives; while it is armed every read of the backlog -- the
page's, and the Inbox's background check at most hourly -- records what it saw, and the first
with every watched channel complete FIRES it, once: an Inbox `sources-complete` card (Review,
Re-sweep) until Clear. The e2e stub answers the channel counts, the focus and channel-priority
(editor-stub-intake.mjs).

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

Diffstat:
Meditor/app/api/ops/channel/[slug]/route.ts | 4++++
Aumtool/app/api/report/source-backlog/route.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/OverviewTab.tsx | 4++++
Aumtool/components/projects/report/SourceBacklog.tsx | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/knobs.md | 15+++++++++++++++
Aumtool/e2e/fixtures/editor-stub-intake.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 5+++++
Mumtool/e2e/fixtures/intake-fixture.mjs | 16+++++++++++++++-
Aumtool/e2e/source-backlog.spec.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox.ts | 5++++-
Mumtool/lib/inbox/groups.mjs | 6+++++-
Aumtool/lib/inbox/sourceWatch.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/what.mjs | 1+
Aumtool/lib/report/sourceBacklog.mjs | 239+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/sourceBacklog.test.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/sourceBacklog.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 895 insertions(+), 3 deletions(-)

diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts @@ -114,6 +114,10 @@ export async function GET( generatedAt: snapshot.generatedAt, totals: snapshot.totals, buckets, + // Listed and not on disk (the download lane's backlog): top-level in + // the snapshot, not a bucket, so said here as a count. `totals.videos` + // + this is what the channel lists (umtool's source backlog line). + undownloaded: Array.isArray(snapshot.undownloadedIds) ? snapshot.undownloadedIds.length : null, } : null, }); diff --git a/umtool/app/api/report/source-backlog/route.ts b/umtool/app/api/report/source-backlog/route.ts @@ -0,0 +1,54 @@ +import { EditorError } from "@/lib/articles/generation"; +import { armSourceWatch, citedChannels, clearSourceWatch, SourceWatchError } from "@/lib/report/sourceBacklog.mjs"; +import { prioritize, readBacklog } from "@/lib/report/sourceBacklog"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// THE SOURCE BACKLOG of a report video (UI notes item 16, lib/report/sourceBacklog.*): +// +// GET ?project=<id> { channels: [{ slug, listed, held, transcribed, done, focused, … }], +// focus, editorError, watch, fired } (the read is recorded: a watch may fire) +// POST { project, op: "prioritize", slugs? } the editor's focus gains them (default: every cited channel), +// through its POST /api/ops/channel-priority -- never settings directly +// POST { project, op: "watch" } Re-sweep when complete: the Inbox says so once every cited channel the +// editor archives is done (one it does not is left out: `left`) +// POST { project, op: "unwatch" } +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers }); + return Response.json(await readBacklog(r.project.dir, r.manifest), { headers }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/source-backlog"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers }); + const cited = (citedChannels(r.manifest) as { slug: string }[]).map((c) => c.slug); + try { + if (body.op === "prioritize") { + const slugs = Array.isArray(body.slugs) ? body.slugs.map(String).filter((s) => cited.includes(s)) : cited; + return Response.json({ ok: true, ...(await prioritize(slugs)) }, { headers }); + } + if (body.op === "watch") { + // Only what the editor archives can ever be complete: a channel it does not answer for is left out, and said. + const now = await readBacklog(r.project.dir, r.manifest); + if (now.editorError) return Response.json({ error: `the editor did not answer: ${now.editorError}` }, { status: 502, headers }); + const slugs = now.channels.filter((c) => !c.error).map((c) => c.slug); + const left = now.channels.filter((c) => c.error).map((c) => c.slug); + return Response.json({ ok: true, ...(await armSourceWatch(r.project.dir, slugs)), ...(left.length ? { left } : {}) }, { headers }); + } + if (body.op === "unwatch") return Response.json({ ok: true, ...(await clearSourceWatch(r.project.dir)) }, { headers }); + return Response.json({ error: 'op is "prioritize", "watch" or "unwatch"' }, { status: 400, headers }); + } catch (e) { + const status = e instanceof EditorError ? e.status : e instanceof SourceWatchError ? ((e as SourceWatchError & { status?: number }).status ?? 400) : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx @@ -15,6 +15,7 @@ import type { Decision } from "@/lib/decisions"; import type { PieceFrame } from "@/lib/pieces/frame"; import { TONE, hms, type ReportTabProps } from "./shared"; import DecisionSettle from "./DecisionSettle"; +import SourceBacklog from "./SourceBacklog"; import { manifestToken } from "@/lib/report/manifest.mjs"; // The Overview tab (canvas "Piece · Overview"): the Next card, then the @@ -55,6 +56,9 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP <NextCard pieceId={frame.pieceId} title={frame.piece?.title ?? project.id} lifecycle={frame.lifecycle} /> </Suspense> + {/* How much of each cited channel the archive holds and has transcribed (UI notes item 16). */} + {clips.length > 0 && <SourceBacklog project={project.id} />} + <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]"> <div className="min-w-0 space-y-4"> {/* --- what is wrong, first ------------------------------------- */} diff --git a/umtool/components/projects/report/SourceBacklog.tsx b/umtool/components/projects/report/SourceBacklog.tsx @@ -0,0 +1,149 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; + +// --------------------------------------------------------------------------- +// THE SOURCE BACKLOG on a report video's page (UI notes item 16): for each +// channel the cut cites, "<channel> transcribed/listed · held · Prioritize", +// from the editor's own snapshot counts (GET /api/report/source-backlog). +// Prioritize puts the channel in the editor's focus through its ops action; +// "Re-sweep when complete" arms a watch the Inbox fires once the backlog of +// every cited channel is done (lib/report/sourceBacklog.mjs). +// --------------------------------------------------------------------------- + +type Row = { + slug: string; + listed: number | null; + held: number | null; + transcribed: number | null; + undownloaded: number | null; + untranscribed: number | null; + done: boolean; + focused: boolean; + clips: number; + tier: string | null; + error?: string; +}; +type View = { + channels: Row[]; + editorError: string | null; + watch: { slugs: string[]; armedAt: string; firedAt?: string } | null; + watchError: string | null; +}; + +const n = (v: number | null) => (v === null ? "?" : v.toLocaleString("en-US")); +const day = (iso: string) => new Date(iso).toLocaleDateString("en-GB", { day: "numeric", month: "short" }); + +export default function SourceBacklog({ project }: { project: string }) { + const [view, setView] = useState<View | null>(null); + const [error, setError] = useState<string | null>(null); + const [said, setSaid] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const load = useCallback(async () => { + const r = await fetch(`/api/report/source-backlog?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + const j = r ? ((await r.json().catch(() => null)) as (View & { error?: string }) | null) : null; + if (!r?.ok || !j) { + setError(j?.error ?? "the backlog could not be read"); + return; + } + setView(j); + }, [project]); + useEffect(() => { + void load(); + }, [load]); + const post = async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + setSaid(null); + try { + const r = await fetch("/api/report/source-backlog", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + if (!r.ok) setError(String(j.error ?? `HTTP ${r.status}`)); + return r.ok ? j : null; + } finally { + setBusy(false); + await load(); + } + }; + if (!view) return error ? <p className="m-0 text-[11px] text-[var(--color-dim)]">sources: {error}</p> : null; + if (!view.channels.length) return null; + // What the editor archives decides it: a channel it does not answer for is never "done". + const allDone = view.channels.filter((c) => !c.error).every((c) => c.done); + const w = view.watch; + return ( + <section data-testid="source-backlog" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="micro m-0">sources</h2> + {view.channels.map((c) => ( + <span key={c.slug} data-backlog-channel={c.slug} data-backlog-done={c.done ? "1" : "0"} className="flex flex-wrap items-baseline gap-1.5"> + <span className="font-mono text-[var(--color-text)]">{c.slug}</span> + {c.error ? ( + <span className="text-[11px] text-[var(--color-dim)]">{c.error}</span> + ) : c.held === null ? ( + <span className="text-[11px] text-[var(--color-dim)]">no report yet</span> + ) : ( + <span className="num" data-backlog-line={c.slug} title={`${n(c.undownloaded)} listed and not downloaded · ${n(c.untranscribed)} held and not transcribed`}> + {n(c.transcribed)}/{n(c.listed)} transcribed · {n(c.held)} held + </span> + )} + {c.done && <span className={badgeVariants({ variant: "on", size: "sm" })}>complete</span>} + {!c.done && !c.error && c.focused && <span className={badgeVariants({ variant: "state", size: "sm" })}>in focus</span>} + {!c.done && !c.error && !c.focused && ( + <button + type="button" + data-backlog-prioritize={c.slug} + disabled={busy || !!view.editorError} + title="put it in the editor's focus: its downloads and transcriptions lead every lane (the editor's channel-priority)" + onClick={async () => { + const j = await post({ op: "prioritize", slugs: [c.slug] }); + if (j) setSaid(`${c.slug} is in the editor's focus`); + }} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Prioritize + </button> + )} + </span> + ))} + <span className="ml-auto flex flex-wrap items-baseline gap-1.5"> + {w?.firedAt ? ( + <span data-backlog-watch="fired" className="text-[11px] text-kept-text">complete since {day(w.firedAt)} — re-sweep (the Inbox says so)</span> + ) : w ? ( + <span data-backlog-watch="armed" className="text-[11px] text-[var(--color-dim)]">re-sweep when complete · watching since {day(w.armedAt)}</span> + ) : null} + {w ? ( + <button type="button" data-backlog-unwatch="" disabled={busy} onClick={() => void post({ op: "unwatch" })} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {w.firedAt ? "Clear" : "Stop watching"} + </button> + ) : ( + !allDone && ( + <button + type="button" + data-backlog-watch-arm="" + disabled={busy} + title="an Inbox card (Re-sweep) once every cited channel has nothing left to download or transcribe" + onClick={async () => { + const j = await post({ op: "watch" }); + if (j) setSaid("watching: the Inbox says when the backlog is done"); + }} + className={buttonVariants({ variant: "outline", size: "sm" })} + > + Re-sweep when complete + </button> + ) + )} + </span> + </div> + {view.editorError && <p className="m-0 mt-1 text-[11px] text-[var(--color-dim)]">the editor did not answer: {view.editorError}</p>} + {view.watchError && <p className="m-0 mt-1 text-[11px] text-[var(--color-bad)]">{view.watchError}</p>} + {error && ( + <p role="alert" className="m-0 mt-1 text-[11px] text-[var(--color-bad)]"> + {error} + </p> + )} + {said && <p data-backlog-said="" className="m-0 mt-1 text-[11px] text-[var(--color-dim)]">{said}</p>} + </section> + ); +} diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -559,6 +559,21 @@ it replies on the note as the agent; with no route the button says why, and the Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's **Make variants**. +## The source backlog (Sources · Prioritize · Re-sweep when complete) + +The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each +channel the cut cites (a clip's `siteChannel`, else its channel, else the cut's provenance channel; a clip with its own +`src` cites none), `<channel> <transcribed>/<listed> transcribed · <held> held` from the EDITOR's snapshot counts +(`GET /api/ops/channel/<slug>`: `totals`, `buckets.downloadedNoTranscript`, `undownloaded`; listed = held + not yet +downloaded), never a walk of the disk. A channel is **complete** when nothing listed is left to download and nothing held is +left to transcribe. + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the line | the Overview tab, above the decisions; `in focus` / `complete` / "the editor does not archive it" | `pnpm ops get channel <slug>` | `GET /api/report/source-backlog?project` | +| Prioritize | a channel's **Prioritize**: the editor's focus (every lane leads with it) gains the channel, the ones in focus kept — through the editor's own `POST /api/ops/channel-priority {focus: {kind: "channels", slugs}}`, never settings; a site focus is the editor's to change (refused, said). Focus never starts a stopped lane or lifts a held one | `pnpm ops channel-priority --json '{"focus":{"kind":"channels","slugs":["<slug>"]}}'` | `POST {op: "prioritize", slugs?}` | +| Re-sweep when complete | **Re-sweep when complete**: a watch (`<project>/source-watch.json`, one writer) over the cited channels the editor archives; every read of the backlog — this page's, and the Inbox's background check, at most hourly — records what it saw, and the first read with every watched channel complete FIRES it, once: an Inbox **sources-complete** card (Review, **Re-sweep**) until **Clear** | — | `POST {op: "watch"}` · `{op: "unwatch"}` | + ## Export one clip A clean mp4 of ONE clip, to post or hand on: the clip's footage as the cut plays it, with none of the deck — no rail, diff --git a/umtool/e2e/fixtures/editor-stub-intake.mjs b/umtool/e2e/fixtures/editor-stub-intake.mjs @@ -0,0 +1,71 @@ +// The editor's doors the intake specs knock on (UI notes 2026-10-30, item 16), +// stubbed beside editor-stub.mjs: +// +// GET /api/ops/channel/<slug> a channel's snapshot counts (testchan: a backlog, +// 1,454/2,798 transcribed; backlog-done: nothing left; +// any other: 404 "Channel … not found") +// GET /api/ops/settings?key=channelPriority { value: { focus, channels } } +// POST /api/ops/channel-priority {focus} the focus replaced, recorded +// POST /__stub/channel-counts {slug, totals?, undownloaded?, untranscribed?} (no token) a spec's +// counts for a channel; {} resets + +const DEFAULT_COUNTS = () => ({ + testchan: { totals: { videos: 2751, transcribed: 1454, downloaded: 2700 }, undownloaded: 47, untranscribed: 1297 }, + "backlog-done": { totals: { videos: 120, transcribed: 120, downloaded: 120 }, undownloaded: 0, untranscribed: 0 }, +}); +let counts = DEFAULT_COUNTS(); +const priority = { focus: { kind: "none" }, channels: {} }; + +/** The control door (before the token check). Answers true when it handled the request. */ +export function intakeControl(req, res, url, { json, readBody }) { + if (req.method === "POST" && url.pathname === "/__stub/channel-counts") { + readBody(req, (body) => { + if (!body?.slug) { + counts = DEFAULT_COUNTS(); + priority.focus = { kind: "none" }; + } else counts[body.slug] = { totals: body.totals ?? counts[body.slug]?.totals ?? { videos: 0, transcribed: 0, downloaded: 0 }, undownloaded: body.undownloaded ?? 0, untranscribed: body.untranscribed ?? 0 }; + json(res, 200, { ok: true, counts }); + }); + return true; + } + return false; +} + +/** The token-gated doors. Answers true when it handled the request. */ +export function intakeRoute(req, res, url, { json, readBody, push }) { + const ch = /^\/api\/ops\/channel\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && ch) { + req.resume(); + const slug = decodeURIComponent(ch[1]); + const c = counts[slug]; + if (!c) { + json(res, 404, { ok: false, error: `Channel "${slug}" not found` }); + return true; + } + json(res, 200, { + ok: true, + slug, + config: { name: slug }, + priority: { tier: "normal", overrides: {}, rank: null }, + counts: null, + media: { status: "ok" }, + report: { generatedAt: "2026-11-01T00:00:00.000Z", totals: c.totals, buckets: { downloadedNoTranscript: c.untranscribed, noTranscript: c.untranscribed }, undownloaded: c.undownloaded }, + }); + return true; + } + if (req.method === "GET" && url.pathname === "/api/ops/settings" && url.searchParams.get("key") === "channelPriority") { + req.resume(); + json(res, 200, { ok: true, key: "channelPriority", value: priority }); + return true; + } + if (req.method === "POST" && url.pathname === "/api/ops/channel-priority") { + readBody(req, (body) => { + push({ route: "channel-priority", ...(body ?? {}) }); + if (!body?.focus || Object.keys(body).length !== 1) return json(res, 400, { ok: false, error: "the stub takes a focus body alone" }); + priority.focus = body.focus; + json(res, 200, { ok: true }); + }); + return true; + } + return false; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -15,6 +15,7 @@ // Modelled on e2e/fixtures/ollama-stub.mjs in the editor: a second webServer // entry, ready when its own endpoint answers. +import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; @@ -1221,6 +1222,8 @@ const server = http.createServer((req, res) => { return json(res, 200, { ok: true, ...scheduleClock }); }); } + // The intake specs' counts (editor-stub-intake.mjs). + if (intakeControl(req, res, url, { json, readBody })) return; if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") { return readBody(req, (body) => { const mode = body?.mode ?? "ok"; @@ -1238,6 +1241,8 @@ const server = http.createServer((req, res) => { return json(res, 401, { error: "missing bearer token" }); } + // UI notes item 16: a channel's counts and the focus (editor-stub-intake.mjs). + if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return; // Release 37 S4: Import this capture (editor-stub-import-page.mjs). if (importPageRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return; if ((url.pathname === "/api/ops/fetch-windows" || url.pathname.startsWith("/api/ops/job/")) && fetchWindowsRoute(req, res, url, fwCtx)) return; diff --git a/umtool/e2e/fixtures/intake-fixture.mjs b/umtool/e2e/fixtures/intake-fixture.mjs @@ -7,6 +7,10 @@ // the spec through `umtool candidates … import`; a // cached window of vid2 (0–9 s), so a candidate on it // plays here (candidates.spec.ts) +// source-backlog-fixture a deck cut citing two channels: testchan (the editor +// stub answers it with a backlog: 1,454/2,798 transcribed) +// and backlog-done (the stub's: nothing left), and a third +// the stub does not archive (source-backlog.spec.ts) // // Synthetic, like every fixture. import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; @@ -72,5 +76,15 @@ export function makeIntakeFixture({ reports, deckManifest, cachedWindow }) { mkdirSync(path.join(cands, "out", "clips-raw"), { recursive: true }); copyFileSync(cachedWindow, path.join(cands, "out", "clips-raw", "vid1_0.00-9.00.mp4")); copyFileSync(cachedWindow, path.join(cands, "out", "clips-raw", "vid2_0.00-9.00.mp4")); - return { cands }; + + // ---- the source backlog (item 16) ---------------------------------------------- + const backlog = path.join(reports, "source-backlog-fixture"); + const bm = deckManifest("source-backlog-fixture", "The Source Backlog Fixture", [ + ...clips(["c01", "c02", "c03"]), + { ...clips(["c04"])[0], channel: "backlog-done" }, + { ...clips(["c05"])[0], channel: "not-archived" }, + ]); + write(backlog, "video.manifest.json", json(bm)); + + return { cands, backlog }; } diff --git a/umtool/e2e/source-backlog.spec.ts b/umtool/e2e/source-backlog.spec.ts @@ -0,0 +1,108 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; + +// --------------------------------------------------------------------------- +// The source backlog on a report video's page (UI notes item 16, +// lib/report/sourceBacklog.*): +// +// source-backlog-fixture a deck cut citing testchan (the editor stub's +// backlog: 1,454/2,798 transcribed, 2,751 held), +// backlog-done (nothing left) and not-archived (the +// stub's 404). WRITES source-watch.json, removed after. +// +// The line per channel from the editor's snapshot counts; Prioritize through +// the editor's channel-priority (the focus body, never settings); Re-sweep +// when complete armed, then FIRED by a read once every channel is done, and +// the Inbox's sources-complete card (Re-sweep). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, ".e2e-song"); +const DIR = path.join(FIXTURE, "reports", "source-backlog-fixture"); +const PROJECT = "reports/source-backlog-fixture"; +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`; +const SHOTS = process.env.U4_SHOTS ?? null; + +const stubLog = () => { + try { + return JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route: string; focus?: { kind: string; slugs?: string[] } }[]; + } catch { + return []; + } +}; +const counts = (page: Page, body: Record<string, unknown>) => page.request.post(`${STUB}/__stub/channel-counts`, { data: body }); + +test.beforeEach(async ({ page }) => { + test.setTimeout(90_000); + rmSync(path.join(DIR, "source-watch.json"), { force: true }); + await counts(page, {}); +}); +test.afterAll(async ({ request }) => { + rmSync(path.join(DIR, "source-watch.json"), { force: true }); + await request.post(`${STUB}/__stub/channel-counts`, { data: {} }); +}); + +async function open(page: Page) { + await page.goto(urls.projectHref(PROJECT)); + await expect(page.getByTestId("source-backlog")).toBeVisible({ timeout: 20_000 }); +} + +test("each cited channel: transcribed/listed and held from the editor; complete; one the editor does not archive", async ({ page }) => { + await open(page); + const box = page.getByTestId("source-backlog"); + await expect(box.locator("[data-backlog-line='testchan']")).toHaveText("1,454/2,798 transcribed · 2,751 held"); + await expect(box.locator("[data-backlog-channel='testchan']")).toHaveAttribute("data-backlog-done", "0"); + await expect(box.locator("[data-backlog-channel='backlog-done']")).toContainText("complete"); + await expect(box.locator("[data-backlog-channel='not-archived']")).toContainText("the editor does not archive it"); + await expect(box.locator("[data-backlog-prioritize='testchan']")).toBeVisible(); + await expect(box.locator("[data-backlog-prioritize='backlog-done']")).toHaveCount(0); + if (SHOTS) { + await page.setViewportSize({ width: 1366, height: 900 }); + await page.screenshot({ path: path.join(SHOTS, "16-source-backlog.png") }); + } +}); + +test("Prioritize asks the editor's channel-priority for its focus; the line says in focus", async ({ page }) => { + await open(page); + const before = stubLog().length; + await page.locator("[data-backlog-prioritize='testchan']").click(); + await expect(page.locator("[data-backlog-said]")).toContainText("testchan is in the editor's focus"); + const asked = stubLog().slice(before).filter((r) => r.route === "channel-priority"); + expect(asked).toHaveLength(1); + expect(asked[0].focus).toEqual({ kind: "channels", slugs: ["testchan"] }); + await expect(page.locator("[data-backlog-channel='testchan']")).toContainText("in focus"); + await expect(page.locator("[data-backlog-prioritize='testchan']")).toHaveCount(0); +}); + +test("Re-sweep when complete: armed; fired once every channel is done; the Inbox's card says Re-sweep", async ({ page }) => { + await open(page); + await page.locator("[data-backlog-watch-arm]").click(); + await expect(page.locator("[data-backlog-watch='armed']")).toContainText("re-sweep when complete"); + const armed = JSON.parse(readFileSync(path.join(DIR, "source-watch.json"), "utf8")); + // A channel the editor does not archive can never be complete: the watch is for the ones it answers. + expect(armed.watch.slugs.sort()).toEqual(["backlog-done", "testchan"]); + // A reload before the backlog is done fires nothing. + await page.reload(); + await expect(page.locator("[data-backlog-watch='armed']")).toBeVisible({ timeout: 20_000 }); + await counts(page, { slug: "testchan", totals: { videos: 2798, transcribed: 2798, downloaded: 2798 }, undownloaded: 0, untranscribed: 0 }); + await page.reload(); + await expect(page.locator("[data-backlog-watch='fired']")).toContainText("complete since", { timeout: 20_000 }); + const fired = JSON.parse(readFileSync(path.join(DIR, "source-watch.json"), "utf8")); + expect(fired.watch.firedAt).toBeTruthy(); + await page.goto(urls.homeHref()); + const card = page.locator(`[data-lit-line][data-piece='p:${PROJECT}'][data-card='sources-complete']`); + await expect(card).toBeVisible({ timeout: 20_000 }); + await expect(card).toContainText("Re-sweep"); + if (SHOTS) await card.screenshot({ path: path.join(SHOTS, "16-inbox-resweep.png") }); + // Cleared, the card goes. + await open(page); + await page.locator("[data-backlog-unwatch]").click(); + await expect(page.locator("[data-backlog-watch]")).toHaveCount(0); + await page.goto(urls.homeHref()); + await expect(card).toHaveCount(0); +}); diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -26,6 +26,7 @@ import { scheduleDecisions } from "./inbox/schedules.mjs"; import { readSchedules } from "./schedules"; import type { ScheduleView } from "./schedule-types"; import { refreshDecisions } from "./inbox/refresh"; +import { sourceWatchDecisions } from "./inbox/sourceWatch"; // --------------------------------------------------------------------------- // THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the @@ -389,7 +390,9 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro const refresh = await readMutes() .then((mutes) => refreshDecisions(graph, life, mutes)) .catch(() => [] as Decision[]); - return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring]; + // Re-sweep when complete (UI notes item 16): a report video's source watch that fired. + const sources = await sourceWatchDecisions().catch(() => [] as Decision[]); + return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring, ...sources]; } /** diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -64,6 +64,9 @@ const KIND_CATEGORY = { // recordings since the current report are something to review. "refresh-held": "spend", "refresh-available": "review", + // UI notes item 16: a report video's cited channels are all downloaded and + // transcribed -- a re-sweep to review (lib/inbox/sourceWatch.ts). + "sources-complete": "review", // Release 29 M8: a model's proposed verdicts for a fact-check's unruled // claims, each waiting on the operator's approve or reject. "verdict-proposed": "review", @@ -96,7 +99,7 @@ export function groupOf(d) { // Within a group: the brief's order first (proposals before failed runs), then // everything else as equals. -const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2 }; +const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2, "sources-complete": 2 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -153,6 +156,7 @@ const ACTION_LABEL = { "ambiguous-project": "Fix the project's files", "refresh-held": "Refresh", "refresh-available": "Refresh", + "sources-complete": "Re-sweep", }; const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" }; diff --git a/umtool/lib/inbox/sourceWatch.ts b/umtool/lib/inbox/sourceWatch.ts @@ -0,0 +1,81 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import type { Decision } from "@/lib/decisions"; +import { projectHref } from "@/lib/hrefs"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { projectRefs } from "@/lib/projects"; +import { SOURCE_WATCH_FILE, backlogWords, readSourceWatch } from "@/lib/report/sourceBacklog.mjs"; +import { readBacklog } from "@/lib/report/sourceBacklog"; + +// --------------------------------------------------------------------------- +// "RE-SWEEP WHEN COMPLETE" (UI notes item 16), the Inbox's half -- one kind: +// +// sources-complete a report video's source watch (<project>/source-watch.json, +// lib/report/sourceBacklog.mjs) has fired: every channel the +// cut cites has nothing left to download or transcribe. Review, +// action Re-sweep (the project's page, the backlog line); +// gone when the operator clears or re-arms the watch. +// +// The check is the refresh check's pattern (lib/inbox/refresh.ts): the Inbox +// only READS the watch files; an armed watch whose last read is over an hour +// old is read again in the background (the editor's snapshot counts, one +// project at a time, never twice at once), in the app's server only and not +// where UMTOOL_SOURCE_WATCH=0. The project page's own read records too, so +// opening the project fires it as well. SERVER-ONLY. +// --------------------------------------------------------------------------- + +export const SOURCES_COMPLETE = "sources-complete"; +export const SOURCE_WATCH_EVERY_MS = 60 * 60 * 1000; + +type Watched = { id: string; dir: string; title: string; watch: { slugs: string[]; armedAt: string; firedAt?: string; fired?: Record<string, unknown>[] }; checkedAt: string | null }; + +async function watched(): Promise<Watched[]> { + const refs = (await projectRefs()).filter((p) => kindMakesTakes(p.kind)); + const out: Watched[] = []; + for (const p of refs) { + const has = await stat(path.join(/* turbopackIgnore: true */ p.dir, SOURCE_WATCH_FILE)).then(() => true, () => false); + if (!has) continue; + const { doc } = await readSourceWatch(p.dir); + if (!doc.watch) continue; + out.push({ id: p.id, dir: p.dir, title: p.name, watch: doc.watch, checkedAt: doc.last?.checkedAt ?? null }); + } + return out; +} + +const g = globalThis as typeof globalThis & { __umtoolSourceWatch?: Promise<unknown> | null }; + +/** Read the stale armed watches' backlogs in the background (a page never waits on it). */ +export function kickSourceWatches(list: Watched[], now = Date.now()): void { + if (g.__umtoolSourceWatch) return; + const stale = list.filter((w) => !w.watch.firedAt && (!w.checkedAt || now - Date.parse(w.checkedAt) >= SOURCE_WATCH_EVERY_MS)); + if (!stale.length) return; + g.__umtoolSourceWatch = (async () => { + for (const w of stale) await readBacklog(w.dir).catch(() => null); + })() + .catch(() => null) + .finally(() => { + g.__umtoolSourceWatch = null; + }); +} + +/** The Inbox's `sources-complete` cards (and the stale watches read in the background). */ +export async function sourceWatchDecisions(o: { background?: boolean } = {}): Promise<Decision[]> { + const list = await watched(); + if (o.background !== false && process.env.NEXT_RUNTIME && process.env.UMTOOL_SOURCE_WATCH !== "0") kickSourceWatches(list); + return list + .filter((w) => w.watch.firedAt) + .map( + (w) => + ({ + project: w.id, + projectTitle: w.title, + piece: `p:${w.id}`, + kind: SOURCES_COMPLETE, + target: w.watch.slugs.join(", "), + why: `the backlog is done — ${(w.watch.fired ?? []).map((r) => backlogWords(r)).join("; ") || w.watch.slugs.join(", ")}: re-sweep the cut's sources`, + href: projectHref(w.id, { tab: "overview" }), + severity: "open", + at: Date.parse(w.watch.firedAt!) || 0, + }) as Decision, + ); +} diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -21,6 +21,7 @@ export const WHAT = { "worth-researching": "worth researching", "refresh-available": "new recordings match", "refresh-held": "refresh held by the cap", + "sources-complete": "sources complete: re-sweep", "claim-unadjudicated": "claims never ruled", "claim-incoherent": "claims that don't hold together", "clip-no-cues": "clips with no cues", diff --git a/umtool/lib/report/sourceBacklog.mjs b/umtool/lib/report/sourceBacklog.mjs @@ -0,0 +1,239 @@ +// THE SOURCE BACKLOG on a report video's page (UI notes 2026-10-30, item 16): +// for each channel the cut cites, how much of it the archive holds and has +// transcribed -- "Sources: emberparadox 1,454/2,798 transcribed · Prioritize" +// -- read from the EDITOR (`GET /api/ops/channel/<slug>`: its snapshot's +// totals and bucket sizes, never a walk of the disk), and a watch that tells +// the operator when that backlog is done ("Re-sweep when complete"). +// +// PRIORITIZE never writes settings: it asks the editor's own +// `POST /api/ops/channel-priority {focus: {kind: "channels", slugs}}` -- the +// focus every lane leads with -- with the channels already in focus kept +// (the focus is ONE list; a site focus is not replaced from here). +// +// THE WATCH, umtool's own state beside the project, in lib/lifecycle.mjs's +// discipline (one writer serialised in-process, whole file temp + rename, an +// unreadable file never overwritten): +// +// <project>/source-watch.json +// { format: "umtool-source-watch", version: 1, +// watch: { slugs, armedAt, firedAt?, fired?: [rows] } | null, +// last?: { checkedAt, rows: [{ slug, listed, held, transcribed, undownloaded, untranscribed, done }] } } +// +// While a watch is armed, every read of the backlog (the page's, and the +// Inbox's background check, lib/inbox/sourceWatch.ts) records what it saw +// (no file is made for a project with no watch); the first read in which +// every watched channel is done FIRES the watch, once: the Inbox raises a +// `sources-complete` card (Re-sweep) until the operator clears or re-arms it. +// +// Plain ESM. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { channelFor, clipsOf } from "../projects/report.mjs"; + +export const SOURCE_WATCH_FILE = "source-watch.json"; +export const SOURCE_WATCH_FORMAT = "umtool-source-watch"; +const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +export class SourceWatchError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "SourceWatchError"; + this.status = status; + } +} + +/** + * The channels the cut cites, as the editor knows them (a clip's + * `siteChannel` -- the archive's slug, the Rumble case -- else its channel, + * else the cut's provenance channel), with how many clips cite each. Clips + * that carry their own media (`src`) cite no channel. + * + * @param {Record<string, any>} manifest + * @returns {Array<{ slug: string, clips: number }>} + */ +export function citedChannels(manifest) { + const n = new Map(); + for (const e of clipsOf(manifest)) { + if (e.src != null) continue; + const slug = typeof e.siteChannel === "string" && e.siteChannel ? e.siteChannel : channelFor(manifest, e); + if (typeof slug !== "string" || !SLUG_RE.test(slug)) continue; + n.set(slug, (n.get(slug) ?? 0) + 1); + } + return [...n.entries()].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)); +} + +const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null); + +/** + * One channel's backlog from the editor's `GET /api/ops/channel/<slug>` + * answer: `listed` (on disk + not yet), `held` (a video directory), + * `downloaded` (its media), `transcribed`, the two backlogs, and `done` -- + * nothing listed left to download and nothing held left to transcribe. A + * channel the editor has no report for answers nulls and is never `done`. + * + * @param {string} slug + * @param {any} r the route's JSON + */ +export function backlogOf(slug, r) { + const rep = isObj(r?.report) ? r.report : null; + const totals = isObj(rep?.totals) ? rep.totals : {}; + const held = num(totals.videos); + const transcribed = num(totals.transcribed); + const downloaded = num(totals.downloaded); + const undownloaded = num(rep?.undownloaded); + const untranscribed = num(rep?.buckets?.downloadedNoTranscript); + const listed = held !== null && undownloaded !== null ? held + undownloaded : num(r?.counts?.playlistCount); + const done = held !== null && undownloaded === 0 && untranscribed === 0; + return { + slug, + name: typeof r?.config?.name === "string" ? r.config.name : null, + listed, + held, + downloaded, + transcribed, + undownloaded, + untranscribed, + done, + tier: typeof r?.priority?.tier === "string" ? r.priority.tier : null, + generatedAt: typeof rep?.generatedAt === "string" ? rep.generatedAt : null, + mediaStatus: typeof r?.media?.status === "string" ? r.media.status : null, + }; +} + +/** + * The focus body that adds `slugs` to what is in focus now (`focus` as + * `settings.channelPriority.focus` reads), or a refusal in words: a site's + * focus is the editor's to change. + * + * @param {any} focus + * @param {string[]} slugs + */ +export function focusBodyFor(focus, slugs) { + const want = [...new Set(slugs.filter((s) => typeof s === "string" && SLUG_RE.test(s)))]; + if (!want.length) throw new SourceWatchError("name the channels to prioritize"); + if (isObj(focus) && focus.kind === "site") { + throw new SourceWatchError(`the editor's focus is the site "${focus.siteId}" — change it on the editor's Channels page; Prioritize adds channels to a channel focus`, 409); + } + const had = isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : []; + const slugsOut = [...new Set([...had, ...want])]; + return { body: { focus: { kind: "channels", slugs: slugsOut } }, added: want.filter((s) => !had.includes(s)), already: want.filter((s) => had.includes(s)) }; +} + +/** Which slugs are in focus now. */ +export const focusedOf = (focus) => (isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : []); + +// ---- the watch ---------------------------------------------------------------- + +export const sourceWatchFile = (dir) => path.join(/* turbopackIgnore: true */ dir, SOURCE_WATCH_FILE); + +const rowOf = (r) => + isObj(r) && typeof r.slug === "string" + ? { slug: r.slug, listed: num(r.listed), held: num(r.held), transcribed: num(r.transcribed), undownloaded: num(r.undownloaded), untranscribed: num(r.untranscribed), done: r.done === true } + : null; + +/** `{ doc: { watch, last }, error? }` -- missing is empty; unreadable is empty with `error`. */ +export async function readSourceWatch(dir) { + const empty = { watch: null, last: null }; + let raw; + try { + raw = await readFile(/* turbopackIgnore: true */ sourceWatchFile(dir), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { doc: empty }; + return { doc: empty, error: `${SOURCE_WATCH_FILE} cannot be read: ${err?.message ?? err}` }; + } + let j; + try { + j = JSON.parse(raw); + } catch (err) { + return { doc: empty, error: `${SOURCE_WATCH_FILE} is not JSON: ${err.message}` }; + } + if (!isObj(j) || j.format !== SOURCE_WATCH_FORMAT) return { doc: empty, error: `${SOURCE_WATCH_FILE} is not a ${SOURCE_WATCH_FORMAT} file` }; + const w = isObj(j.watch) && Array.isArray(j.watch.slugs) ? j.watch : null; + const watch = w + ? { + slugs: w.slugs.filter((s) => typeof s === "string"), + armedAt: typeof w.armedAt === "string" ? w.armedAt : "", + ...(typeof w.firedAt === "string" ? { firedAt: w.firedAt, fired: Array.isArray(w.fired) ? w.fired.map(rowOf).filter(Boolean) : [] } : {}), + } + : null; + const last = isObj(j.last) && typeof j.last.checkedAt === "string" && Array.isArray(j.last.rows) ? { checkedAt: j.last.checkedAt, rows: j.last.rows.map(rowOf).filter(Boolean) } : null; + return { doc: { watch, last } }; +} + +let chain = Promise.resolve(); + +function writeSourceWatch(dir, mutate) { + const run = chain.then(async () => { + const file = sourceWatchFile(dir); + const read = await readSourceWatch(dir); + if (read.error) throw new SourceWatchError(`${read.error}; fix or remove ${file} first`, 409); + const doc = read.doc; + const result = mutate(doc); + const out = { format: SOURCE_WATCH_FORMAT, version: 1, watch: doc.watch, ...(doc.last ? { last: doc.last } : {}) }; + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } + return { ...result, doc: out }; + }); + chain = run.catch(() => {}); + return run; +} + +/** ARM: tell me when these channels' backlog is done (a new watch replaces the old, fired or not). */ +export function armSourceWatch(dir, slugs, { now = null } = {}) { + const want = [...new Set((slugs ?? []).filter((s) => typeof s === "string" && SLUG_RE.test(s)))]; + if (!want.length) return Promise.reject(new SourceWatchError("the cut cites no channel to watch")); + return writeSourceWatch(dir, (doc) => { + doc.watch = { slugs: want, armedAt: now ?? new Date().toISOString() }; + return { armed: want }; + }); +} + +/** CLEAR: no watch (the card goes); what was last seen stays. */ +export function clearSourceWatch(dir) { + return writeSourceWatch(dir, (doc) => { + const had = doc.watch; + doc.watch = null; + return { cleared: !!had }; + }); +} + +/** + * RECORD what a read of the backlog saw. A watch not yet fired FIRES when + * every one of its channels was read and is done -- once; answers `{ fired }`. + * + * @param {string} dir + * @param {ReturnType<typeof backlogOf>[]} rows + */ +export function recordSourceCheck(dir, rows, { now = null } = {}) { + const stamp = now ?? new Date().toISOString(); + return writeSourceWatch(dir, (doc) => { + const kept = rows.map(rowOf).filter(Boolean); + doc.last = { checkedAt: stamp, rows: kept }; + const w = doc.watch; + if (!w || w.firedAt) return { fired: false }; + const by = new Map(kept.map((r) => [r.slug, r])); + const all = w.slugs.length > 0 && w.slugs.every((s) => by.get(s)?.done === true); + if (!all) return { fired: false }; + w.firedAt = stamp; + w.fired = w.slugs.map((s) => by.get(s)); + return { fired: true }; + }); +} + +/** "1,454" */ +export const thousands = (n) => (typeof n === "number" ? n.toLocaleString("en-US") : "?"); + +/** The line for one channel: `emberparadox 1,454/2,798 transcribed · 2,751 held`. */ +export function backlogWords(r) { + if (r.error) return `${r.slug}: ${r.error}`; + if (r.held === null) return `${r.slug}: no report yet`; + return `${r.slug} ${thousands(r.transcribed)}/${thousands(r.listed ?? r.held)} transcribed · ${thousands(r.held)} held${r.done ? " · complete" : ""}`; +} diff --git a/umtool/lib/report/sourceBacklog.test.mjs b/umtool/lib/report/sourceBacklog.test.mjs @@ -0,0 +1,78 @@ +// The source backlog (UI notes item 16): the channels a cut cites (the +// archive's slug first), one channel's counts from the editor's snapshot +// answer, Prioritize's focus body (the channels in focus kept; a site focus +// refused), and the watch -- armed, recorded, FIRED once when every watched +// channel is done, an unreadable file never overwritten. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { SOURCE_WATCH_FILE, armSourceWatch, backlogOf, backlogWords, citedChannels, clearSourceWatch, focusBodyFor, readSourceWatch, recordSourceCheck } from "./sourceBacklog.mjs"; + +const answer = ({ videos = 2751, transcribed = 1454, downloaded = 2700, undownloaded = 47, untranscribed = 1297 } = {}) => ({ + ok: true, + config: { name: "Some Streamer" }, + priority: { tier: "normal" }, + report: { generatedAt: "2026-11-01T00:00:00Z", totals: { videos, transcribed, downloaded }, buckets: { downloadedNoTranscript: untranscribed }, undownloaded }, +}); + +test("the cited channels: siteChannel first, else the clip's channel, else the provenance's; own-media clips cite none", () => { + const m = { + provenance: { channelSlug: "main" }, + timeline: [ + { type: "clip", id: "a", video: "v1" }, + { type: "clip", id: "b", video: "v2", channel: "other" }, + { type: "clip", id: "c", video: "v3", channel: "rumble-local", siteChannel: "rumble-site" }, + { type: "clip", id: "d", video: "v4" }, + { type: "clip", id: "e", src: "media/x.mp4" }, + { type: "card", id: "k" }, + ], + }; + assert.deepEqual(citedChannels(m), [{ slug: "main", clips: 2 }, { slug: "other", clips: 1 }, { slug: "rumble-site", clips: 1 }]); +}); + +test("one channel's backlog: listed is held + not downloaded; done when nothing is left to download or transcribe", () => { + const r = backlogOf("chan", answer()); + assert.equal(r.listed, 2798); + assert.equal(r.held, 2751); + assert.equal(r.transcribed, 1454); + assert.equal(r.done, false); + assert.equal(backlogWords(r), "chan 1,454/2,798 transcribed · 2,751 held"); + const d = backlogOf("chan", answer({ undownloaded: 0, untranscribed: 0, transcribed: 2751 })); + assert.equal(d.done, true); + assert.match(backlogWords(d), /complete$/); + assert.equal(backlogOf("chan", null).done, false, "no answer is never done"); +}); + +test("Prioritize: the focus gains the channels, the ones in it kept; a site focus is the editor's", () => { + assert.deepEqual(focusBodyFor({ kind: "none" }, ["a"]), { body: { focus: { kind: "channels", slugs: ["a"] } }, added: ["a"], already: [] }); + assert.deepEqual(focusBodyFor({ kind: "channels", slugs: ["x", "a"] }, ["a", "b"]).body.focus.slugs, ["x", "a", "b"]); + assert.deepEqual(focusBodyFor({ kind: "channels", slugs: ["a"] }, ["a"]).added, []); + assert.throws(() => focusBodyFor({ kind: "site", siteId: "s1" }, ["a"]), /site "s1"/); + assert.throws(() => focusBodyFor(null, []), /name the channels/); +}); + +test("the watch: armed, recorded, fired ONCE when every watched channel is done; cleared; an unreadable file refused", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-watch-")); + await armSourceWatch(dir, ["a", "b"], { now: "2026-11-01T00:00:00.000Z" }); + const notDone = [backlogOf("a", answer({ undownloaded: 0, untranscribed: 0 })), backlogOf("b", answer())]; + assert.deepEqual((await recordSourceCheck(dir, notDone)).fired, false); + // One channel read and done is not enough: both must be. + assert.deepEqual((await recordSourceCheck(dir, [notDone[0]])).fired, false); + const done = [notDone[0], backlogOf("b", answer({ undownloaded: 0, untranscribed: 0 }))]; + assert.equal((await recordSourceCheck(dir, done, { now: "2026-11-02T00:00:00.000Z" })).fired, true); + assert.equal((await recordSourceCheck(dir, done)).fired, false, "once"); + const { doc } = await readSourceWatch(dir); + assert.equal(doc.watch.firedAt, "2026-11-02T00:00:00.000Z"); + assert.deepEqual(doc.watch.fired.map((r) => r.slug), ["a", "b"]); + await clearSourceWatch(dir); + assert.equal((await readSourceWatch(dir)).doc.watch, null); + assert.ok((await readSourceWatch(dir)).doc.last, "what was last seen stays"); + await assert.rejects(armSourceWatch(dir, []), /no channel/); + await writeFile(path.join(dir, SOURCE_WATCH_FILE), "nope"); + await assert.rejects(armSourceWatch(dir, ["a"]), (e) => e.status === 409); + assert.equal(await readFile(path.join(dir, SOURCE_WATCH_FILE), "utf8"), "nope"); +}); diff --git a/umtool/lib/report/sourceBacklog.ts b/umtool/lib/report/sourceBacklog.ts @@ -0,0 +1,62 @@ +import { askEditor, EditorError } from "@/lib/articles/generation"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { backlogOf, citedChannels, focusBodyFor, focusedOf, readSourceWatch, recordSourceCheck } from "./sourceBacklog.mjs"; + +// The source backlog's editor half (UI notes item 16): lib/report/sourceBacklog.mjs +// holds the rules and the watch; this asks the editor, with umtool's WORKER_TOKEN, +// for each cited channel's snapshot counts and the focus, and asks it to +// prioritize. SERVER-ONLY. + +export type BacklogRow = ReturnType<typeof backlogOf> & { clips: number; focused: boolean; error?: string }; +export type BacklogView = { + channels: BacklogRow[]; + focus: unknown; + editorError: string | null; + watch: { slugs: string[]; armedAt: string; firedAt?: string } | null; + watchError: string | null; + fired: boolean; +}; + +/** Read every cited channel's backlog, record it (the watch may fire), answer the view. */ +export async function readBacklog(dir: string, manifest: Record<string, unknown> | null = null): Promise<BacklogView> { + const m = (manifest ?? (await readManifest(dir)) ?? {}) as Record<string, unknown>; + const cited = citedChannels(m) as { slug: string; clips: number }[]; + let editorError: string | null = null; + const focus = await askEditor<{ value?: { focus?: unknown } }>("/api/ops/settings?key=channelPriority") + .then((r) => r.value?.focus ?? null) + .catch((e: unknown) => { + editorError = e instanceof Error ? e.message : String(e); + return null; + }); + const inFocus = new Set(focusedOf(focus) as string[]); + const channels: BacklogRow[] = await Promise.all( + cited.map(async ({ slug, clips }) => { + try { + const r = await askEditor(`/api/ops/channel/${encodeURIComponent(slug)}`); + return { ...(backlogOf(slug, r) as ReturnType<typeof backlogOf>), clips, focused: inFocus.has(slug) }; + } catch (e) { + if (!(e instanceof EditorError) || e.status !== 404) editorError ??= e instanceof Error ? e.message : String(e); + return { ...(backlogOf(slug, null) as ReturnType<typeof backlogOf>), clips, focused: inFocus.has(slug), error: e instanceof EditorError && e.status === 404 ? "the editor does not archive it" : "not read" }; + } + }), + ); + let fired = false; + // Recorded only for an armed watch (no file is made in a project nobody asked to watch), and only + // a real answer: an editor that did not answer says nothing about the backlog. + const before = await readSourceWatch(dir); + if (before.doc.watch && !before.doc.watch.firedAt && !editorError && channels.some((c) => c.held !== null)) { + fired = await recordSourceCheck(dir, channels.filter((c) => !c.error)) + .then((r: { fired: boolean }) => r.fired) + .catch(() => false); + } + const { doc, error } = fired ? await readSourceWatch(dir) : before; + return { channels, focus, editorError, watch: doc.watch, watchError: error ?? null, fired }; +} + +/** PRIORITIZE: the editor's focus gains `slugs` (the ones in focus kept). */ +export async function prioritize(slugs: string[]): Promise<{ added: string[]; already: string[]; focus: unknown }> { + const cur = await askEditor<{ value?: { focus?: unknown } }>("/api/ops/settings?key=channelPriority", { fresh: true }); + const { body, added, already } = focusBodyFor(cur.value?.focus ?? null, slugs) as { body: { focus: unknown }; added: string[]; already: string[] }; + if (added.length) await askEditor("/api/ops/channel-priority", { method: "POST", body }); + return { added, already, focus: body.focus }; +}