commit c40d9606b0212c9a38e45d992b0c243a91ed7521
parent 9e5668ef7671ee293ff00f8415ce5e573de663e5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 02:30:55 -0400
umtool: research over the corpus as data -- scope, search (enumerate once), window, coverage, reading log, fetch, media
lib/research calls the MCP's own engine (yt-dlp-transcript-mcp/research), never
a tool's text; parity.test.ts holds a search to enumerate_matches' total and ids
through createCorpusTools on the new research fixture corpus.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
28 files changed, 2334 insertions(+), 1 deletion(-)
diff --git a/mcp/src/research.ts b/mcp/src/research.ts
@@ -25,6 +25,7 @@ export type { SourceSpec } from "./sources";
export {
findVideo,
findPost,
+ resolveSelectedChannels,
MCP_POLICY,
type SearchHit,
type SearchResult,
diff --git a/package.json b/package.json
@@ -24,7 +24,7 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs",
+ "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs",
"test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]",
"typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit",
"lint": "pnpm --filter export run lint",
diff --git a/umtool/app/api/research/_respond.ts b/umtool/app/api/research/_respond.ts
@@ -0,0 +1,13 @@
+import { SourceError } from "@/lib/research/sources";
+
+// Every research route answers JSON, never cached, and an error in words:
+// a SourceError carries its own status (400 a bad request, 404 nothing there,
+// 502 a source that cannot be read); anything else is a 500.
+export function ok(body: unknown): Response {
+ return Response.json(body, { headers: { "cache-control": "no-store" } });
+}
+
+export function fail(e: unknown): Response {
+ const status = e instanceof SourceError ? e.status : ((e as { status?: number })?.status ?? 500);
+ return Response.json({ error: (e as Error)?.message ?? String(e) }, { status, headers: { "cache-control": "no-store" } });
+}
diff --git a/umtool/app/api/research/coverage/route.ts b/umtool/app/api/research/coverage/route.ts
@@ -0,0 +1,20 @@
+import { scopeFrom } from "@/lib/research/corpus";
+import { coverageOf } from "@/lib/research/coverage";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET ?source=&channels=a,b -> CoverageResponse (lib/research/types.ts)
+//
+// Channels × years: what the source publishes (its summaries, by upload year
+// and state), what the editor holds on disk (channel_coverage, through its
+// GET /api/ops/coverage; for the local corpus, on disk when the editor cannot
+// be asked -- and the answer says why), gaps over 60 days, and transcripts vs
+// captions where a search has counted a channel whole.
+export async function GET(request: Request) {
+ try {
+ return ok(await coverageOf(scopeFrom(new URL(request.url).searchParams)));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/fetch/route.ts b/umtool/app/api/research/fetch/route.ts
@@ -0,0 +1,34 @@
+import { fetchForReader } from "@/lib/research/fetch";
+import { SourceError } from "@/lib/research/sources";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// POST { source, channel, video, start, end, reason } | { job }
+// -> { state: "ready", file, from, to, cached } | { state: "queued", job, status }
+// | { state: "failed", message, job? }
+//
+// The clip behind a cite, through the editor's fetch-window route exactly as
+// the MCP's fetch_clip asks for it (lib/research/fetch.ts) -- never yt-dlp.
+// Never waits: a queued fetch is polled with { job }.
+export async function POST(request: Request) {
+ try {
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b) throw new SourceError("expected a JSON body");
+ if (typeof b.job === "string" && b.job.trim()) return ok(await fetchForReader({ job: b.job.trim() }));
+ const start = Number(b.start);
+ const end = Number(b.end);
+ return ok(
+ await fetchForReader({
+ source: String(b.source ?? ""),
+ channel: String(b.channel ?? ""),
+ video: String(b.video ?? ""),
+ start,
+ end,
+ reason: String(b.reason ?? "").slice(0, 400),
+ }),
+ );
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/log/route.ts b/umtool/app/api/research/log/route.ts
@@ -0,0 +1,35 @@
+import { REPORTS_ROOT } from "@/lib/paths";
+import { LogError, markHit, readLog } from "@/lib/research/log.mjs";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// The reading log (lib/research/log.mjs), umtool-side under
+// REPORTS_ROOT/.umtool/research/sessions/ -- never in the corpus.
+//
+// GET ?session=<16 hex> -> { marks, error? }
+// POST { session, key: "<channel>/<id>", state: read|skipped|unread,
+// query?, scope? } -> { key, state, at, marks }
+export async function GET(request: Request) {
+ const session = new URL(request.url).searchParams.get("session") ?? "";
+ const log = await readLog(REPORTS_ROOT, session);
+ if (log.error === "not a session id") return fail(new LogError(log.error));
+ return ok(log);
+}
+
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body) throw new LogError("expected a JSON body");
+ const scope = body.scope && typeof body.scope === "object" && !Array.isArray(body.scope) ? (body.scope as Record<string, unknown>) : undefined;
+ return ok(
+ await markHit(REPORTS_ROOT, String(body.session ?? ""), String(body.key ?? ""), String(body.state ?? "") as "read", {
+ ...(typeof body.query === "string" ? { query: body.query } : {}),
+ // The scope is a description for a person reading the file: kept small.
+ ...(scope && JSON.stringify(scope).length <= 4000 ? { scope } : {}),
+ }),
+ );
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/media/route.ts b/umtool/app/api/research/media/route.ts
@@ -0,0 +1,52 @@
+import { createReadStream } from "node:fs";
+import { stat } from "node:fs/promises";
+import { Readable } from "node:stream";
+import { findVideo } from "yt-dlp-transcript-mcp/research";
+import { contentTypeOf, resolveLocalMedia } from "@/lib/research/media";
+import { openSource } from "@/lib/research/sources";
+import { fail } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET ?source=&channel=&video=&file=<name the window answer offered>
+//
+// One file the reader may play from this machine (lib/research/media.ts): a
+// fetched clip window, a kept source or its audio, in the editor's corpus. The
+// name must be one the server's own scan offers -- never a path -- and it is
+// served whole with byte ranges, so the player can seek. Read only.
+export async function GET(request: Request) {
+ try {
+ const q = new URL(request.url).searchParams;
+ const opened = await openSource(q.get("source"));
+ const found = await findVideo(opened.source, q.get("video") ?? "", q.get("channel") ?? "");
+ if (!found) return new Response("no such recording", { status: 404 });
+ const r = await resolveLocalMedia(found.ch.slug, found.record, q.get("file") ?? "");
+ if (!r) return new Response("not a file offered for this recording", { status: 404 });
+ const st = await stat(/* turbopackIgnore: true */ r.abs).catch(() => null);
+ if (!st?.isFile()) return new Response("gone", { status: 404 });
+
+ const headers: Record<string, string> = {
+ "content-type": contentTypeOf(r.abs),
+ "accept-ranges": "bytes",
+ "cache-control": "private, max-age=600",
+ };
+ const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get("range") ?? "");
+ if (range && (range[1] || range[2])) {
+ const size = st.size;
+ let start = range[1] ? Number(range[1]) : size - Number(range[2]);
+ let end = range[1] && range[2] ? Number(range[2]) : size - 1;
+ start = Math.max(0, start);
+ end = Math.min(size - 1, end);
+ if (start > end) return new Response("range not satisfiable", { status: 416, headers: { "content-range": `bytes */${size}` } });
+ const stream = createReadStream(/* turbopackIgnore: true */ r.abs, { start, end });
+ return new Response(Readable.toWeb(stream) as ReadableStream, {
+ status: 206,
+ headers: { ...headers, "content-range": `bytes ${start}-${end}/${size}`, "content-length": String(end - start + 1) },
+ });
+ }
+ const stream = createReadStream(/* turbopackIgnore: true */ r.abs);
+ return new Response(Readable.toWeb(stream) as ReadableStream, { headers: { ...headers, "content-length": String(st.size) } });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/scope/route.ts b/umtool/app/api/research/scope/route.ts
@@ -0,0 +1,19 @@
+import { scopeFrom, scopeOf } from "@/lib/research/corpus";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET ?source=&channels=a,b&from=YYYY-MM-DD&to=&states=&media=&posts=1
+// -> ScopeSummary (lib/research/types.ts)
+//
+// What the scope holds, BEFORE a search runs: its channels, its videos, the
+// upload-date span (the summaries index), the transcript vs captions share as
+// far as a search has counted it, and how many curated aliases the source
+// ships. Nothing is scanned.
+export async function GET(request: Request) {
+ try {
+ return ok(await scopeOf(scopeFrom(new URL(request.url).searchParams)));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/search/route.ts b/umtool/app/api/research/search/route.ts
@@ -0,0 +1,35 @@
+import { runSearch, scopeFrom } from "@/lib/research/corpus";
+import { parseAsk } from "@/lib/research/query.mjs";
+import { SourceError } from "@/lib/research/sources";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// POST { q, source, channels?, from?, to?, states?, media?, posts?, exclude?, fresh? }
+// -> SearchResponse (lib/research/types.ts)
+//
+// ONE scan for the whole match set -- enumerate_matches' own, with snippets --
+// and never a page of it (the coverage rule). `q` is the ask bar's text
+// (lib/research/query.mjs: a phrase, /regex/, or a near:N b). The answer
+// says whether the set is complete, or which channels a cap left unread; it
+// carries the facets and the session's reading log.
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") throw new SourceError("expected a JSON body");
+ const ask = parseAsk(typeof body.q === "string" ? body.q : "");
+ if (ask.error) throw new SourceError(ask.error);
+ const exclude = Array.isArray(body.exclude) ? body.exclude.filter((x): x is string => typeof x === "string" && x.trim() !== "") : undefined;
+ return ok(
+ await runSearch({
+ ...scopeFrom(body),
+ query: ask.query,
+ regex: ask.regex,
+ ...(exclude?.length ? { exclude } : {}),
+ fresh: body.fresh === true,
+ }),
+ );
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/sources/route.ts b/umtool/app/api/research/sources/route.ts
@@ -0,0 +1,14 @@
+import { listSources } from "@/lib/research/sources";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET -> { sources: [{ handle, kind, label, detail }] }: the corpora the ask
+// bar may read, the local one first (lib/research/sources.ts).
+export async function GET() {
+ try {
+ return ok({ sources: await listSources() });
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/window/route.ts b/umtool/app/api/research/window/route.ts
@@ -0,0 +1,37 @@
+import { MAX_SPAN, windowOf } from "@/lib/research/corpus";
+import { SourceError } from "@/lib/research/sources";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// GET ?source=&channel=&video=&t=<seconds>[&span=30][&track=<alt track>][&kind=post]
+// -> WindowResponse (lib/research/types.ts)
+//
+// The transcript ±span seconds around a cue (max 600), the cue nearest `t`
+// lit, its citation in the house format, and what umtool can play from this
+// machine. `kind=post` reads a post instead (no timeline).
+export async function GET(request: Request) {
+ try {
+ const q = new URL(request.url).searchParams;
+ const channel = q.get("channel")?.trim() ?? "";
+ const video = q.get("video")?.trim() ?? "";
+ if (!channel || !video) throw new SourceError("channel and video are required");
+ const t = Number(q.get("t") ?? "0");
+ const span = Number(q.get("span") ?? "30");
+ if (!Number.isFinite(t) || t < 0) throw new SourceError("t is a second, 0 or more");
+ if (!Number.isFinite(span) || span <= 0 || span > MAX_SPAN) throw new SourceError(`span is 1 to ${MAX_SPAN} seconds`);
+ return ok(
+ await windowOf({
+ source: q.get("source") ?? "",
+ channel,
+ video,
+ t,
+ span,
+ ...(q.get("track") ? { track: q.get("track")! } : {}),
+ kind: q.get("kind") === "post" ? "post" : "video",
+ }),
+ );
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/e2e/fixtures/research-fixture.mjs b/umtool/e2e/fixtures/research-fixture.mjs
@@ -0,0 +1,223 @@
+// The RESEARCH fixture (plans/umtool-redesign.md, R1): a composed public dir
+// the e2e server reads as its local corpus (TRANSCRIPT_LOCAL_DIR, set in
+// playwright.config.ts), the way the MCP's --local reads one, plus a few
+// channel dirs in the fixture's CHANNELS_DIR for the inventory's "held"
+// numbers when the editor cannot be asked.
+//
+// INVENTED, every word: no channel, recording or line here is real. The
+// phrase the specs search for is RESEARCH_PHRASE.
+//
+// <dest>/research-public/
+// corpus.json site.url ARCHIVE so citations are viewer links
+// summaries/ every recording's state (one deleted, one unlisted)
+// transcripts/<slug>/ one shard per channel
+// duplicates.json one cross-platform cluster (the Rumble mirror)
+// <channels>/harbor-radio, night-desk config.json + data/<id>/metadata.info.json
+//
+// Channels and what RESEARCH_PHRASE finds (8 recordings, 1 mirror folded):
+// harbor-radio 6 recordings 2019–2026; 5 match (hr-2021a twice);
+// captions and transcriptions; hr-2024a deleted,
+// hr-2026a unlisted
+// harbor-radio-rumble v1abcd mirrors hr-2024a (folded); v2efgh matches
+// night-desk 3 recordings, transcribed; nd-2023 matches
+// candace-owens a LOCAL-ONLY slug (lib/research/rules.mjs): 1 match
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const ARCHIVE = "https://archive.example";
+export const RESEARCH_PHRASE = "lighthouse budget";
+
+const FILLER = [
+ "okay so where were we",
+ "the tide was out again this morning",
+ "we got a lot of letters about the ferry",
+ "somebody asked about the harbor master",
+ "let me read the next one",
+ "the council meets on thursday",
+ "that is not what they told us last year",
+ "anyway the boats are still running",
+ "the fog came in early tonight",
+ "we will put the numbers on the website",
+ "thanks to everyone who called in",
+ "the weather looks rough for the weekend",
+];
+
+// Cues every 4 s from `start` for `n` lines, the lines from FILLER, with the
+// `say` lines put at their exact seconds.
+function cues(duration, say) {
+ const out = [];
+ const at = new Map(say.map(([t, text]) => [t, text]));
+ const times = new Set([0, 4, 8, 12, 16]);
+ for (const [t] of say) for (let d = -40; d <= 40; d += 4) if (t + d >= 0 && t + d < duration) times.add(t + d);
+ let i = 0;
+ for (const t of [...times].sort((a, b) => a - b)) {
+ out.push({ start: t, end: t + 3.8, text: at.get(t) ?? FILLER[i++ % FILLER.length] });
+ }
+ return out;
+}
+
+const rec = (channelSlug, channel, platform, id, title, uploadDate, fmt, duration, say, extra = {}) => ({
+ transcriptFormat: fmt,
+ slug: `${channelSlug}/${id}`,
+ id,
+ channelSlug,
+ title,
+ uploadDate,
+ duration,
+ channel,
+ description: "",
+ tags: [],
+ isLivestream: false,
+ ageRestricted: false,
+ platform,
+ webpageUrl: platform === "rumble" ? `https://rumble.com/${id}-${title.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.html` : `https://www.youtube.com/watch?v=${id}`,
+ cues: cues(duration, say),
+ ...extra,
+});
+
+const P = RESEARCH_PHRASE;
+
+export const RESEARCH_CHANNELS = [
+ {
+ slug: "harbor-radio",
+ name: "Harbor Radio",
+ records: [
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2019a", "Harbor Radio 1: the old pier", "20190314", "vtt", 1800, [[600, `the ${P} was never approved`]]),
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2021a", "Harbor Radio 52: storm season", "20210907", "vtt", 2400, [
+ [1212, `who signed off on the ${P}`],
+ [1500, `I asked twice about the ${P} and got nothing`],
+ ]),
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2022a", "Harbor Radio 80: the council vote", "20220211", "whisper-json", 3600, [[2044, `they voted the ${P} down eight to one`]]),
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2022b", "Harbor Radio 91: call-in night", "20221103", "vtt", 5400, [[900, "the lighthouse keeper called in"]]),
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2024a", "Harbor Radio 140: the audit", "20240520", "vtt", 7880, [[4972, `How much was the ${P}? You cut it all,`]]),
+ rec("harbor-radio", "Harbor Radio", "youtube", "hr-2026a", "Harbor Radio 200: looking back", "20260119", "whisper-json", 3000, [[96, `looking back the ${P} was the whole story`]]),
+ ],
+ },
+ {
+ slug: "harbor-radio-rumble",
+ name: "Harbor Radio (Rumble)",
+ platform: "rumble",
+ records: [
+ rec("harbor-radio-rumble", "Harbor Radio (Rumble)", "rumble", "v1abcd", "Harbor Radio 140: the audit", "20240521", "vtt", 7880, [[4972, `How much was the ${P}? You cut it all,`]]),
+ rec("harbor-radio-rumble", "Harbor Radio (Rumble)", "rumble", "v2efgh", "Harbor Radio clips: budget fight", "20250302", "vtt", 300, [[32, `the ${P} fight in one clip`]]),
+ ],
+ },
+ {
+ slug: "night-desk",
+ name: "Night Desk",
+ records: [
+ rec("night-desk", "Night Desk", "youtube", "nd-2022", "Night Desk: ferries", "20220615", "whisper-json", 2000, [[300, "the ferry budget is a different story"]]),
+ rec("night-desk", "Night Desk", "youtube", "nd-2023", "Night Desk: the keeper", "20230901", "whisper-json", 2400, [[400, `the keeper never saw the ${P}`]]),
+ rec("night-desk", "Night Desk", "youtube", "nd-2025", "Night Desk: winter", "20251201", "whisper-json", 1500, [[200, "winter on the coast is long"]]),
+ ],
+ },
+ {
+ slug: "candace-owens",
+ name: "Local Only Fixture",
+ records: [rec("candace-owens", "Local Only Fixture", "youtube", "lo-2025", "Local-only fixture episode", "20250610", "vtt", 600, [[12, `a word on the ${P}`]])],
+ },
+];
+
+const STATES = { "harbor-radio/hr-2024a": "deleted", "harbor-radio/hr-2026a": "unlisted" };
+
+// The editor's disk for the "held" column: harbor-radio holds five of its six
+// (hr-2022b not downloaded) and night-desk all three. The other two channels
+// are not held at all.
+const HELD = {
+ "harbor-radio": ["hr-2019a", "hr-2021a", "hr-2022a", "hr-2024a", "hr-2026a"],
+ "night-desk": ["nd-2022", "nd-2023", "nd-2025"],
+};
+
+const page = (n) => `page-${String(n).padStart(4, "0")}.json`;
+const write = (file, value) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value));
+};
+
+/** Write the composed public dir under `dest` and the held channel dirs under `channels`. */
+export function makeResearchFixture({ dest, channels }) {
+ const pub = path.join(dest, "research-public");
+ const all = RESEARCH_CHANNELS.flatMap((c) => c.records);
+ write(path.join(pub, "corpus.json"), {
+ spec: 5,
+ kind: "site",
+ generatedAt: "2026-10-14T00:00:00.000Z",
+ site: { id: "fixture", title: "Fixture archive", url: ARCHIVE },
+ totals: { channels: RESEARCH_CHANNELS.length, videos: all.length },
+ channels: RESEARCH_CHANNELS.map((c) => ({ slug: c.slug, name: c.name, videoCount: c.records.length, groupId: "default" })),
+ });
+ for (const c of RESEARCH_CHANNELS) {
+ write(path.join(pub, "transcripts", c.slug, "manifest.json"), {
+ version: 1,
+ channelSlug: c.slug,
+ pageCount: 1,
+ maxPageBytes: 8_000_000,
+ generatedAt: "2026-10-14",
+ slugToPage: Object.fromEntries(c.records.map((r) => [r.id, 0])),
+ });
+ write(path.join(pub, "transcripts", c.slug, page(0)), c.records);
+ }
+ write(path.join(pub, "summaries", "manifest.json"), {
+ version: 3,
+ totalCount: all.length,
+ pageSize: 1000,
+ pageCount: 1,
+ generatedAt: "2026-10-14T00:00:00.000Z",
+ channels: RESEARCH_CHANNELS.map((c) => ({ slug: c.slug, name: c.name, count: c.records.length })),
+ });
+ write(
+ path.join(pub, "summaries", page(0)),
+ all.map((r) => {
+ const state = STATES[r.slug];
+ return {
+ slug: r.slug,
+ id: r.id,
+ channelSlug: r.channelSlug,
+ title: r.title,
+ uploadDate: r.uploadDate,
+ date: r.uploadDate,
+ duration: String(r.duration),
+ channel: r.channel,
+ isLivestream: false,
+ ageRestricted: false,
+ isDeleted: state === "deleted",
+ isUnlisted: state === "unlisted",
+ ...(state ? { state } : {}),
+ platform: r.platform,
+ webpageUrl: r.webpageUrl,
+ };
+ }),
+ );
+ const ref = (r) => ({ slug: r.slug, id: r.id, channelSlug: r.channelSlug, channel: r.channel, platform: r.platform, title: r.title, duration: r.duration, uploadDate: r.uploadDate, hasTranscript: true });
+ const a = all.find((r) => r.slug === "harbor-radio/hr-2024a");
+ const b = all.find((r) => r.slug === "harbor-radio-rumble/v1abcd");
+ write(path.join(pub, "duplicates.json"), {
+ version: 1,
+ generatedAt: "2026-10-14T00:00:00.000Z",
+ runConfig: {},
+ totals: { videosScanned: all.length, clusters: 1, videosInClusters: 2 },
+ clusters: [
+ {
+ clusterId: "fixture-audit",
+ matchKind: "transcript",
+ score: 1,
+ contained: false,
+ durationBucket: 7880,
+ crossPlatform: true,
+ crossChannel: true,
+ videoRefs: [ref(a), ref(b)],
+ canonicalSlug: a.slug,
+ },
+ ],
+ });
+
+ for (const [slug, ids] of Object.entries(HELD)) {
+ const c = RESEARCH_CHANNELS.find((x) => x.slug === slug);
+ write(path.join(channels, slug, "config.json"), `${JSON.stringify({ handling: "youtube", name: c.name }, null, 2)}\n`);
+ for (const id of ids) {
+ const r = c.records.find((x) => x.id === id);
+ write(path.join(channels, slug, "data", id, "metadata.info.json"), { id, title: r.title, upload_date: r.uploadDate });
+ }
+ }
+ return { pub };
+}
diff --git a/umtool/lib/research/corpus.ts b/umtool/lib/research/corpus.ts
@@ -0,0 +1,414 @@
+import {
+ enumerate,
+ findPost,
+ findVideo,
+ parseSearchArgs,
+ resolveSelectedChannels,
+ type ChannelRef,
+ type SearchHit,
+} from "yt-dlp-transcript-mcp/research";
+import { cuesOfTrack, trackLabel } from "yt-dlp-transcript-common/lib/captionTracks";
+import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
+import { passesFilters } from "yt-dlp-transcript-common/lib/search/evalTree";
+import { clock } from "yt-dlp-transcript-common/lib/search/window";
+import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts";
+import { REPORTS_ROOT } from "../paths.mjs";
+import { citationText, facetsOf, hitKey, isoDate, sessionKey, trackOf, yearOf } from "./facets.mjs";
+import { readLog } from "./log.mjs";
+import { markRanges } from "./query.mjs";
+import { isLocalOnly } from "./rules.mjs";
+import { localMediaFor } from "./media";
+import { openSource, SourceError, type ChannelCensus, type Opened } from "./sources";
+import type {
+ ChannelChoice,
+ ResultHit,
+ Scope,
+ ScopeSummary,
+ SearchResponse,
+ TrackCensus,
+ WindowCue,
+ WindowResponse,
+} from "./types";
+
+// ---------------------------------------------------------------------------
+// RESEARCH OVER THE CORPUS, AS DATA (plans/umtool-redesign.md, R1).
+//
+// Every read goes through the SAME engine the MCP tools wrap
+// (yt-dlp-transcript-mcp/research): a search IS enumerate_matches' scan --
+// its scoping, filters, exclusions, alias expansion, mirror collapsing and
+// caps (MCP_POLICY) -- called once for the whole match set, never paged (the
+// coverage rule), with snippets on. Nothing here parses a tool's text, and
+// lib/research/parity.test.ts holds the two to the same total and ids.
+//
+// Read-only on the corpus. The reading log is umtool's own (log.mjs).
+// ---------------------------------------------------------------------------
+
+/** Snippets kept per recording; `matches` still counts every hit. */
+const SNIPPETS_PER_RECORDING = 12;
+const BATCH = 8;
+
+/** The tool's own arguments for a scope (and a query). */
+export function toolArgs(scope: Scope, query?: { query: string; regex?: boolean; exclude?: string[] }): Record<string, unknown> {
+ return {
+ ...(query ? { query: query.query, regex: query.regex === true } : {}),
+ ...(query?.exclude?.length ? { exclude: query.exclude } : {}),
+ ...(scope.channels?.length ? { channels: scope.channels } : {}),
+ ...(scope.dateFrom ? { date_from: scope.dateFrom } : {}),
+ ...(scope.dateTo ? { date_to: scope.dateTo } : {}),
+ ...(scope.states?.length ? { states: scope.states } : {}),
+ ...(scope.mediaType ? { media_type: scope.mediaType } : {}),
+ content_types: scope.posts ? ["video", "post"] : ["video"],
+ };
+}
+
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+/** A Scope from a query string or a JSON body, unknowns dropped. */
+export function scopeFrom(input: URLSearchParams | Record<string, unknown>): Scope {
+ const get = (k: string): unknown => (input instanceof URLSearchParams ? input.get(k) ?? undefined : input[k]);
+ const list = (k: string): string[] | undefined => {
+ const raw = input instanceof URLSearchParams ? input.getAll(k).flatMap((v) => v.split(",")) : get(k);
+ const arr = (Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [])
+ .filter((x): x is string => typeof x === "string")
+ .map((x) => x.trim())
+ .filter(Boolean);
+ return arr.length ? arr : undefined;
+ };
+ const str = (k: string): string | undefined => {
+ const v = get(k);
+ return typeof v === "string" && v.trim() ? v.trim() : undefined;
+ };
+ const media = str("media");
+ const posts = get("posts");
+ return {
+ source: str("source") ?? "",
+ ...(list("channels") ? { channels: list("channels") } : {}),
+ ...(str("from") && DATE.test(str("from")!) ? { dateFrom: str("from") } : {}),
+ ...(str("to") && DATE.test(str("to")!) ? { dateTo: str("to") } : {}),
+ ...(list("states") ? { states: list("states") } : {}),
+ ...(media === "video" || media === "livestream" ? { mediaType: media } : {}),
+ ...(posts === true || posts === "1" || posts === "true" ? { posts: true } : {}),
+ };
+}
+
+function choiceOf(ch: ChannelRef): ChannelChoice {
+ return {
+ key: ch.key,
+ slug: ch.slug,
+ name: ch.name,
+ ...(ch.videoCount != null ? { videoCount: ch.videoCount } : {}),
+ ...(ch.siteTitle ? { site: ch.siteTitle } : {}),
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ };
+}
+
+function censusOf(opened: Opened, keys: string[]): TrackCensus | null {
+ let counted = 0;
+ const sum = { transcript: 0, captions: 0, unknown: 0 };
+ for (const k of keys) {
+ const c = opened.census.get(k);
+ if (!c) continue;
+ counted++;
+ sum.transcript += c.transcript;
+ sum.captions += c.captions;
+ sum.unknown += c.unknown;
+ }
+ return counted === 0 ? null : { ...sum, counted, of: keys.length };
+}
+
+/** What a scope holds, before anything runs: the "holds …" line. */
+export async function scopeOf(scope: Scope): Promise<ScopeSummary> {
+ const opened = await openSource(scope.source);
+ const { source } = opened;
+ const parsed = parseSearchArgs(toolArgs(scope));
+ if (parsed.error) throw new SourceError(parsed.error);
+ const all = await source.listChannels();
+ const sel = await resolveSelectedChannels(source, { channels: scope.channels });
+ const keys = new Set(sel.channels.map((c) => c.key));
+ const slugs = new Map(sel.channels.map((c) => [c.slug, c]));
+ let videos = 0;
+ let first: string | null = null;
+ let last: string | null = null;
+ const index = source.videoIndex ? await source.videoIndex().catch(() => null) : null;
+ if (index && index.size > 0) {
+ for (const v of index.values()) {
+ if (!slugs.has(v.channelSlug)) continue;
+ if (parsed.filters && !passesFilters(v, parsed.filters, v)) continue;
+ videos++;
+ if (/^\d{8}$/.test(v.uploadDate)) {
+ if (!first || v.uploadDate < first) first = v.uploadDate;
+ if (!last || v.uploadDate > last) last = v.uploadDate;
+ }
+ }
+ } else {
+ videos = sel.channels.reduce((n, c) => n + (c.videoCount ?? 0), 0);
+ }
+ const aliases = await source.loadAliases().catch(() => []);
+ return {
+ source: opened.option,
+ channels: all.map(choiceOf),
+ selected: sel.channels.length,
+ videos,
+ first,
+ last,
+ tracks: censusOf(opened, [...keys]),
+ aliases: aliases.length,
+ warnings: [
+ ...parsed.warnings,
+ ...sel.unknownChannels.map((c) => `unknown channel: ${c}`),
+ ...(index && index.size > 0 ? [] : parsed.filters ? ["this source ships no summaries index: the count ignores the filters"] : []),
+ ],
+ };
+}
+
+// ── the census: transcripts vs captions, learned from a scan that read a channel whole ──
+
+type Seen = { fmt: unknown; duration: number; year: string };
+
+async function recordCensus(opened: Opened, channels: ChannelRef[], seen: Map<string, Map<string, Seen>>): Promise<void> {
+ for (const ch of channels) {
+ const recs = seen.get(ch.key);
+ if (!recs) continue;
+ let expected: number;
+ try {
+ expected = Object.keys((await opened.source.transcriptsManifest(ch)).slugToPage).length;
+ } catch {
+ continue;
+ }
+ if (recs.size < expected) continue; // read in part (a filter pruned pages, or a cap): not a census
+ const c: ChannelCensus = { total: 0, transcript: 0, captions: 0, unknown: 0, byYear: {} };
+ for (const r of recs.values()) {
+ const t = trackOf(r.fmt);
+ c.total++;
+ c[t]++;
+ const y = (c.byYear[r.year || "undated"] ??= { transcript: 0, captions: 0, unknown: 0 });
+ y[t]++;
+ }
+ opened.census.set(ch.key, c);
+ }
+}
+
+// ── search ──
+
+type Memo = { at: number; value: SearchResponse };
+const g = globalThis as { __umtoolResearchSearches?: Map<string, Memo> };
+const memo = (g.__umtoolResearchSearches ??= new Map());
+const MEMO_MS = 10 * 60_000;
+const MEMO_MAX = 8;
+
+export type SearchRequest = Scope & { query: string; regex?: boolean; exclude?: string[]; fresh?: boolean };
+
+/**
+ * One search: enumerate_matches' scan, ONCE, the whole match set -- never a
+ * page of it. The answer says whether it is complete, and what a cap left
+ * unread. The last few are kept ten minutes per session (a reload, a second
+ * tab), and a corpus that moved under them opens a new source anyway.
+ */
+export async function runSearch(req: SearchRequest): Promise<SearchResponse> {
+ const started = Date.now();
+ const opened = await openSource(req.source);
+ const scope: Scope = { ...req, source: opened.option.handle };
+ const session = sessionKey({ ...scope, query: req.query, regex: req.regex === true });
+ const cached = memo.get(session);
+ if (!req.fresh && cached && Date.now() - cached.at < MEMO_MS) {
+ const log = await readLog(REPORTS_ROOT, session);
+ return { ...cached.value, log: { marks: log.marks, ...(log.error ? { error: log.error } : {}) } };
+ }
+
+ const { source } = opened;
+ // What the scan reads, per channel: the format (transcript or captions) and
+ // the length of every record -- free, since the scan reads them anyway.
+ const seen = new Map<string, Map<string, Seen>>();
+ const e = await enumerate(source, toolArgs(scope, req), {
+ includeSnippets: true,
+ snippetsPerVideo: SNIPPETS_PER_RECORDING,
+ onRecord: (rec: TranscriptDetail, ch: ChannelRef) => {
+ let m = seen.get(ch.key);
+ if (!m) seen.set(ch.key, (m = new Map()));
+ m.set(rec.slug, {
+ fmt: (rec as { transcriptFormat?: unknown }).transcriptFormat,
+ duration: rec.duration,
+ year: yearOf(rec.uploadDate),
+ });
+ },
+ });
+ if ("error" in e) throw new SourceError(e.error);
+ const { result, parsed } = e;
+ const selection = await resolveSelectedChannels(source, { channels: scope.channels });
+ await recordCensus(opened, selection.channels, seen);
+
+ const avail = await source.availabilityMap().catch(() => new Map<string, { state: string }>());
+ const byKey = new Map(selection.channels.map((c) => [c.slug, c]));
+ const fired = result.firedAliases.map((a) => ({ pattern: a.suggestion, regex: a.useRegex === true }));
+ const q = { query: e.query, regex: req.regex === true, aliases: fired };
+ const hits: ResultHit[] = result.hits.map((h: SearchHit) => {
+ const ch = byKey.get(h.channelSlug);
+ const rec = ch ? seen.get(ch.key)?.get(h.slug) : undefined;
+ const post = h.contentType === "post";
+ return {
+ key: hitKey(h),
+ kind: post ? "post" : "video",
+ videoId: h.videoId,
+ channelSlug: h.channelSlug,
+ channelKey: ch?.key ?? h.channelSlug,
+ channelName: h.channelName,
+ ...(h.siteTitle ? { site: h.siteTitle } : {}),
+ title: h.title,
+ uploadDate: h.uploadDate,
+ track: post ? "post" : trackOf(rec?.fmt),
+ state: (avail.get(h.slug)?.state as string | undefined) ?? "available",
+ ...(rec?.duration ? { duration: rec.duration } : {}),
+ matches: h.matches,
+ snippets: h.snippets.map((s) => ({
+ t: s.seconds,
+ clock: s.clock,
+ text: s.text,
+ marks: markRanges(s.text, q),
+ ...(s.track ? { track: s.track } : {}),
+ ...(s.scope ? { scope: s.scope } : {}),
+ })),
+ ...(h.mirrors?.length ? { mirrors: h.mirrors.map((m) => ({ videoId: m.videoId, channelName: m.channelName })) } : {}),
+ ...(post && h.author ? { author: h.author } : {}),
+ ...(isLocalOnly(h.channelSlug) ? { localOnly: true } : {}),
+ };
+ });
+
+ const value: SearchResponse = {
+ session,
+ query: e.query,
+ regex: req.regex === true,
+ source: opened.option,
+ total: result.total,
+ matches: hits.reduce((n, h) => n + h.matches, 0),
+ complete: !result.truncated,
+ notReached: result.coverage.channelsNotReached,
+ ...(result.coverage.channelStopped ? { stopped: result.coverage.channelStopped } : {}),
+ scanned: result.scanned,
+ mirrorsFolded: result.duplicates.collapsed,
+ batches: Math.ceil(result.total / BATCH),
+ aliases: result.firedAliases.map((a) => a.label),
+ warnings: [
+ ...parsed.warnings,
+ ...result.selection.unknownChannels.map((c) => `unknown channel: ${c}`),
+ ...(result.postsScanned.skippedForTagFilter ? ["posts skipped: a tag filter was given"] : []),
+ ],
+ hits,
+ facets: facetsOf(hits),
+ log: { marks: {} },
+ tookMs: Date.now() - started,
+ };
+ memo.set(session, { at: Date.now(), value });
+ while (memo.size > MEMO_MAX) memo.delete(memo.keys().next().value!);
+ const log = await readLog(REPORTS_ROOT, session);
+ return { ...value, log: { marks: log.marks, ...(log.error ? { error: log.error } : {}) } };
+}
+
+// ── the reader's window ──
+
+export type WindowRequest = {
+ source: string;
+ channel: string;
+ video: string;
+ /** The cited second. */
+ t: number;
+ /** Seconds each side (the ± expand). */
+ span: number;
+ /** An alternate caption track, when the hit was in one. */
+ track?: string;
+ kind?: "video" | "post";
+};
+
+export const MAX_SPAN = 600;
+
+/** The transcript around a cue, with the cue lit, and its citation. */
+export async function windowOf(req: WindowRequest): Promise<WindowResponse> {
+ const opened = await openSource(req.source);
+ const { source } = opened;
+ const avail = await source.availabilityMap().catch(() => new Map<string, { state: string }>());
+
+ if (req.kind === "post") {
+ const found = await findPost(source, req.video, req.channel);
+ if (!found) throw new SourceError(`no post ${req.video} in ${opened.option.label}`, 404);
+ const { ch, post } = found;
+ const date = isoDate(post.uploadDate);
+ const author = post.authorName || post.author;
+ const url = viewerPostUrl(ch.siteUrl ?? source.publicOrigin(), post.slug) ?? post.url ?? null;
+ return {
+ kind: "post",
+ title: `Post by ${author}`,
+ channelSlug: ch.slug,
+ channelName: ch.name,
+ videoId: post.id,
+ uploadDate: post.uploadDate,
+ duration: 0,
+ state: "available",
+ track: "post",
+ cueCount: 0,
+ at: 0,
+ span: 0,
+ cues: [],
+ lit: -1,
+ citation: { text: citationText({ quote: post.text, title: "", post: { author, date }, url }), url },
+ media: [],
+ text: post.text,
+ author,
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ };
+ }
+
+ const found = await findVideo(source, req.video, req.channel);
+ if (!found) throw new SourceError(`no recording ${req.video} in ${opened.option.label}`, 404);
+ const { ch, record } = found;
+ const all = (cuesOfTrack(record, req.track) ?? record.cues ?? []).filter((c) => c && typeof c.start === "number");
+ const span = Math.max(5, Math.min(MAX_SPAN, Math.round(req.span)));
+ // The cited cue: the one starting nearest the cite (a snippet's second is its cue's start).
+ let litAll = -1;
+ let best = Infinity;
+ for (let i = 0; i < all.length; i++) {
+ const d = Math.abs(all[i].start - req.t);
+ if (d < best) {
+ best = d;
+ litAll = i;
+ }
+ }
+ const lo = req.t - span;
+ const hi = req.t + span;
+ const cues: WindowCue[] = [];
+ let lit = -1;
+ for (let i = 0; i < all.length; i++) {
+ const c = all[i];
+ if (c.start < lo || c.start > hi) continue;
+ if (i === litAll) lit = cues.length;
+ cues.push({ t: c.start, end: c.end, text: c.text });
+ }
+ const litCue = litAll >= 0 ? all[litAll] : null;
+ const at = litCue ? litCue.start : req.t;
+ const url = momentUrl({
+ siteOrigin: ch.siteUrl ?? source.publicOrigin(),
+ slug: record.slug,
+ seconds: at,
+ webpageUrl: record.webpageUrl,
+ platform: record.platform,
+ });
+ const alt = req.track && req.track !== record.track ? req.track : undefined;
+ return {
+ kind: "video",
+ title: record.title,
+ channelSlug: ch.slug,
+ channelName: ch.name,
+ videoId: record.id,
+ uploadDate: record.uploadDate,
+ duration: record.duration || (all.length ? all[all.length - 1].end : 0),
+ state: (avail.get(record.slug)?.state as string | undefined) ?? "available",
+ track: trackOf((record as { transcriptFormat?: unknown }).transcriptFormat),
+ ...(alt ? { trackLabel: trackLabel(alt) } : {}),
+ cueCount: all.length,
+ at,
+ span,
+ cues,
+ lit,
+ citation: { text: citationText({ quote: litCue?.text, title: record.title, clock: clock(at), url }), url },
+ media: await localMediaFor(ch.slug, record),
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ };
+}
diff --git a/umtool/lib/research/coverage.ts b/umtool/lib/research/coverage.ts
@@ -0,0 +1,157 @@
+import { channelCoverage, type ChannelCoverage } from "yt-dlp-transcript-common/controller/channelCoverage";
+import { mapConcurrent } from "yt-dlp-transcript-common/lib/concurrency";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { describeFetchError, editorFromEnv, resolveSelectedChannels, type ChannelRef } from "yt-dlp-transcript-mcp/research";
+import { CHANNELS_DIR } from "../paths.mjs";
+import { yearOf } from "./facets.mjs";
+import { isLocalOnly } from "./rules.mjs";
+import { openSource } from "./sources";
+import type { CoverageResponse, CoverageRow, Scope } from "./types";
+
+// ---------------------------------------------------------------------------
+// THE ARCHIVE INVENTORY's numbers (plans/umtool-redesign.md, "Research,
+// first-class" 6): what the archive can and cannot answer, channels × years.
+//
+// published the source's own summaries index, by upload year and state:
+// what a search over this source can reach
+// held what the editor holds on disk (channel_coverage: every held
+// video by its coverage date, and the spans with nothing held),
+// asked of the editor's GET /api/ops/coverage exactly as the MCP's
+// channel_coverage asks it. When umtool has no WORKER_TOKEN, or the
+// editor does not answer, the answer says which -- and for the
+// local corpus reads the same controller on disk instead
+// (common/controller/channelCoverage.ts, read only)
+// tracks transcripts vs captions per year, for a channel a search has
+// read whole (lib/research/corpus.ts's census)
+// ---------------------------------------------------------------------------
+
+/** The inventory marks a gap longer than this (the canvas: "gap over 60 days that year"). */
+export const GAP_DAYS = 60;
+const TIMEOUT_MS = 15_000;
+
+type Held = NonNullable<CoverageRow["held"]>;
+
+function heldOf(c: Pick<ChannelCoverage, "held" | "byYear" | "gaps" | "first" | "last">): Held {
+ const gapYears = new Set<string>();
+ for (const g of c.gaps) {
+ for (let y = Number(g.after.slice(0, 4)); y <= Number(g.before.slice(0, 4)); y++) gapYears.add(String(y));
+ }
+ return {
+ total: c.held,
+ byYear: c.byYear,
+ gaps: c.gaps,
+ gapYears: [...gapYears].sort(),
+ first: c.first,
+ last: c.last,
+ };
+}
+
+type EditorAsk = { ok: true; body: ChannelCoverage } | { ok: false; status?: number; why: string; stop: boolean };
+
+/** One channel from the editor, as the MCP's channel_coverage asks it. */
+async function askEditor(slug: string): Promise<EditorAsk> {
+ const editor = editorFromEnv(process.env);
+ if (!editor) return { ok: false, why: "WORKER_TOKEN is not set for umtool, so the editor was not asked", stop: true };
+ const q = new URLSearchParams({ slug, gapDays: String(GAP_DAYS) });
+ let res: Response;
+ try {
+ res = await fetch(`${editor.url}/api/ops/coverage?${q}`, {
+ headers: { authorization: `Bearer ${editor.token}` },
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (e) {
+ return { ok: false, why: `the editor at ${editor.url} is unreachable: ${describeFetchError(e, TIMEOUT_MS)}`, stop: true };
+ }
+ const body = (await res.json().catch(() => null)) as (ChannelCoverage & { error?: string }) | null;
+ if (res.ok && body && typeof body.held === "number") return { ok: true, body };
+ if (res.status === 503) return { ok: false, status: 503, why: "the editor's ops surface is off (it has no WORKER_TOKEN)", stop: true };
+ if (res.status === 401) return { ok: false, status: 401, why: "the editor refused umtool's WORKER_TOKEN", stop: true };
+ const err = body?.error ?? `HTTP ${res.status}`;
+ // A channel the editor does not hold is an answer about that channel; a
+ // route the editor does not have is an answer about the editor.
+ if (res.status === 404 && /^Channel ".*" not found$/.test(err)) return { ok: false, status: 404, why: err, stop: false };
+ return { ok: false, status: res.status, why: `the editor answered ${res.status}: ${err}`, stop: true };
+}
+
+async function fromDisk(slug: string): Promise<Held | null> {
+ try {
+ return heldOf(await channelCoverage({ ...getPaths(), channelsDir: CHANNELS_DIR }, slug, { gapDays: GAP_DAYS }));
+ } catch {
+ return null;
+ }
+}
+
+export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
+ const opened = await openSource(scope.source);
+ const { source } = opened;
+ const sel = await resolveSelectedChannels(source, { channels: scope.channels });
+ const channels: ChannelRef[] = sel.channels;
+
+ // Published, from the summaries index (one read for every channel).
+ const published = new Map<string, CoverageRow["published"]>();
+ const index = source.videoIndex ? await source.videoIndex().catch(() => null) : null;
+ for (const ch of channels) published.set(ch.slug, { total: 0, byYear: {}, byState: {} });
+ if (index) {
+ for (const v of index.values()) {
+ const p = published.get(v.channelSlug);
+ if (!p) continue;
+ p.total++;
+ const y = yearOf(v.uploadDate);
+ if (y) p.byYear[y] = (p.byYear[y] ?? 0) + 1;
+ p.byState[v.state] = (p.byState[v.state] ?? 0) + 1;
+ }
+ }
+ for (const ch of channels) {
+ const p = published.get(ch.slug)!;
+ if (p.total === 0 && ch.videoCount) p.total = ch.videoCount;
+ }
+
+ // Held: the editor, else (local corpus) the disk.
+ let via: CoverageResponse["held"]["via"] = "editor";
+ let note: string | undefined;
+ let stopped = false;
+ const held = new Map<string, Held | null>();
+ await mapConcurrent(channels, 4, async (ch) => {
+ if (stopped) return;
+ const a = await askEditor(ch.slug);
+ if (a.ok) held.set(ch.key, heldOf(a.body));
+ else if (a.stop) {
+ stopped = true;
+ note ??= a.why;
+ } else held.set(ch.key, null);
+ });
+ if (stopped) {
+ held.clear();
+ if (opened.option.kind === "local") {
+ via = "disk";
+ note = `${note}; read on disk instead`;
+ await mapConcurrent(channels, 8, async (ch) => held.set(ch.key, await fromDisk(ch.slug)));
+ } else {
+ via = "none";
+ note = `${note}; held counts need the editor for a published source`;
+ }
+ }
+
+ const years = new Set<string>();
+ const rows: CoverageRow[] = channels.map((ch) => {
+ const p = published.get(ch.slug)!;
+ const h = held.get(ch.key) ?? null;
+ const census = opened.census.get(ch.key);
+ for (const y of Object.keys(p.byYear)) years.add(y);
+ for (const y of Object.keys(h?.byYear ?? {})) years.add(y);
+ return {
+ key: ch.key,
+ slug: ch.slug,
+ name: ch.name,
+ ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}),
+ published: p,
+ held: h,
+ tracks: census ? census.byYear : null,
+ };
+ });
+ const ys = [...years].filter((y) => /^\d{4}$/.test(y)).map(Number).sort((a, b) => a - b);
+ const span: string[] = [];
+ for (let y = ys[0]; ys.length && y <= ys[ys.length - 1]; y++) span.push(String(y));
+ rows.sort((a, b) => (b.held?.total ?? b.published.total) - (a.held?.total ?? a.published.total) || a.name.localeCompare(b.name));
+ return { source: opened.option, years: span, rows, held: { via, ...(note ? { note } : {}) }, gapDays: GAP_DAYS };
+}
diff --git a/umtool/lib/research/facets.mjs b/umtool/lib/research/facets.mjs
@@ -0,0 +1,98 @@
+// The Research results' facets, keys and citation text: pure, so the server
+// that builds a result, the page that filters it and the tests agree.
+import { createHash } from "node:crypto";
+
+/**
+ * What a record's text is, from its `transcriptFormat` (the per-video
+ * transcript.cues.json field the index spreads into every shard record):
+ * `vtt` is the platform's captions, `whisper-json` / `chough-json` our own
+ * transcription. A record without one (an older build) is unknown, never
+ * guessed.
+ *
+ * @param {unknown} format
+ * @returns {"transcript" | "captions" | "unknown"}
+ */
+export function trackOf(format) {
+ if (format === "vtt") return "captions";
+ if (typeof format === "string" && /-json$/.test(format)) return "transcript";
+ return "unknown";
+}
+
+/** "YYYYMMDD" → "YYYY", or "" when there is no date. */
+export const yearOf = (d) => (typeof d === "string" && /^\d{4}/.test(d) ? d.slice(0, 4) : "");
+
+/** "YYYYMMDD" → "YYYY-MM-DD" (as it is; anything else unchanged). */
+export const isoDate = (d) => (typeof d === "string" && /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : d ?? "");
+
+/** A hit's reading-log key: `<channelSlug>/<id>`, the slug the viewer uses. */
+export const hitKey = (h) => `${h.channelSlug}/${h.videoId}`;
+
+/**
+ * Facets over the result rows: per year (every year between the first and the
+ * last, zeros kept, so the histogram's gaps are visible), per channel (most
+ * first), per track and per state.
+ *
+ * @param {{ channelSlug: string, channelName: string, uploadDate: string, track: string, state: string }[]} hits
+ */
+export function facetsOf(hits) {
+ const years = new Map();
+ const channels = new Map();
+ /** @type {Record<string, number>} */
+ const tracks = {};
+ /** @type {Record<string, number>} */
+ const states = {};
+ for (const h of hits) {
+ const y = yearOf(h.uploadDate);
+ if (y) years.set(y, (years.get(y) ?? 0) + 1);
+ const c = channels.get(h.channelSlug) ?? { slug: h.channelSlug, name: h.channelName, n: 0 };
+ c.n += 1;
+ channels.set(h.channelSlug, c);
+ tracks[h.track] = (tracks[h.track] ?? 0) + 1;
+ states[h.state] = (states[h.state] ?? 0) + 1;
+ }
+ const ys = [...years.keys()].map(Number).sort((a, b) => a - b);
+ const span = [];
+ for (let y = ys[0]; ys.length && y <= ys[ys.length - 1]; y++) span.push({ year: String(y), n: years.get(String(y)) ?? 0 });
+ return {
+ years: span,
+ channels: [...channels.values()].sort((a, b) => b.n - a.n || a.name.localeCompare(b.name)),
+ tracks,
+ states,
+ };
+}
+
+/**
+ * The scratch session a reading log belongs to until R2's cases exist: the
+ * query and the scope, normalised, hashed. Same query, same scope, same log.
+ *
+ * @param {Record<string, unknown>} scope source, query, regex, channels, dates, states, mediaType, posts
+ */
+export function sessionKey(scope) {
+ const norm = {
+ source: String(scope.source ?? ""),
+ query: String(scope.query ?? "").trim(),
+ regex: scope.regex === true,
+ channels: [...((scope.channels ?? []))].map(String).sort(),
+ dateFrom: scope.dateFrom ?? "",
+ dateTo: scope.dateTo ?? "",
+ states: [...((scope.states ?? []))].map(String).sort(),
+ mediaType: scope.mediaType ?? "",
+ posts: scope.posts === true,
+ };
+ return createHash("sha1").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
+}
+
+/**
+ * A citation in the house format (mcp/src/instructions.ts; common's
+ * authoringRules): the quoted words, then `[<title> @ <m:ss>](<moment url>)`
+ * for a video, `[post by <author>, <date>](<url>)` for a post. A video with
+ * no link (no viewer origin and no platform URL) is cited by its title and
+ * time alone, never with an invented link.
+ *
+ * @param {{ quote?: string, title: string, clock?: string, url?: string | null, post?: { author: string, date: string } }} c
+ */
+export function citationText(c) {
+ const quote = c.quote ? `"${c.quote.replace(/\s+/g, " ").trim()}" ` : "";
+ const label = c.post ? `post by ${c.post.author}, ${c.post.date}` : `${c.title} @ ${c.clock ?? "0:00"}`;
+ return c.url ? `${quote}[${label}](${c.url})` : `${quote}${label}`;
+}
diff --git a/umtool/lib/research/facets.test.mjs b/umtool/lib/research/facets.test.mjs
@@ -0,0 +1,65 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { citationText, facetsOf, hitKey, isoDate, sessionKey, trackOf, yearOf } from "./facets.mjs";
+import { isLocalOnly, LOCAL_ONLY_CHANNELS } from "./rules.mjs";
+
+test("trackOf: vtt is captions, *-json our transcription, anything else unknown", () => {
+ assert.equal(trackOf("vtt"), "captions");
+ assert.equal(trackOf("whisper-json"), "transcript");
+ assert.equal(trackOf("chough-json"), "transcript");
+ assert.equal(trackOf(undefined), "unknown");
+ assert.equal(trackOf("srt"), "unknown");
+});
+
+test("facets: every year in the span (zeros kept), channels most first, tracks, states", () => {
+ const h = (channelSlug, uploadDate, track = "captions", state = "available") => ({ channelSlug, channelName: channelSlug.toUpperCase(), uploadDate, track, state });
+ const f = facetsOf([h("a", "20190105"), h("b", "20220101"), h("b", "20220301", "transcript"), h("a", "20220601", "captions", "deleted")]);
+ assert.deepEqual(f.years, [
+ { year: "2019", n: 1 },
+ { year: "2020", n: 0 },
+ { year: "2021", n: 0 },
+ { year: "2022", n: 3 },
+ ]);
+ assert.deepEqual(f.channels.map((c) => [c.slug, c.n]), [
+ ["a", 2],
+ ["b", 2],
+ ]);
+ assert.deepEqual(f.tracks, { captions: 3, transcript: 1 });
+ assert.deepEqual(f.states, { available: 3, deleted: 1 });
+ assert.deepEqual(facetsOf([]).years, []);
+});
+
+test("keys and dates", () => {
+ assert.equal(hitKey({ channelSlug: "c", videoId: "v" }), "c/v");
+ assert.equal(yearOf("20240102"), "2024");
+ assert.equal(isoDate("20240102"), "2024-01-02");
+});
+
+test("sessionKey: same query and scope, same session, whatever the order", () => {
+ const a = sessionKey({ source: "local:/x", query: "fired ", channels: ["b", "a"] });
+ const b = sessionKey({ source: "local:/x", query: "fired", channels: ["a", "b"] });
+ assert.equal(a, b);
+ assert.match(a, /^[0-9a-f]{16}$/);
+ assert.notEqual(a, sessionKey({ source: "local:/x", query: "fired", channels: ["a"] }));
+ assert.notEqual(a, sessionKey({ source: "local:/x", query: "fired", channels: ["a", "b"], regex: true }));
+});
+
+test("citationText: the house format for a video, a post, and a video with no link", () => {
+ assert.equal(
+ citationText({ quote: "How many employees?\nYou fired them all,", title: "Kino Casino", clock: "1:22:53", url: "https://j.example/?v=c%2Fv&t=4973" }),
+ '"How many employees? You fired them all," [Kino Casino @ 1:22:53](https://j.example/?v=c%2Fv&t=4973)',
+ );
+ assert.equal(
+ citationText({ quote: "No.", title: "", post: { author: "synthbaker", date: "2026-02-11" }, url: "https://x.example/p/1" }),
+ '"No." [post by synthbaker, 2026-02-11](https://x.example/p/1)',
+ );
+ assert.equal(citationText({ title: "T", clock: "0:05", url: null }), "T @ 0:05");
+});
+
+test("Candace channels are local-only", () => {
+ assert.deepEqual([...LOCAL_ONLY_CHANNELS], ["candace-owens", "realcandaceo"]);
+ assert.ok(isLocalOnly("realcandaceo"));
+ assert.ok(isLocalOnly(" Candace-Owens"));
+ assert.ok(!isLocalOnly("the-quartering"));
+ assert.ok(!isLocalOnly(undefined));
+});
diff --git a/umtool/lib/research/fetch.ts b/umtool/lib/research/fetch.ts
@@ -0,0 +1,70 @@
+import {
+ fetchClip,
+ NO_EDITOR_TEXT,
+ resolveClipTarget,
+ validateFetchClipArgs,
+ type FetchClipDeps,
+ type FetchClipOutcome,
+} from "yt-dlp-transcript-mcp/research";
+import { openSource, SourceError } from "./sources";
+import type { FetchAnswer } from "./types";
+
+// ---------------------------------------------------------------------------
+// FETCH CLIP from the reader: the seconds behind a cite, through the editor's
+// fetch-window route -- EXACTLY as the MCP's fetch_clip asks (its client,
+// mcp/src/fetchClip.ts, and its cite-to-directory mapping, clipTarget.ts),
+// never yt-dlp by hand. The editor paces it, uses its cookies, writes the file
+// into the corpus and records who asked ("umtool") and why.
+//
+// The route never waits: a fetch is queued and the page polls by job id
+// (`{ job }`, fetch_clip's resume), one short answer per poll.
+// ---------------------------------------------------------------------------
+
+const deps: FetchClipDeps = {
+ env: process.env,
+ fetch: (url, init) => globalThis.fetch(url, init),
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
+ now: () => Date.now(),
+};
+
+/** The answer, in the page's words. */
+export function answerOf(o: FetchClipOutcome): FetchAnswer {
+ switch (o.kind) {
+ case "cached":
+ return { state: "ready", file: o.file, from: o.from, to: o.to, cached: true };
+ case "fetched":
+ return o.file
+ ? { state: "ready", file: o.file, ...(o.from !== undefined ? { from: o.from } : {}), ...(o.to !== undefined ? { to: o.to } : {}), cached: false }
+ : { state: "failed", message: "the editor finished but named no file", job: o.jobId };
+ case "queued":
+ return { state: "queued", job: o.jobId, status: o.status };
+ case "no_editor":
+ return { state: "failed", message: NO_EDITOR_TEXT.replace(/^fetch_clip: /, "") };
+ case "cooldown":
+ return { state: "failed", message: `${o.platform} is cooling down after a 429 (${Math.ceil(o.cooldownMs / 60000)} min): ${o.error}` };
+ case "refused":
+ return { state: "failed", message: `the editor refused it (${o.status}): ${o.error}`, ...(o.jobId ? { job: o.jobId } : {}) };
+ case "failed":
+ return { state: "failed", message: `the editor's job ${o.status}: ${o.log || "no reason given"}`, job: o.jobId };
+ case "unreachable":
+ return { state: "failed", message: `the editor at ${o.url} did not answer: ${o.message}`, ...(o.jobId ? { job: o.jobId } : {}) };
+ }
+}
+
+export type FetchRequest =
+ | { job: string }
+ | { source: string; channel: string; video: string; start: number; end: number; reason: string };
+
+export async function fetchForReader(req: FetchRequest): Promise<FetchAnswer> {
+ const args =
+ "job" in req
+ ? { job: req.job, wait_seconds: 0 }
+ : { channel: req.channel, video: req.video, start: req.start, end: req.end, reason: req.reason, wait_seconds: 0 };
+ const v = validateFetchClipArgs(args);
+ if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, ""));
+ if (!("job" in req)) {
+ const opened = await openSource(req.source);
+ await resolveClipTarget(opened.source, opened.option.handle, v.request);
+ }
+ return answerOf(await fetchClip(v.request, deps, { requestedBy: "umtool" }));
+}
diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts
@@ -0,0 +1,68 @@
+// Research's addresses, one builder per URL shape (the lib/hrefs.ts rule:
+// a literal link is one P-phase has to find by hand). In their own module
+// because lib/hrefs.ts belongs to P3 while R1 runs beside it.
+//
+// The page's state is in its query, so a search is a link:
+// /research?q=…&source=…&channels=a,b&from=YYYY-MM-DD&to=…&states=…&media=…&posts=1
+import { withQuery } from "../hrefs";
+import type { Scope } from "./types";
+
+export type ResearchQuery = Partial<Scope> & { q?: string };
+
+function scopeQuery(s: Partial<Scope>) {
+ return {
+ source: s.source,
+ channels: s.channels?.length ? s.channels.join(",") : undefined,
+ from: s.dateFrom,
+ to: s.dateTo,
+ states: s.states?.length ? s.states.join(",") : undefined,
+ media: s.mediaType,
+ posts: s.posts === true,
+ };
+}
+
+/** The Research page, with a query and a scope when given. */
+export function researchHref(q: ResearchQuery = {}): string {
+ return withQuery("/research", { q: q.q, ...scopeQuery(q) });
+}
+
+/** The archive inventory (channels × years). */
+export function researchArchiveHref(q: Partial<Scope> = {}): string {
+ return withQuery("/research/archive", scopeQuery(q));
+}
+
+/** GET /api/research/scope for a scope. */
+export function researchScopeApi(s: Partial<Scope>): string {
+ return withQuery("/api/research/scope", scopeQuery(s));
+}
+
+/** GET /api/research/coverage for a scope. */
+export function researchCoverageApi(s: Partial<Scope>): string {
+ return withQuery("/api/research/coverage", scopeQuery(s));
+}
+
+/** GET /api/research/window: the transcript ±span around a cue. */
+export function researchWindowApi(w: {
+ source: string;
+ channel: string;
+ video: string;
+ t: number;
+ span?: number;
+ track?: string;
+ kind?: "video" | "post";
+}): string {
+ return withQuery("/api/research/window", {
+ source: w.source,
+ channel: w.channel,
+ video: w.video,
+ t: w.t,
+ span: w.span,
+ track: w.track,
+ kind: w.kind === "post" ? "post" : undefined,
+ });
+}
+
+/** GET /api/research/media: one local file the reader offered. */
+export function researchMediaApi(m: { source: string; channel: string; video: string; file: string }): string {
+ return withQuery("/api/research/media", m);
+}
diff --git a/umtool/lib/research/log.mjs b/umtool/lib/research/log.mjs
@@ -0,0 +1,147 @@
+// THE READING LOG (plans/umtool-redesign.md, "Research, first-class" 4): each
+// hit of a search is read, skipped or unread, and the header says "read 37 of
+// 97" -- the sweep discipline's coverage rule, made visible for the human.
+//
+// REPORTS_ROOT/.umtool/research/sessions/<session>.json
+// { format: "umtool-research-log", version: 1, session, query, scope,
+// updatedAt, marks: { "<channelSlug>/<id>": { state, at } } }
+//
+// A SCRATCH SESSION keyed by query + scope (facets.mjs sessionKey) until R2's
+// cases exist; a case will carry its own. Umtool-side, NEVER in the corpus:
+// REPORTS_ROOT's dot-dirs are state the project walk skips.
+//
+// The lifecycle store's discipline (lib/lifecycle.mjs): one writer, serialised
+// in-process; every write a whole file to a temp name and a rename; a file
+// that does not parse is never overwritten (a write refuses with 409 until
+// somebody fixes it; a read treats it as empty and says so in `error`).
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const LOG_FORMAT = "umtool-research-log";
+export const LOG_VERSION = 1;
+export const MARK_STATES = ["read", "skipped"];
+
+const SESSION_RE = /^[0-9a-f]{16}$/;
+// `<channelSlug>/<id>`: the slug grammar and the editor's id grammar.
+const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[\w.-]{1,128}$/;
+
+export class LogError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "LogError";
+ this.status = status;
+ }
+}
+
+export const isSession = (s) => typeof s === "string" && SESSION_RE.test(s);
+export const isHitKey = (k) => typeof k === "string" && KEY_RE.test(k) && !k.split("/").some((p) => p === "." || p === "..");
+
+/** The file for one session under a reports root. */
+export function logFile(reportsRoot, session) {
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research", "sessions", `${session}.json`);
+}
+
+/**
+ * The log of one session. A missing file is an empty log; an unreadable one
+ * is empty with `error`.
+ *
+ * @param {string} reportsRoot
+ * @param {string} session
+ * @returns {Promise<{ marks: Record<string, { state: "read" | "skipped", at: string }>, query?: string, scope?: Record<string, unknown>, error?: string }>}
+ */
+export async function readLog(reportsRoot, session) {
+ if (!isSession(session)) return { marks: {}, error: "not a session id" };
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ logFile(reportsRoot, session), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return { marks: {} };
+ return { marks: {}, error: `the reading log cannot be read: ${err?.message ?? err}` };
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ return { marks: {}, error: `the reading log is not JSON: ${err.message}` };
+ }
+ if (!raw || typeof raw !== "object" || raw.format !== LOG_FORMAT || typeof raw.marks !== "object" || !raw.marks) {
+ return { marks: {}, error: "not a umtool-research-log file" };
+ }
+ /** @type {Record<string, { state: "read" | "skipped", at: string }>} */
+ const marks = {};
+ for (const [k, m] of Object.entries(raw.marks)) {
+ if (!isHitKey(k) || !m || typeof m !== "object" || !MARK_STATES.includes(m.state)) continue;
+ marks[k] = { state: m.state, at: typeof m.at === "string" ? m.at : "" };
+ }
+ return {
+ marks,
+ ...(typeof raw.query === "string" ? { query: raw.query } : {}),
+ ...(raw.scope && typeof raw.scope === "object" ? { scope: raw.scope } : {}),
+ };
+}
+
+/** Counts over a set of hit keys: read, skipped, unread. */
+export function tally(marks, keys) {
+ let read = 0;
+ let skipped = 0;
+ for (const k of keys) {
+ const s = marks[k]?.state;
+ if (s === "read") read++;
+ else if (s === "skipped") skipped++;
+ }
+ return { read, skipped, unread: keys.length - read - skipped, total: keys.length };
+}
+
+let chain = Promise.resolve();
+
+/**
+ * Mark one hit read, skipped, or (`unread`) clear its mark. `meta` names the
+ * query and scope in the file, for a person reading it later.
+ *
+ * @param {string} reportsRoot
+ * @param {string} session
+ * @param {string} key `<channelSlug>/<id>`
+ * @param {"read" | "skipped" | "unread"} state
+ * @param {{ query?: string, scope?: Record<string, unknown>, now?: Date }} [meta]
+ */
+export function markHit(reportsRoot, session, key, state, meta = {}) {
+ if (!isSession(session)) return Promise.reject(new LogError(`not a session id: ${JSON.stringify(session)}`));
+ if (!isHitKey(key)) return Promise.reject(new LogError(`not a hit: ${JSON.stringify(key)} (channel/id)`));
+ if (state !== "unread" && !MARK_STATES.includes(state)) {
+ return Promise.reject(new LogError(`state is read | skipped | unread, not ${JSON.stringify(state)}`));
+ }
+ const run = chain.then(() => write(reportsRoot, session, key, state, meta));
+ chain = run.catch(() => {});
+ return run;
+}
+
+async function write(reportsRoot, session, key, state, meta) {
+ const file = logFile(reportsRoot, session);
+ const read = await readLog(reportsRoot, session);
+ if (read.error) throw new LogError(`${read.error}; fix or remove ${file} first`, 409);
+ const now = (meta.now ?? new Date()).toISOString();
+ const marks = { ...read.marks };
+ if (state === "unread") delete marks[key];
+ else marks[key] = { state, at: now };
+ const query = typeof meta.query === "string" ? meta.query.slice(0, 500) : read.query;
+ const scope = meta.scope && typeof meta.scope === "object" ? meta.scope : read.scope;
+ const doc = {
+ format: LOG_FORMAT,
+ version: LOG_VERSION,
+ session,
+ ...(query !== undefined ? { query } : {}),
+ ...(scope !== undefined ? { scope } : {}),
+ updatedAt: now,
+ marks: Object.fromEntries(Object.entries(marks).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
+ };
+ await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return { key, state, at: now, marks: doc.marks };
+}
diff --git a/umtool/lib/research/log.test.mjs b/umtool/lib/research/log.test.mjs
@@ -0,0 +1,63 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { LOG_FORMAT, isHitKey, logFile, markHit, readLog, tally } from "./log.mjs";
+
+const S = "FAKE-TEST-VALUE";
+
+test("a missing log is empty; marks round-trip; unread clears", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-"));
+ try {
+ assert.deepEqual(await readLog(root, S), { marks: {} });
+ await markHit(root, S, "chan/vid1", "read", { query: "fired", scope: { source: "local:/x" }, now: new Date("2026-10-14T00:00:00Z") });
+ await markHit(root, S, "chan/vid2", "skipped");
+ const r = await readLog(root, S);
+ assert.deepEqual(Object.keys(r.marks), ["chan/vid1", "chan/vid2"]);
+ assert.equal(r.marks["chan/vid1"].state, "read");
+ assert.equal(r.marks["chan/vid1"].at, "2026-10-14T00:00:00.000Z");
+ assert.equal(r.query, "fired");
+ assert.deepEqual(r.scope, { source: "local:/x" });
+ await markHit(root, S, "chan/vid2", "unread");
+ assert.deepEqual(Object.keys((await readLog(root, S)).marks), ["chan/vid1"]);
+ const doc = JSON.parse(await readFile(logFile(root, S), "utf8"));
+ assert.equal(doc.format, LOG_FORMAT);
+ assert.equal(doc.session, S);
+ assert.equal(doc.query, "fired", "the query survives a later mark without one");
+ assert.ok(logFile(root, S).includes(`${path.sep}.umtool${path.sep}research${path.sep}sessions${path.sep}`));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("writes are serialised: a burst of marks all land", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-"));
+ try {
+ await Promise.all(Array.from({ length: 20 }, (_, i) => markHit(root, S, `c/v${i}`, i % 2 ? "read" : "skipped")));
+ const r = await readLog(root, S);
+ assert.equal(Object.keys(r.marks).length, 20);
+ assert.deepEqual(tally(r.marks, [...Object.keys(r.marks), "c/other"]), { read: 10, skipped: 10, unread: 1, total: 21 });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("an unreadable log is never overwritten; bad input is refused", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-"));
+ try {
+ await mkdir(path.dirname(logFile(root, S)), { recursive: true });
+ await writeFile(logFile(root, S), "{not json");
+ assert.match((await readLog(root, S)).error, /not JSON/);
+ await assert.rejects(markHit(root, S, "c/v", "read"), (e) => e.status === 409);
+ assert.equal(await readFile(logFile(root, S), "utf8"), "{not json");
+ await assert.rejects(markHit(root, "../../x", "c/v", "read"), (e) => e.status === 400);
+ await assert.rejects(markHit(root, S, "../v", "read"), (e) => e.status === 400);
+ await assert.rejects(markHit(root, S, "c/v", "done"), (e) => e.status === 400);
+ assert.ok(isHitKey("the-quartering/vxe1ae"));
+ assert.ok(!isHitKey("c/.."));
+ assert.ok(!isHitKey("c/v/w"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/research/media.ts b/umtool/lib/research/media.ts
@@ -0,0 +1,98 @@
+import { readdir, stat } from "node:fs/promises";
+import path from "node:path";
+import { CLIPS_DIR_NAME, hasClipWindowExt, parseClipWindowName } from "yt-dlp-transcript-common/lib/clipWindow";
+import { isRealAudioFile, isSourceMediaFile } from "yt-dlp-transcript-common/lib/mediaFiles";
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { CHANNELS_DIR } from "../paths.mjs";
+import type { LocalMedia } from "./types";
+
+// ---------------------------------------------------------------------------
+// What the reader can PLAY from this machine: the editor's corpus, read only.
+//
+// channels/<slug>/data/<dir>/clips/<from>-<to>.<ext> a fetched window
+// channels/<slug>/data/<dir>/source-media.<ext> a kept source
+// channels/<slug>/data/<dir>/audio.<ext> its audio
+//
+// `<dir>` is the editor's directory id: extractVideoId of the record's URL,
+// which on Rumble is the URL slug, not the embed id the archive cites
+// (FACTS, fetch_clip). A big file may be a relative link into media/, and that
+// may be on a drive that is not mounted: a file that does not stat is not
+// offered. Nothing here writes; a missing clip is fetched through the editor.
+// ---------------------------------------------------------------------------
+
+const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+const ID = /^[\w.-]{1,128}$/;
+
+/** The editor's directory ids a record may live under, most likely first. */
+export function dirIdsFor(record: { id: string; webpageUrl?: string }): string[] {
+ const mapped = record.webpageUrl ? extractVideoId(record.webpageUrl) : null;
+ return [...new Set([mapped, record.id].filter((x): x is string => !!x && ID.test(x) && x !== "." && x !== ".."))];
+}
+
+function videoDir(slug: string, dirId: string): string | null {
+ if (!SLUG.test(slug) || !ID.test(dirId) || dirId === "." || dirId === "..") return null;
+ return path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "data", dirId);
+}
+
+async function isFile(p: string): Promise<boolean> {
+ const st = await stat(/* turbopackIgnore: true */ p).catch(() => null);
+ return !!st?.isFile();
+}
+
+/** Every playable file for a record, windows first (tightest last-fetched order kept). */
+export async function localMediaFor(slug: string, record: { id: string; webpageUrl?: string }): Promise<LocalMedia[]> {
+ const out: LocalMedia[] = [];
+ for (const id of dirIdsFor(record)) {
+ const dir = videoDir(slug, id);
+ if (!dir) continue;
+ const clipsDir = path.join(/* turbopackIgnore: true */ dir, CLIPS_DIR_NAME);
+ for (const name of (await readdir(/* turbopackIgnore: true */ clipsDir).catch(() => [] as string[])).sort()) {
+ if (!hasClipWindowExt(name)) continue;
+ const w = parseClipWindowName(name);
+ if (!w || !(await isFile(path.join(/* turbopackIgnore: true */ clipsDir, name)))) continue;
+ out.push({ name: `${id}/${CLIPS_DIR_NAME}/${name}`, kind: "window", from: w.from, to: w.to });
+ }
+ for (const name of (await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[])).sort()) {
+ const kind = isSourceMediaFile(name) ? "source" : isRealAudioFile(name) ? "audio" : null;
+ if (!kind || !(await isFile(path.join(/* turbopackIgnore: true */ dir, name)))) continue;
+ out.push({ name: `${id}/${name}`, kind });
+ }
+ if (out.length) break;
+ }
+ return out;
+}
+
+/**
+ * The absolute path of one offered file -- a member of localMediaFor's own
+ * scan, never a path from the client.
+ */
+export async function resolveLocalMedia(
+ slug: string,
+ record: { id: string; webpageUrl?: string },
+ name: string,
+): Promise<{ abs: string; item: LocalMedia } | null> {
+ const offered = await localMediaFor(slug, record);
+ const item = offered.find((m) => m.name === name);
+ if (!item) return null;
+ const [id, ...rest] = item.name.split("/");
+ const dir = videoDir(slug, id);
+ if (!dir) return null;
+ return { abs: path.join(/* turbopackIgnore: true */ dir, ...rest), item };
+}
+
+const TYPES: Record<string, string> = {
+ ".mp4": "video/mp4",
+ ".m4v": "video/mp4",
+ ".mkv": "video/x-matroska",
+ ".webm": "video/webm",
+ ".mov": "video/quicktime",
+ ".mp3": "audio/mpeg",
+ ".m4a": "audio/mp4",
+ ".aac": "audio/aac",
+ ".opus": "audio/ogg",
+ ".ogg": "audio/ogg",
+ ".wav": "audio/wav",
+ ".flac": "audio/flac",
+};
+
+export const contentTypeOf = (name: string) => TYPES[path.extname(name).toLowerCase()] ?? "application/octet-stream";
diff --git a/umtool/lib/research/parity.test.ts b/umtool/lib/research/parity.test.ts
@@ -0,0 +1,154 @@
+// Research reads the corpus through the SAME engine as the MCP's tools, and
+// this holds it there: on the e2e fixture corpus (e2e/fixtures/research-
+// fixture.mjs, read as the MCP's --local reads a composed public dir), a
+// Research search finds exactly the recordings `enumerate_matches` lists --
+// the same total, the same ids, in the same order -- through
+// createCorpusTools, the in-process tools Claude Code and the generation jobs
+// call. Then the rest of lib/research over the same corpus: the scope preview,
+// the census, the reader's window and citation, the inventory's disk fallback.
+//
+// Run with: pnpm --filter umtool exec tsx --test lib/research/parity.test.ts
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+let tmp: string;
+let pub: string;
+// The modules read their env at import, so they are imported after it is set.
+let lib: {
+ corpus: typeof import("./corpus");
+ coverage: typeof import("./coverage");
+ createCorpusTools: typeof import("yt-dlp-transcript-mcp/callTool").createCorpusTools;
+ fixture: typeof import("../../e2e/fixtures/research-fixture.mjs");
+};
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-research-"));
+ const fixture = await import("../../e2e/fixtures/research-fixture.mjs");
+ pub = fixture.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") }).pub;
+ process.env.TRANSCRIPT_LOCAL_DIR = pub;
+ process.env.CHANNELS_DIR = path.join(tmp, "channels");
+ process.env.SITES_DIR = path.join(tmp, "sites");
+ process.env.REPORTS_DIR = path.join(tmp, "reports");
+ process.env.SETTINGS_FILE = path.join(tmp, "settings.json");
+ delete process.env.TRANSCRIPT_HUB_URL;
+ delete process.env.WORKER_TOKEN;
+ lib = {
+ corpus: await import("./corpus"),
+ coverage: await import("./coverage"),
+ createCorpusTools: (await import("yt-dlp-transcript-mcp/callTool")).createCorpusTools,
+ fixture,
+ };
+});
+
+after(async () => {
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const toolIds = (text: string) => [...text.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]);
+
+type Ask = { query: string; regex?: boolean; channels?: string[]; dateFrom?: string; dateTo?: string; states?: string[] };
+const ASKS: [string, Ask][] = [
+ ["the fixture phrase", { query: "lighthouse budget" }],
+ ["a regex", { query: "light\\w+ (budget|keeper)", regex: true }],
+ ["one channel", { query: "lighthouse budget", channels: ["night-desk"] }],
+ ["a date window", { query: "lighthouse budget", dateFrom: "2022-01-01", dateTo: "2024-12-31" }],
+ ["deleted only", { query: "lighthouse budget", states: ["deleted"] }],
+];
+for (const [label, ask] of ASKS) {
+ test(`parity with enumerate_matches through createCorpusTools: ${label}`, async () => {
+ const scope = { source: `local:${pub}`, ...ask };
+ const tools = await lib.createCorpusTools({ source: `local:${pub}` });
+ try {
+ const text = await tools.call("enumerate_matches", lib.corpus.toolArgs(scope, ask));
+ const res = await lib.corpus.runSearch({ ...scope, fresh: true });
+ const total = Number(/(\d+) match\(es\);/.exec(text)?.[1] ?? "0");
+ assert.equal(res.total, total, text);
+ assert.deepEqual(
+ res.hits.map((h) => h.videoId),
+ toolIds(text),
+ );
+ assert.equal(res.complete, !/COVERAGE PARTIAL/.test(text));
+ } finally {
+ await tools.close();
+ }
+ });
+}
+
+test("a search: 8 recordings, the mirror folded, facets, tracks, states, marks", async () => {
+ const res = await lib.corpus.runSearch({ source: "", query: lib.fixture.RESEARCH_PHRASE, fresh: true });
+ assert.equal(res.total, 8);
+ assert.equal(res.mirrorsFolded, 1);
+ assert.equal(res.complete, true);
+ assert.equal(res.batches, 1);
+ const audit = res.hits.find((h) => h.videoId === "hr-2024a")!;
+ assert.deepEqual(audit.mirrors, [{ videoId: "v1abcd", channelName: "Harbor Radio (Rumble)" }]);
+ assert.equal(audit.state, "deleted");
+ assert.equal(audit.track, "captions");
+ assert.equal(audit.duration, 7880);
+ assert.equal(res.hits.find((h) => h.videoId === "hr-2022a")!.track, "transcript");
+ assert.equal(res.hits.find((h) => h.videoId === "hr-2021a")!.matches, 2);
+ const snip = audit.snippets[0];
+ assert.equal(snip.t, 4972);
+ assert.deepEqual(
+ snip.marks.map(([a, b]) => snip.text.slice(a, b).toLowerCase()),
+ ["lighthouse budget"],
+ );
+ assert.ok(res.hits.find((h) => h.channelSlug === "candace-owens")!.localOnly);
+ assert.deepEqual(res.facets.years.map((y) => y.year), ["2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026"]);
+ assert.equal(res.facets.years.find((y) => y.year === "2020")!.n, 0);
+ assert.deepEqual(res.facets.tracks, { captions: 5, transcript: 3 });
+ assert.equal(res.facets.states.deleted, 1);
+ assert.equal(res.facets.states.unlisted, 1);
+ assert.deepEqual(res.log.marks, {});
+});
+
+test("the scope preview: before a search, no track census; after one, every channel counted", async () => {
+ const before = await lib.corpus.scopeOf({ source: "", channels: ["night-desk"] });
+ assert.equal(before.selected, 1);
+ assert.equal(before.videos, 3);
+ assert.equal(before.first, "20220615");
+ assert.equal(before.last, "20251201");
+ assert.equal(before.channels.length, 4);
+ assert.ok(before.channels.find((c) => c.slug === "candace-owens")!.localOnly);
+ // The earlier tests' full scans counted every channel already.
+ const all = await lib.corpus.scopeOf({ source: "" });
+ assert.equal(all.videos, 12);
+ assert.deepEqual(all.tracks, { transcript: 5, captions: 7, unknown: 0, counted: 4, of: 4 });
+ const filtered = await lib.corpus.scopeOf({ source: "", dateFrom: "2025-01-01" });
+ assert.equal(filtered.videos, 4);
+ await assert.rejects(lib.corpus.scopeOf({ source: "local:/etc" }), /not an offered source/);
+});
+
+test("the reader's window: the hit lit, ± span, the citation in the house format", async () => {
+ const w = await lib.corpus.windowOf({ source: "", channel: "harbor-radio", video: "hr-2024a", t: 4972, span: 12 });
+ assert.equal(w.cues[w.lit].t, 4972);
+ assert.match(w.cues[w.lit].text, /lighthouse budget/);
+ assert.ok(w.cues.every((c) => c.t >= 4960 && c.t <= 4984));
+ assert.equal(w.duration, 7880);
+ assert.equal(w.state, "deleted");
+ assert.equal(w.citation.url, "https://archive.example/?v=harbor-radio%2Fhr-2024a&t=4972");
+ assert.equal(
+ w.citation.text,
+ '"How much was the lighthouse budget? You cut it all," [Harbor Radio 140: the audit @ 1:22:52](https://archive.example/?v=harbor-radio%2Fhr-2024a&t=4972)',
+ );
+ assert.deepEqual(w.media, []);
+ await assert.rejects(lib.corpus.windowOf({ source: "", channel: "harbor-radio", video: "nope", t: 1, span: 10 }), /no recording/);
+});
+
+test("the inventory: no WORKER_TOKEN, so the local corpus is read on disk, and the answer says why", async () => {
+ const c = await lib.coverage.coverageOf({ source: "" });
+ assert.equal(c.held.via, "disk");
+ assert.match(c.held.note ?? "", /WORKER_TOKEN is not set/);
+ assert.deepEqual(c.years, ["2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026"]);
+ const hr = c.rows.find((r) => r.slug === "harbor-radio")!;
+ assert.equal(hr.published.total, 6);
+ assert.equal(hr.held?.total, 5);
+ assert.equal(hr.held?.byYear["2022"], 1);
+ assert.ok(hr.held!.gapYears.includes("2020"), "2019 → 2021 is a gap over 60 days");
+ assert.equal(hr.published.byState.deleted, 1);
+ assert.deepEqual(hr.tracks?.["2022"], { transcript: 1, captions: 1, unknown: 0 });
+ assert.equal(c.rows.find((r) => r.slug === "harbor-radio-rumble")!.held, null);
+});
diff --git a/umtool/lib/research/query.mjs b/umtool/lib/research/query.mjs
@@ -0,0 +1,97 @@
+// What the Research ask bar accepts, and what it hands the engine
+// (plans/umtool-redesign.md, "Research, first-class" 1).
+//
+// how many employees a phrase: the engine's plain search is already a
+// case-insensitive substring, so the words match
+// together, in order
+// "how many employees" the same; the quotes are dropped
+// /fir(ed|ing) them/ a regex (case-insensitive), as enumerate_matches'
+// `regex: true`; aliases do not apply to a regex
+// fired near:4 employees the two terms within 4 words of each other, either
+// order, INSIDE ONE CAPTION LINE -- compiled to a
+// regex, because the engine matches cue by cue
+//
+// Pure, so a unit test, the server and the page agree on what a query means.
+
+const RE_SPECIALS = /[.*+?^${}()|[\]\\]/g;
+export const escapeRegex = (s) => s.replace(RE_SPECIALS, "\\$&");
+
+/**
+ * @param {string} raw
+ * @returns {{ query: string, regex: boolean, kind: "phrase"|"regex"|"near", near?: { a: string, b: string, n: number }, error?: string }}
+ */
+export function parseAsk(raw) {
+ const text = String(raw ?? "").trim();
+ if (!text) return { query: "", regex: false, kind: "phrase", error: "Type what to find" };
+
+ const re = /^\/(.+)\/[a-z]*$/s.exec(text);
+ if (re) {
+ try {
+ new RegExp(re[1], "i");
+ } catch (e) {
+ return { query: re[1], regex: true, kind: "regex", error: `Not a regex: ${e.message}` };
+ }
+ return { query: re[1], regex: true, kind: "regex" };
+ }
+
+ const near = /^(.+?)\s+near:(\d{1,2})\s+(.+)$/i.exec(text);
+ if (near) {
+ const a = unquote(near[1]);
+ const b = unquote(near[3]);
+ const n = Number(near[2]);
+ if (!a || !b || n < 1) return { query: text, regex: false, kind: "near", error: "near:N takes a term on each side and N ≥ 1" };
+ return { query: nearRegex(a, b, n), regex: true, kind: "near", near: { a, b, n } };
+ }
+
+ return { query: unquote(text), regex: false, kind: "phrase" };
+}
+
+function unquote(s) {
+ const t = s.trim();
+ const m = /^"(.*)"$/s.exec(t);
+ return (m ? m[1] : t).trim();
+}
+
+/** `a` and `b` within `n` words of each other, either order. */
+export function nearRegex(a, b, n) {
+ const gap = `\\W+(?:\\w+\\W+){0,${Math.max(0, n - 1)}}`;
+ const A = escapeRegex(a);
+ const B = escapeRegex(b);
+ return `${A}${gap}${B}|${B}${gap}${A}`;
+}
+
+/**
+ * Where a query matched in a snippet, as [start, end) ranges, merged. The
+ * engine says THAT a cue matched (a boolean); this finds WHERE, the same way:
+ * a plain query as a case-insensitive substring, a regex as one, plus every
+ * alias the engine fired (`{ pattern, regex }`).
+ *
+ * @param {string} text
+ * @param {{ query: string, regex: boolean, aliases?: { pattern: string, regex: boolean }[] }} q
+ * @returns {[number, number][]}
+ */
+export function markRanges(text, q) {
+ const out = [];
+ const patterns = [{ pattern: q.query, regex: q.regex }, ...(q.aliases ?? [])];
+ for (const p of patterns) {
+ if (!p.pattern) continue;
+ let re;
+ try {
+ re = new RegExp(p.regex ? p.pattern : escapeRegex(p.pattern), "gi");
+ } catch {
+ continue;
+ }
+ for (const m of text.matchAll(re)) {
+ if (m[0].length === 0) continue;
+ out.push([m.index, m.index + m[0].length]);
+ }
+ }
+ out.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
+ const merged = [];
+ for (const r of out) {
+ const last = merged[merged.length - 1];
+ if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
+ else merged.push([r[0], r[1]]);
+ }
+ return merged;
+}
diff --git a/umtool/lib/research/query.test.mjs b/umtool/lib/research/query.test.mjs
@@ -0,0 +1,38 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { markRanges, nearRegex, parseAsk } from "./query.mjs";
+
+test("a phrase is the engine's plain query; quotes are dropped", () => {
+ assert.deepEqual(parseAsk(" how many employees "), { query: "how many employees", regex: false, kind: "phrase" });
+ assert.deepEqual(parseAsk('"how many employees"'), { query: "how many employees", regex: false, kind: "phrase" });
+ assert.equal(parseAsk("").error, "Type what to find");
+});
+
+test("/…/ is a regex, and a bad one says what is wrong", () => {
+ assert.deepEqual(parseAsk("/fir(ed|ing) them/"), { query: "fir(ed|ing) them", regex: true, kind: "regex" });
+ assert.match(parseAsk("/fir(ed/").error, /^Not a regex/);
+});
+
+test("near:N compiles to a regex over one caption line, either order", () => {
+ const p = parseAsk("fired near:3 employees");
+ assert.equal(p.kind, "near");
+ assert.equal(p.regex, true);
+ assert.deepEqual(p.near, { a: "fired", b: "employees", n: 3 });
+ const re = new RegExp(p.query, "i");
+ assert.ok(re.test("you fired all the employees"));
+ assert.ok(re.test("employees? you fired them"));
+ assert.ok(!re.test("fired one two three four employees"));
+ assert.equal(nearRegex("a.b", "c", 1), "a\\.b\\W+(?:\\w+\\W+){0,0}c|c\\W+(?:\\w+\\W+){0,0}a\\.b");
+});
+
+test("markRanges finds the query, case-insensitive, and the fired aliases, merged", () => {
+ assert.deepEqual(markRanges("How many employees? how MANY", { query: "how many", regex: false }), [
+ [0, 8],
+ [20, 28],
+ ]);
+ assert.deepEqual(markRanges("k cups and cake cups", { query: "k cups", regex: false, aliases: [{ pattern: "(k|cake)[ -]?cups", regex: true }] }), [
+ [0, 6],
+ [11, 20],
+ ]);
+ assert.deepEqual(markRanges("anything", { query: "(", regex: true }), []);
+});
diff --git a/umtool/lib/research/rules.mjs b/umtool/lib/research/rules.mjs
@@ -0,0 +1,14 @@
+// Research rules that are DATA (plans/umtool-redesign.md, "Constraints on every
+// phase", Research rules), so the page, the routes and a later export (R2's
+// board) read one list.
+//
+// Candace channels are LOCAL-ONLY: read through the local corpus, they may
+// appear in Research, but never in anything exported or published. Research
+// exports nothing in R1; every hit from one is marked so, and an exporter
+// must refuse it (isLocalOnly).
+export const LOCAL_ONLY_CHANNELS = Object.freeze(["candace-owens", "realcandaceo"]);
+
+/** @param {string | null | undefined} slug */
+export function isLocalOnly(slug) {
+ return typeof slug === "string" && LOCAL_ONLY_CHANNELS.includes(slug.trim().toLowerCase());
+}
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -0,0 +1,154 @@
+import { readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
+import { REPO_ROOT, SITES_DIR } from "../paths.mjs";
+import type { SourceOption } from "./types";
+
+// ---------------------------------------------------------------------------
+// THE SOURCE PICKER (plans/umtool-redesign.md, "Research, first-class" 1):
+// which corpus the ask bar reads.
+//
+// local the composed public dir on this machine, resolved as the MCP
+// server's default resolves it: TRANSCRIPT_LOCAL_DIR, else
+// EXPORT_PUBLIC_DIR, else <repo>/export/public
+// remote a published site: every transcripts/sites/*/site.json with a
+// `siteUrl` (a private site has none, and is not offered)
+// hub TRANSCRIPT_HUB_URL, else settings.json `homepageUrl`
+//
+// Only an OFFERED handle opens: a request naming any other directory or origin
+// is refused, so the routes can never be pointed at an arbitrary path.
+//
+// The live source for a handle is the MCP's own (SourceRegistry), cached per
+// handle on globalThis (one copy for every route bundle, as lib/projects.ts
+// learned in P2a). A local one is reopened when its corpus.json changes -- a
+// site build recomposes export/public -- and a remote or a hub after
+// REMOTE_TTL_MS, since the sources cache their channel lists for life.
+// ---------------------------------------------------------------------------
+
+const REMOTE_TTL_MS = 15 * 60_000;
+
+export function localDir(): string {
+ const env = process.env.TRANSCRIPT_LOCAL_DIR?.trim() || process.env.EXPORT_PUBLIC_DIR?.trim();
+ return env
+ ? path.resolve(/* turbopackIgnore: true */ env)
+ : path.join(/* turbopackIgnore: true */ REPO_ROOT, "export", "public");
+}
+
+function hubUrl(settings: { homepageUrl?: unknown } | null): string | null {
+ const env = process.env.TRANSCRIPT_HUB_URL?.trim();
+ if (env) return env.replace(/\/+$/, "");
+ const h = settings?.homepageUrl;
+ return typeof h === "string" && /^https?:\/\//.test(h.trim()) ? h.trim().replace(/\/+$/, "") : null;
+}
+
+async function readJson<T>(file: string): Promise<T | null> {
+ try {
+ return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")) as T;
+ } catch {
+ return null;
+ }
+}
+
+/** Every corpus the ask bar may read, the local one first. */
+export async function listSources(): Promise<SourceOption[]> {
+ const dir = localDir();
+ const corpus = await readJson<{ site?: { title?: string } }>(path.join(/* turbopackIgnore: true */ dir, "corpus.json"));
+ const out: SourceOption[] = [
+ {
+ handle: `local:${dir}`,
+ kind: "local",
+ label: "Local corpus",
+ detail: corpus?.site?.title ? `this machine · ${corpus.site.title} build` : "this machine",
+ },
+ ];
+ const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
+ const sites: SourceOption[] = [];
+ for (const id of ids.sort()) {
+ if (id.startsWith("_") || id.startsWith(".")) continue;
+ const site = await readJson<{ siteUrl?: unknown; title?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json"));
+ const url = typeof site?.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : "";
+ if (!/^https?:\/\//.test(url)) continue;
+ sites.push({
+ handle: `remote:${url}`,
+ kind: "remote",
+ label: typeof site?.title === "string" && site.title ? site.title : id,
+ detail: `published · ${url.replace(/^https?:\/\//, "")}`,
+ });
+ }
+ out.push(...sites);
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+ const hub = hubUrl(await readJson<{ homepageUrl?: unknown }>(settingsFile));
+ if (hub) out.push({ handle: `hub:${hub}`, kind: "hub", label: "Hub", detail: `every listed site · ${hub.replace(/^https?:\/\//, "")}` });
+ return out;
+}
+
+function specOf(handle: string): SourceSpec {
+ const m = /^(local|remote|hub):(.+)$/s.exec(handle);
+ if (!m) throw new SourceError(`not a source: ${handle}`);
+ if (m[1] === "local") return { kind: "local", dir: m[2] };
+ if (m[1] === "remote") return { kind: "remote", url: m[2] };
+ return { kind: "hub", url: m[2] };
+}
+
+export class SourceError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+/** Transcripts vs captions per channel, counted by a search that read it whole. */
+export type ChannelCensus = {
+ total: number;
+ transcript: number;
+ captions: number;
+ unknown: number;
+ byYear: Record<string, { transcript: number; captions: number; unknown: number }>;
+};
+
+export type Opened = {
+ option: SourceOption;
+ source: ShardSource;
+ /** By channel key; only channels a full scan has counted. */
+ census: Map<string, ChannelCensus>;
+};
+
+type Entry = { opened: Opened; stamp: string; at: number };
+const g = globalThis as { __umtoolResearchSources?: Map<string, Entry> };
+const cache = (g.__umtoolResearchSources ??= new Map());
+
+async function stampOf(option: SourceOption): Promise<string> {
+ if (option.kind !== "local") return "";
+ const dir = option.handle.slice("local:".length);
+ const st = await stat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "corpus.json")).catch(() => null);
+ return st ? `${st.mtimeMs}:${st.size}` : "none";
+}
+
+/**
+ * The live source for an offered handle (the local one when none is named).
+ * A handle that is not offered is a 400.
+ */
+export async function openSource(handle: string | null | undefined): Promise<Opened> {
+ const options = await listSources();
+ const want = handle?.trim() || options[0].handle;
+ const option = options.find((o) => o.handle === want);
+ if (!option) throw new SourceError(`not an offered source: ${want} — choose the local corpus, a published site or the hub`);
+ const stamp = await stampOf(option);
+ const hit = cache.get(option.handle);
+ if (hit && hit.stamp === stamp && (option.kind === "local" || Date.now() - hit.at < REMOTE_TTL_MS)) {
+ hit.opened.option = option;
+ return hit.opened;
+ }
+ const registry = new SourceRegistry(specOf(option.handle));
+ let source: ShardSource;
+ try {
+ source = (await registry.resolve(undefined)).source;
+ } catch (e) {
+ throw new SourceError(`${option.label} cannot be read: ${(e as Error).message}`, 502);
+ }
+ const opened: Opened = { option, source, census: new Map() };
+ cache.set(option.handle, { opened, stamp, at: Date.now() });
+ return opened;
+}
diff --git a/umtool/lib/research/types.ts b/umtool/lib/research/types.ts
@@ -0,0 +1,212 @@
+// The Research API's shapes (app/api/research/*), shared by the routes and the
+// page. Types only: safe for a client component.
+
+export type SourceKind = "local" | "remote" | "hub";
+
+/** A corpus the ask bar can read: the local corpus, a published site, the hub. */
+export type SourceOption = {
+ /** The MCP's own handle form: `local:<dir>`, `remote:<url>`, `hub:<url>`. */
+ handle: string;
+ kind: SourceKind;
+ label: string;
+ /** "published", "this machine", the site's url. */
+ detail?: string;
+};
+
+/** What a search or a preview is scoped to (the scope chips). */
+export type Scope = {
+ source: string;
+ /** Channel keys (a hub's are `<site>:<slug>`); none = every channel. */
+ channels?: string[];
+ /** YYYY-MM-DD, inclusive. */
+ dateFrom?: string;
+ dateTo?: string;
+ /** VideoState values kept; none = all. */
+ states?: string[];
+ mediaType?: "video" | "livestream";
+ /** Search the posts corpus too. */
+ posts?: boolean;
+};
+
+export type ChannelChoice = {
+ key: string;
+ slug: string;
+ name: string;
+ videoCount?: number;
+ site?: string;
+ /** Candace's: may show here, never in anything exported (lib/research/rules.mjs). */
+ localOnly?: boolean;
+};
+
+/** Transcripts vs captions, as far as a full scan has counted them. */
+export type TrackCensus = {
+ transcript: number;
+ captions: number;
+ unknown: number;
+ /** Channels of the scope counted / in the scope. */
+ counted: number;
+ of: number;
+};
+
+/** GET /api/research/scope: what the scope holds, before anything runs. */
+export type ScopeSummary = {
+ source: SourceOption;
+ channels: ChannelChoice[];
+ /** Channels the scope selects. */
+ selected: number;
+ /** Videos in the scope (summaries index; the channels' counts without one). */
+ videos: number;
+ /** Upload dates, YYYYMMDD, when the source ships a summaries index. */
+ first: string | null;
+ last: string | null;
+ /** Counted only when a search has read the scope's channels whole. */
+ tracks: TrackCensus | null;
+ /** Curated aliases the source ships (a plain query expands through them). */
+ aliases: number;
+ /** Tokens that matched nothing, and other things the filters said. */
+ warnings: string[];
+};
+
+export type Snip = {
+ t: number;
+ clock: string;
+ text: string;
+ /** [start, end) of each match in `text`. */
+ marks: [number, number][];
+ /** An alternate caption track's hit (common/lib/captionTracks.ts). */
+ track?: string;
+ /** A non-timed layer (description, tags): no timecode to cite. */
+ scope?: string;
+};
+
+export type ResultHit = {
+ /** `<channelSlug>/<id>`: the reading log's key. */
+ key: string;
+ kind: "video" | "post";
+ videoId: string;
+ channelSlug: string;
+ channelKey: string;
+ channelName: string;
+ site?: string;
+ title: string;
+ uploadDate: string;
+ /** transcript | captions | unknown, or post. */
+ track: string;
+ /** VideoState from the summaries ("available" when the source says nothing). */
+ state: string;
+ duration?: number;
+ matches: number;
+ snippets: Snip[];
+ mirrors?: { videoId: string; channelName: string }[];
+ author?: string;
+ localOnly?: boolean;
+};
+
+export type Facets = {
+ years: { year: string; n: number }[];
+ channels: { slug: string; name: string; n: number }[];
+ tracks: Record<string, number>;
+ states: Record<string, number>;
+};
+
+export type LogMarks = Record<string, { state: "read" | "skipped"; at: string }>;
+
+/** POST /api/research/search: the whole match set, once. */
+export type SearchResponse = {
+ session: string;
+ query: string;
+ regex: boolean;
+ source: SourceOption;
+ /** Recordings (mirrors folded): enumerate_matches' total. */
+ total: number;
+ /** Matching lines across them. */
+ matches: number;
+ complete: boolean;
+ /** When capped: the channels never reached, and where it stopped. */
+ notReached: string[];
+ stopped?: { channel: string; page: number; pages: number };
+ scanned: { pages: number; channels: number };
+ mirrorsFolded: number;
+ batches: number;
+ aliases: string[];
+ warnings: string[];
+ hits: ResultHit[];
+ facets: Facets;
+ log: { marks: LogMarks; error?: string };
+ tookMs: number;
+};
+
+export type WindowCue = { t: number; end: number; text: string };
+
+/** GET /api/research/window: the transcript around a cue, for the reader. */
+export type WindowResponse = {
+ kind: "video" | "post";
+ title: string;
+ channelSlug: string;
+ channelName: string;
+ videoId: string;
+ uploadDate: string;
+ duration: number;
+ state: string;
+ /** transcript | captions | unknown. */
+ track: string;
+ /** The alternate track read, by its label, when not the primary. */
+ trackLabel?: string;
+ cueCount: number;
+ at: number;
+ span: number;
+ cues: WindowCue[];
+ /** Index into `cues` of the cited cue. */
+ lit: number;
+ citation: { text: string; url: string | null };
+ /** Files umtool can play from this machine, best first. */
+ media: LocalMedia[];
+ /** A post's text, when kind is post. */
+ text?: string;
+ author?: string;
+ localOnly?: boolean;
+};
+
+export type LocalMedia = {
+ name: string;
+ kind: "window" | "source" | "audio";
+ /** A clip window's span, source seconds. */
+ from?: number;
+ to?: number;
+};
+
+/** POST /api/research/fetch: the editor's answer, as fetch_clip reads it. */
+export type FetchAnswer =
+ | { state: "ready"; file: string; from?: number; to?: number; cached: boolean }
+ | { state: "queued"; job: string; status: string }
+ | { state: "failed"; message: string; job?: string };
+
+export type CoverageRow = {
+ key: string;
+ slug: string;
+ name: string;
+ localOnly?: boolean;
+ /** Published: the source's summaries, by upload year. */
+ published: { total: number; byYear: Record<string, number>; byState: Record<string, number> };
+ /** Held on disk (channel_coverage), by coverage date; null when not known. */
+ held: {
+ total: number;
+ byYear: Record<string, number>;
+ gaps: { after: string; before: string; days: number }[];
+ gapYears: string[];
+ first: string | null;
+ last: string | null;
+ } | null;
+ /** Transcripts vs captions per year, when a search counted the channel whole. */
+ tracks: Record<string, { transcript: number; captions: number; unknown: number }> | null;
+};
+
+/** GET /api/research/coverage: channels × years. */
+export type CoverageResponse = {
+ source: SourceOption;
+ years: string[];
+ rows: CoverageRow[];
+ /** Where `held` came from, and why not the editor when it did not. */
+ held: { via: "editor" | "disk" | "none"; note?: string };
+ gapDays: number;
+};
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,6 +8,7 @@
"build": "next build",
"start": "next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
+ "test": "tsx --test lib/research/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {