commit e7ca446fac8be4e9e5d20ee8a3c72f2145599c93
parent ca6abc9971ce682f9c0ffcf0c2b28eee42bba5ec
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 04:01:52 -0400
Merge branch 'ux/integration' into ux/p3
# Conflicts:
# package.json
# plans/umtool-redesign.md
Diffstat:
54 files changed, 5107 insertions(+), 225 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,10 @@
# Changelog
## [Unreleased]
+- **umtool has a Research page, `/research`.** Ask the corpus (a phrase, a `/regex/`, or `a near:8 b`) in the local corpus, a published site or the hub; the scope chips (channels, dates, state on the platform, videos or streams, posts) say what the scope **holds** before anything runs: channels, videos, the years, and transcripts vs captions once a search has counted them. A search reads the whole scope once, with the MCP's own `enumerate_matches` engine (the same total and the same recordings), and says **full coverage** or **Partial — not reached:** the channels a cap left unread, with the mirrors it folded. Results are lit lines grouped by recording, the match marked, with year, channel, text, state and reading facets that narrow what is shown. The reader on the right shows the transcript around the lit hit with its cue lit, **−**/**+** to narrow or widen it, **Copy citation** in the house format, **Play from** a clip or source this machine holds, and **Fetch clip** through the editor's fetch-window route, as `fetch_clip` asks. Keys: `j`/`k` lines, `r` read, `s` skip, `u` unread, `c` copy citation, `/` the ask bar. Needs a restart of umtool.
+- **Research keeps a reading log.** Every hit is read, skipped or unread, and the header says **read 37 of 97**. The log is umtool's, under `REPORTS_ROOT/.umtool/research/sessions/`, one per query and scope, never in the corpus.
+- **umtool's archive inventory, `/research/archive`.** Channels × years: the videos the editor holds (its `GET /api/ops/coverage`, the MCP's `channel_coverage`) or the videos the source publishes, on the Meter ramp, gaps over 60 days marked, nothing held as —. Hover or focus a cell for what it holds, published, deleted or unlisted, and transcripts vs captions; the arrow keys walk the grid; **Table** lists the same numbers. When umtool has no `WORKER_TOKEN` or the editor does not answer, the page says which, and for the local corpus reads the held counts on disk instead.
+- **The MCP's enumerate is shared as data.** `enumerate_matches` renders `mcp/src/enumerate.ts`, which umtool calls through the new `yt-dlp-transcript-mcp/research` export; `fetch_clip`'s cite-to-directory mapping is `clipTarget.ts`, and a caller can name itself to the editor (`requestedBy`). Nothing an agent sees changed.
- **umtool drafts each section of a report video with a model you pick.** A video project made from an article's iteration has a **draft** section: for the cut, the on-screen titles, the teaser, the flips, the threads, the narration and the YouTube text, **Draft with** and a model (the generation policy's models, the task's route chosen first), **force** (re-drafts only what a model drafted; what you wrote or edited is never replaced), and for a per-entry task the entries to draft. The job's progress shows while it runs; when it ends the page shows what it wrote, skipped and had refused by a check, the **drafted by** badge with **Approve** and **Reject**, and any draft kept aside with **Use this**. A project not made from an iteration says so and offers none. The article's Iterations tab gains the same drafts beside **Narrate**. Needs a restart of umtool.
- **Draft everything.** One button on the Iterations tab (or `umtool chain <article> <n> --draft-all [--model M]`) runs the chain with every media draft in it, on the model you choose: the cut, on-screen, teaser, flips, threads and narration after the manifest, then the voices, a fast build and the podcast, then the YouTube text, whose chapters are re-muxed so `out/youtube.txt` is written. A draft the editor refuses or that fails is marked failed and the chain carries on; one with nothing to draft, or flips and threads with no on-screen deck (or with the other panel on), is skipped. It does not attach the video to the article: review the drafts first. Started again, it resumes after the last draft that ran. Needs a restart of umtool.
- **A site's Delete shows its plan before anything goes.** On `/sites`, **Delete** lists what would be removed (the site, its publish state and last bundle, its staging), how much, what is kept and what refuses; **Confirm delete** removes it. A site with a deploy target, a recorded deploy or reports of its own is refused unless you tick the box and press **Delete with force**; a site whose directory is a link, or a publish stage running, is refused outright. The delete is `pnpm ops delete-site`'s, so it now removes the build state too.
diff --git a/mcp/package.json b/mcp/package.json
@@ -5,7 +5,8 @@
"type": "module",
"exports": {
"./package.json": "./package.json",
- "./callTool": "./src/callTool.ts"
+ "./callTool": "./src/callTool.ts",
+ "./research": "./src/research.ts"
},
"description": "MCP server exposing a yt-dlp transcript archive (or a federated hub) to Claude Code and other MCP clients \u2014 reads the site's static JSON shards.",
"bin": {
diff --git a/mcp/src/clipTarget.ts b/mcp/src/clipTarget.ts
@@ -0,0 +1,34 @@
+// A cited moment mapped to the editor's directory (fetch_clip's first step),
+// shared by the tool and umtool's Research page so both ask the editor for the
+// same thing.
+//
+// Rumble: the cited id is the EMBED id (the record's `id`); the editor's
+// directory is the URL slug, read off the record's webpageUrl. The channel is
+// the one the record lives in, which is the editor's directory even when the
+// citation spelled it by name or in another case. A video the source does not
+// hold is passed as cited, with a note saying so.
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { isVideoId, notFoundNote, type FetchClipRequest } from "./fetchClip";
+import { findVideo } from "./search";
+import type { ShardSource } from "./source";
+
+export async function resolveClipTarget(
+ source: ShardSource,
+ handle: string,
+ request: FetchClipRequest,
+): Promise<{ note: string; ctx: { channel?: string; video?: string } }> {
+ if (!("target" in request)) return { note: "", ctx: {} };
+ const target = request.target;
+ let note = "";
+ const found = await findVideo(source, target.video, target.channel);
+ if (found) {
+ const webpageUrl = found.record.webpageUrl;
+ const mapped = webpageUrl ? extractVideoId(webpageUrl) : null;
+ target.video = mapped && isVideoId(mapped) ? mapped : target.video;
+ target.channel = found.ch.slug;
+ if (target.kind === "window" && webpageUrl) target.webpageUrl = webpageUrl;
+ } else {
+ note = `${notFoundNote(target.video, handle)}\n\n`;
+ }
+ return { note, ctx: { channel: target.channel, video: target.video } };
+}
diff --git a/mcp/src/enumerate.test.ts b/mcp/src/enumerate.test.ts
@@ -0,0 +1,125 @@
+// enumerate(): the scan behind enumerate_matches, as data. The tool and a
+// caller of enumerate() cover exactly the same set, because the tool renders
+// enumerate()'s result -- these pin that, and the two options a structured
+// caller adds (snippets, onRecord) change nothing about which recordings match.
+
+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";
+import { CHANNELS, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { createCorpusTools, type CorpusTools } from "./callTool";
+import { enumerate, type Enumerated } from "./enumerate";
+import { resolveClipTarget } from "./clipTarget";
+import { fetchClip, validateFetchClipArgs, type FetchClipDeps } from "./fetchClip";
+import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { LocalSource } from "./source";
+
+let dir: string;
+let corpus: CorpusTools;
+
+before(async () => {
+ dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "mcp-enumerate-")));
+ corpus = await createCorpusTools({ source: `local:${dir}` });
+});
+
+after(async () => {
+ await corpus.close();
+ await rm(dir, { recursive: true, force: true });
+});
+
+// The ids a worklist row names: `- <id> | video | …`.
+const toolIds = (text: string) => [...text.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]);
+const ok = (e: Enumerated | { error: string }): Enumerated => {
+ if ("error" in e) throw new Error(e.error);
+ return e;
+};
+
+for (const args of [
+ { query: "the" },
+ { query: "sourdough" },
+ { query: "contest", channels: ["synth-kitchen"] },
+ { query: "o.en", regex: true },
+ { query: "the", date_from: "2026-02-01" },
+ { query: "the", exclude: ["oven"] },
+]) {
+ test(`enumerate() and the tool cover the same set: ${JSON.stringify(args)}`, async () => {
+ const text = await corpus.call("enumerate_matches", args);
+ const e = ok(await enumerate(new LocalSource(dir), args, { includeSnippets: true, snippetsPerVideo: 12 }));
+ const total = Number(/(\d+) match\(es\);/.exec(text)?.[1] ?? "0");
+ assert.equal(e.result.total, total);
+ assert.deepEqual(
+ e.result.hits.map((h) => h.videoId),
+ toolIds(text),
+ );
+ assert.equal(e.result.truncated, /COVERAGE PARTIAL/.test(text));
+ });
+}
+
+test("snippets are the caller's choice and never change the set", async () => {
+ const src = new LocalSource(dir);
+ const bare = ok(await enumerate(src, { query: "the" }));
+ const rich = ok(await enumerate(src, { query: "the" }, { includeSnippets: true, snippetsPerVideo: 2 }));
+ assert.deepEqual(rich.result.hits.map((h) => h.videoId), bare.result.hits.map((h) => h.videoId));
+ assert.ok(bare.result.hits.every((h) => h.snippets.length === 0));
+ assert.ok(rich.result.hits.every((h) => h.snippets.length > 0 && h.snippets.length <= 2));
+ // matches still counts every hit, past the snippets kept.
+ const qa = rich.result.hits.find((h) => h.videoId === "qa-long-03")!;
+ assert.ok(qa.matches > qa.snippets.length);
+});
+
+test("onRecord sees every record the scan reads, before any filter or match", async () => {
+ const seen: string[] = [];
+ const e = ok(
+ await enumerate(new LocalSource(dir), { query: "contest", date_from: "2026-02-01" }, {
+ onRecord: (rec, ch) => seen.push(`${ch.slug}/${rec.id}`),
+ }),
+ );
+ const all = CHANNELS.flatMap((c: { slug: string; records: { id: string }[] }) => c.records.map((r) => `${c.slug}/${r.id}`));
+ assert.deepEqual([...seen].sort(), [...all].sort());
+ assert.deepEqual(e.result.hits.map((h) => h.videoId), ["pie-stream-02"]);
+});
+
+test("a bad argument is the tool's error, and nothing is searched", async () => {
+ assert.deepEqual(await enumerate(new LocalSource(dir), { query: " " }), { error: "query is required" });
+ const bad = await enumerate(new LocalSource(dir), { query: "x", date_from: "yesterday" });
+ assert.ok("error" in bad && /not a date/.test(bad.error));
+});
+
+test("resolveClipTarget: the record's channel and its URL's id, as fetch_clip sends them", async () => {
+ const v = validateFetchClipArgs({ channel: "Synth Kitchen", video: "bread-day-01", start: 15, end: 20, reason: "r" });
+ assert.ok(v.ok);
+ const { note, ctx } = await resolveClipTarget(new LocalSource(dir), `local:${dir}`, v.request);
+ assert.equal(note, "");
+ // The channel the record lives in, and the id the editor names its directory
+ // with: extractVideoId of the record's URL (on Rumble, not the embed id).
+ const url = "https://video.example/watch?v=bread-day-01";
+ const dirId = extractVideoId(url);
+ assert.deepEqual(ctx, { channel: "synth-kitchen", video: dirId && /^[\w.-]+$/.test(dirId) ? dirId : "bread-day-01" });
+ assert.ok("target" in v.request && v.request.target.kind === "window");
+ assert.equal((v.request.target as { webpageUrl?: string }).webpageUrl, "https://video.example/watch?v=bread-day-01");
+
+ const gone = validateFetchClipArgs({ channel: "synth-kitchen", video: "nope-99", start: 1, end: 2, reason: "r" });
+ assert.ok(gone.ok);
+ const r = await resolveClipTarget(new LocalSource(dir), `local:${dir}`, gone.request);
+ assert.match(r.note, /nope-99/);
+});
+
+test("fetchClip says who asked: mcp by default, the caller's name when given", async () => {
+ const bodies: unknown[] = [];
+ const deps: FetchClipDeps = {
+ env: { WORKER_TOKEN: "tok", ARCHILYZER_EDITOR_URL: "http://editor.test" },
+ fetch: async (_url, init) => {
+ bodies.push(JSON.parse(init?.body ?? "{}"));
+ return { status: 200, json: async () => ({ file: "/x/clips/1.00-2.00.mp4", from: 1, to: 2, bytes: 1 }) };
+ },
+ sleep: async () => {},
+ now: () => 0,
+ };
+ const v = validateFetchClipArgs({ channel: "c", video: "v", start: 5, end: 6, reason: "r" });
+ assert.ok(v.ok);
+ await fetchClip(v.request, deps);
+ await fetchClip(v.request, deps, { requestedBy: "umtool" });
+ assert.deepEqual(bodies.map((b) => (b as { requestedBy: string }).requestedBy), ["mcp", "umtool"]);
+});
diff --git a/mcp/src/enumerate.ts b/mcp/src/enumerate.ts
@@ -0,0 +1,247 @@
+// THE ENUMERATE, AS DATA (umtool redesign R1): the one scan behind
+// `enumerate_matches`, callable in process.
+//
+// `enumerate_matches` renders its result as text for an agent. umtool's
+// Research page needs the same scan as structured data -- the ids, the
+// timecodes, the coverage -- and must not parse the text to get it. So the
+// scan lives here, and the tool is a renderer over it: the scoping, the
+// filters, the exclusions, the alias expansion, the mirror collapsing and the
+// caps (MCP_POLICY) are one code path for both by construction.
+//
+// The argument parsing for both search tools moved here from server.ts
+// unchanged (`parseSearchArgs`, `strArray`): it is the half of the contract a
+// caller passing the tool's own arguments needs.
+import { normalizeDateArg } from "./dateArg";
+import { isTagId } from "yt-dlp-transcript-common/lib/curatedTags";
+import {
+ VIDEO_STATES,
+ isVideoState,
+ type VideoState,
+} from "yt-dlp-transcript-common/lib/availability";
+import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
+import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts";
+import type { ChannelRef, ShardSource } from "./source";
+import {
+ parseContentTypes,
+ searchTranscripts,
+ type SearchFilters,
+ type SearchResult,
+} from "./search";
+
+// The parsed form of SEARCH_FILTER_ARGS, plus any tokens that were not
+// understood. Unknown tokens are REPORTED rather than dropped silently: a
+// typo'd state ("removed" for "deleted") would otherwise widen the search back
+// to the whole corpus and look like a legitimate empty result.
+export type ParsedSearchArgs = {
+ filters: SearchFilters | null;
+ exclude?: string[];
+ scopes?: LayerScope[];
+ collapseDuplicates: boolean;
+ warnings: string[];
+ // Set when an argument must stop the call rather than be dropped (a date
+ // bound that is not a date). Callers return it as an error and search nothing.
+ error?: string;
+};
+
+export const SCOPE_TOKENS: ReadonlyArray<LayerScope> = [
+ "transcripts",
+ "chat",
+ "description",
+ "tags",
+ "metadata",
+ "posts",
+];
+
+export function parseSearchArgs(args: Record<string, unknown>): ParsedSearchArgs {
+ const warnings: string[] = [];
+
+ const rawStates = strArray(args.states);
+ let states: VideoState[] | undefined;
+ if (rawStates) {
+ states = rawStates.filter((s): s is VideoState => isVideoState(s));
+ const bad = rawStates.filter((s) => !isVideoState(s));
+ if (bad.length > 0) {
+ warnings.push(
+ `unknown state(s) ignored: ${bad.join(", ")} (valid: ${VIDEO_STATES.join(", ")})`,
+ );
+ }
+ if (states.length === 0) {
+ states = undefined;
+ warnings.push("no valid states given — the state filter was NOT applied");
+ }
+ }
+
+ const mediaType =
+ args.media_type === "video" || args.media_type === "livestream"
+ ? args.media_type
+ : undefined;
+ if (args.media_type !== undefined && mediaType === undefined) {
+ warnings.push(`unknown media_type ignored: ${String(args.media_type)}`);
+ }
+ const age =
+ args.age === "all_ages" || args.age === "restricted" ? args.age : undefined;
+ if (args.age !== undefined && age === undefined) {
+ warnings.push(`unknown age ignored: ${String(args.age)}`);
+ }
+
+ // A date bound the caller cannot have meant is an ERROR, not a warning: an
+ // ignored bound widens the search to the whole corpus and the count reads as
+ // the bounded one (see dateArg.ts). The common spellings are normalised.
+ const from = normalizeDateArg(args.date_from);
+ const to = normalizeDateArg(args.date_to);
+ const badDates = [
+ ["date_from", args.date_from, from],
+ ["date_to", args.date_to, to],
+ ]
+ .filter(([, , v]) => v === null)
+ .map(([name, raw]) => `${name}=${JSON.stringify(raw)}`);
+ const error = badDates.length
+ ? `not a date: ${badDates.join(", ")} — use YYYYMMDD or YYYY-MM-DD. Nothing was searched.`
+ : undefined;
+
+ // Curated tags. A malformed id is REPORTED, never silently dropped: dropping
+ // the only tag in the list would widen the search back to the whole corpus
+ // and read as a legitimate result, which is the same failure a typo'd state
+ // would cause.
+ const rawTags = strArray(args.tags);
+ let tags: string[] | undefined;
+ if (rawTags) {
+ const normalized = rawTags.map((t) => t.trim().toLowerCase());
+ tags = normalized.filter((t) => isTagId(t));
+ const bad = normalized.filter((t) => !isTagId(t));
+ if (bad.length > 0) {
+ warnings.push(
+ `not a tag id, ignored: ${bad.join(", ")} (ids are lowercase, ` +
+ `[a-z0-9._-]; call list_tags)`,
+ );
+ }
+ if (tags.length === 0) {
+ tags = undefined;
+ warnings.push("no valid tags given — the tag filter was NOT applied");
+ }
+ }
+
+ const anyFilter =
+ states !== undefined ||
+ mediaType !== undefined ||
+ age !== undefined ||
+ Boolean(from) ||
+ Boolean(to) ||
+ tags !== undefined;
+
+ const filters: SearchFilters | null = anyFilter
+ ? {
+ videos: mediaType === undefined || mediaType === "video",
+ livestreams: mediaType === undefined || mediaType === "livestream",
+ allAges: age === undefined || age === "all_ages",
+ restricted: age === undefined || age === "restricted",
+ states: new Set<VideoState>(states ?? VIDEO_STATES),
+ ...(from ? { dateFrom: from } : {}),
+ ...(to ? { dateTo: to } : {}),
+ ...(tags ? { curatedTags: tags } : {}),
+ }
+ : null;
+
+ const rawScopes = strArray(args.scopes);
+ let scopes: LayerScope[] | undefined;
+ if (rawScopes) {
+ scopes = rawScopes.filter((s): s is LayerScope =>
+ (SCOPE_TOKENS as readonly string[]).includes(s),
+ );
+ const bad = rawScopes.filter(
+ (s) => !(SCOPE_TOKENS as readonly string[]).includes(s),
+ );
+ if (bad.length > 0) {
+ warnings.push(`unknown scope(s) ignored: ${bad.join(", ")}`);
+ }
+ if (scopes.length === 0) {
+ scopes = undefined;
+ warnings.push("no valid scopes given — searching captions + title");
+ }
+ }
+
+ return {
+ filters,
+ exclude: strArray(args.exclude),
+ scopes,
+ collapseDuplicates: args.collapse_duplicates !== false,
+ warnings,
+ ...(error ? { error } : {}),
+ };
+}
+
+// Coerce a tool arg to a trimmed non-empty string[] (drops non-strings/blanks).
+export function strArray(v: unknown): string[] | undefined {
+ if (!Array.isArray(v)) return undefined;
+ const out = v
+ .filter((x): x is string => typeof x === "string")
+ .map((x) => x.trim())
+ .filter((x) => x !== "");
+ return out.length > 0 ? out : undefined;
+}
+
+// Videos per batch when a call names none: the sweep's own batch.
+export const DEFAULT_BATCH_SIZE = 8;
+
+export type EnumerateOptions = {
+ // The worklist carries no cue text by default, exactly as the tool's. A
+ // caller that shows the hits asks for snippets; WHICH recordings match does
+ // not change (snippets are collected after a record has matched).
+ includeSnippets?: boolean;
+ // Snippets kept per recording when they are included (the engine's default,
+ // 4, otherwise). `matches` still counts every hit.
+ snippetsPerVideo?: number;
+ // Every transcript record the scan reads, before any filter: what a caller
+ // learns about the scope for free (umtool counts transcripts vs captions).
+ onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void;
+};
+
+export type Enumerated = {
+ query: string;
+ parsed: ParsedSearchArgs;
+ result: SearchResult;
+ batchSize: number;
+};
+
+// `enumerate_matches`' scan: the tool's own arguments in, the whole match set
+// out (never a page of it -- the coverage rule). `{ error }` is the text the
+// tool answers with as an error, and nothing was searched.
+export async function enumerate(
+ source: ShardSource,
+ args: Record<string, unknown>,
+ opts: EnumerateOptions = {},
+): Promise<Enumerated | { error: string }> {
+ const query = String(args.query ?? "").trim();
+ if (!query) return { error: "query is required" };
+
+ const batchSizeArg =
+ typeof args.batch_size === "number" ? Math.floor(args.batch_size) : DEFAULT_BATCH_SIZE;
+ const batchSize = batchSizeArg >= 1 ? batchSizeArg : DEFAULT_BATCH_SIZE;
+
+ const parsed = parseSearchArgs(args);
+ if (parsed.error) return { error: parsed.error };
+ const result = await searchTranscripts(source, {
+ query,
+ filters: parsed.filters,
+ exclude: parsed.exclude,
+ scopes: parsed.scopes,
+ collapseDuplicates: parsed.collapseDuplicates,
+ // The singulars stay parsed even though they are no longer advertised.
+ channel: typeof args.channel === "string" ? args.channel : undefined,
+ channels: strArray(args.channels),
+ group: typeof args.group === "string" ? args.group : undefined,
+ groups: strArray(args.groups),
+ regex: args.regex === true,
+ useAliases: args.use_aliases !== false,
+ maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined,
+ contentTypes: parseContentTypes(args.content_types),
+ includeSnippets: opts.includeSnippets === true,
+ ...(opts.snippetsPerVideo !== undefined ? { snippetsPerVideo: opts.snippetsPerVideo } : {}),
+ ...(opts.onRecord ? { onRecord: opts.onRecord } : {}),
+ offset: 0,
+ // The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then
+ // slices, so asking for every collected match costs nothing extra.
+ limit: Number.MAX_SAFE_INTEGER,
+ });
+ return { query, parsed, result, batchSize };
+}
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -398,7 +398,12 @@ export type PollProgress = {
export async function fetchClip(
request: FetchClipRequest,
deps: FetchClipDeps,
- hooks: { onPoll?: (p: PollProgress) => void | Promise<void> } = {},
+ hooks: {
+ onPoll?: (p: PollProgress) => void | Promise<void>;
+ // Who asked, as the editor records it beside the file (default "mcp"):
+ // umtool's Research page says "umtool".
+ requestedBy?: string;
+ } = {},
): Promise<FetchClipOutcome> {
const editor = editorFromEnv(deps.env);
if (!editor) return { kind: "no_editor" };
@@ -499,7 +504,7 @@ export async function fetchClip(
const { target } = request;
const provenance = {
- requestedBy: REQUESTED_BY,
+ requestedBy: hooks.requestedBy ?? REQUESTED_BY,
manifest: request.report,
reason: request.reason.slice(0, MAX_REASON_CHARS),
};
diff --git a/mcp/src/research.ts b/mcp/src/research.ts
@@ -0,0 +1,45 @@
+// What umtool's Research page reads the corpus through, in process
+// (plans/umtool-redesign.md, R1): the SAME engine the tools wrap, as data.
+//
+// enumerate enumerate_matches' scan (enumerate.ts) -- the ids,
+// hits and coverage, never a page of them
+// SourceRegistry a handle (local:/remote:/hub:) to a live source,
+// cached per handle, as the server resolves `source`
+// findVideo / findPost one record, as get_transcript / get_post find it
+// fetch_clip's client validate, map the cite to the editor's directory,
+// ask the editor (never yt-dlp)
+//
+// Read-only, like every corpus tool; the only write is the editor's, through
+// its fetch-window route.
+export {
+ enumerate,
+ parseSearchArgs,
+ strArray,
+ DEFAULT_BATCH_SIZE,
+ type Enumerated,
+ type EnumerateOptions,
+ type ParsedSearchArgs,
+} from "./enumerate";
+export { SourceRegistry, handleFor, type ResolvedSource } from "./sourceRegistry";
+export type { SourceSpec } from "./sources";
+export {
+ findVideo,
+ findPost,
+ resolveSelectedChannels,
+ MCP_POLICY,
+ type SearchHit,
+ type SearchResult,
+ type Snippet,
+} from "./search";
+export type { ChannelRef, ShardSource } from "./source";
+export {
+ fetchClip,
+ validateFetchClipArgs,
+ editorFromEnv,
+ describeFetchError,
+ NO_EDITOR_TEXT,
+ type FetchClipDeps,
+ type FetchClipOutcome,
+ type FetchClipRequest,
+} from "./fetchClip";
+export { resolveClipTarget } from "./clipTarget";
diff --git a/mcp/src/search.ts b/mcp/src/search.ts
@@ -486,6 +486,11 @@ export async function searchTranscripts(
// existing caller reads exactly the same pages and parses exactly the same
// bytes. A caller with a different budget passes its own.
policy?: SearchPolicy;
+ // Told every transcript record the video pass reads, BEFORE any filter or
+ // match: what the scan saw of the scope, for a caller that wants to learn
+ // about it for free (umtool counts transcripts vs captions per channel).
+ // Changes nothing about what matches.
+ onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void;
},
): Promise<SearchResult> {
const policy = opts.policy ?? MCP_POLICY;
@@ -603,6 +608,7 @@ export async function searchTranscripts(
if (records === null) continue; // failed page — skipped, as before
pagesScanned++;
for (const rec of records) {
+ opts.onRecord?.(rec, ch);
if (
filters &&
!passesFilters(rec, filters, availability?.get(rec.slug))
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -1,4 +1,3 @@
-import { normalizeDateArg } from "./dateArg";
import {
Server,
type Prompt,
@@ -12,7 +11,7 @@ import type { VideoStat } from "yt-dlp-transcript-common/lib/stats";
import { momentUrl, momentBaseUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl";
import type { Platform } from "yt-dlp-transcript-common/lib/platform";
import type { SearchAlias } from "yt-dlp-transcript-common/lib/searchAliases";
-import { isTagId, type PublishedTag } from "yt-dlp-transcript-common/lib/curatedTags";
+import type { PublishedTag } from "yt-dlp-transcript-common/lib/curatedTags";
import { groupPublishedTags } from "yt-dlp-transcript-common/lib/publishedTags";
import {
cuesOfTrack,
@@ -22,12 +21,7 @@ import {
trackLabel,
} from "yt-dlp-transcript-common/lib/captionTracks";
import { windowedTranscript } from "yt-dlp-transcript-common/lib/search/window";
-import {
- VIDEO_STATES,
- isVideoState,
- type VideoState,
-} from "yt-dlp-transcript-common/lib/availability";
-import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
+import { VIDEO_STATES } from "yt-dlp-transcript-common/lib/availability";
import {
sortGroups,
resolveChannelGroupId,
@@ -82,8 +76,6 @@ import {
renderFetchClip,
validateFetchClipArgs,
editorFromEnv,
- notFoundNote,
- isVideoId,
NO_EDITOR_TEXT,
type FetchClipDeps,
type PollProgress,
@@ -103,7 +95,8 @@ import {
generationPolicyTool,
planGeneration,
} from "./generation";
-import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
+import { enumerate, parseSearchArgs, strArray, type ParsedSearchArgs } from "./enumerate";
+import { resolveClipTarget } from "./clipTarget";
import {
decodeShareLink,
applyLinkOverrides,
@@ -1144,9 +1137,9 @@ const DEFAULT_FETCH_CLIP_DEPS: FetchClipDeps = {
// from the URL slug (`v1007ay`). Passing the embed id would make the editor
// create a NEW data/vxe1ae/ and fetch rumble.com/vxe1ae. The record's
// `webpageUrl` is the slug URL, so the canonical id comes from it — the same
-// `extractVideoId` the editor names its directories with. On YouTube the two
-// are equal. A video the corpus does not hold goes through as cited, with a
-// note saying what that risks.
+// `extractVideoId` the editor names its directories with (clipTarget.ts). On
+// YouTube the two are equal. A video the corpus does not hold goes through as
+// cited, with a note saying what that risks.
async function handleFetchClip(
source: ShardSource,
resolved: ResolvedSource,
@@ -1161,24 +1154,7 @@ async function handleFetchClip(
if (!v.ok) return errorText(v.error);
const request = v.request;
- let note = "";
- let ctx: { channel?: string; video?: string } = {};
- if ("target" in request) {
- const target = request.target;
- const found = await findVideo(source, target.video, target.channel);
- if (found) {
- const webpageUrl = found.record.webpageUrl;
- const mapped = webpageUrl ? extractVideoId(webpageUrl) : null;
- target.video = mapped && isVideoId(mapped) ? mapped : target.video;
- // The channel the record lives in, which is the editor's directory even
- // when the citation spelled it by name or in another case.
- target.channel = found.ch.slug;
- if (target.kind === "window" && webpageUrl) target.webpageUrl = webpageUrl;
- } else {
- note = `${notFoundNote(target.video, resolved.handle)}\n\n`;
- }
- ctx = { channel: target.channel, video: target.video };
- }
+ const { note, ctx } = await resolveClipTarget(source, resolved.handle, request);
const outcome = await fetchClip(request, deps, { onPoll });
const rendered = renderFetchClip(outcome, ctx);
@@ -1786,36 +1762,11 @@ async function handleEnumerateMatches(
source: ShardSource,
args: Record<string, unknown>,
): Promise<ToolResult> {
- const query = String(args.query ?? "").trim();
- if (!query) return errorText("query is required");
-
- const batchSizeArg =
- typeof args.batch_size === "number" ? Math.floor(args.batch_size) : 8;
- const batchSize = batchSizeArg >= 1 ? batchSizeArg : 8;
-
- const parsed = parseSearchArgs(args);
- if (parsed.error) return errorText(parsed.error);
- const result = await searchTranscripts(source, {
- query,
- filters: parsed.filters,
- exclude: parsed.exclude,
- scopes: parsed.scopes,
- collapseDuplicates: parsed.collapseDuplicates,
- // The singulars stay parsed even though they are no longer advertised.
- channel: typeof args.channel === "string" ? args.channel : undefined,
- channels: strArray(args.channels),
- group: typeof args.group === "string" ? args.group : undefined,
- groups: strArray(args.groups),
- regex: args.regex === true,
- useAliases: args.use_aliases !== false,
- maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined,
- contentTypes: parseContentTypes(args.content_types),
- includeSnippets: false,
- offset: 0,
- // The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then
- // slices, so asking for every collected match costs nothing extra.
- limit: Number.MAX_SAFE_INTEGER,
- });
+ // The scan is enumerate.ts's, shared with umtool's Research page: this tool
+ // only renders it.
+ const e = await enumerate(source, args);
+ if ("error" in e) return errorText(e.error);
+ const { query, parsed, result, batchSize } = e;
const partial = result.truncated;
const capNote = describeCapCoverage(result);
@@ -1889,150 +1840,6 @@ function describeFiredAliases(fired: SearchAlias[]): string {
return `expanded via alias ${parts.join(", ")}`;
}
-// ─── the shared filter/scope parsing for both search tools ───
-
-// The parsed form of SEARCH_FILTER_ARGS, plus any tokens that were not
-// understood. Unknown tokens are REPORTED rather than dropped silently: a
-// typo'd state ("removed" for "deleted") would otherwise widen the search back
-// to the whole corpus and look like a legitimate empty result.
-type ParsedSearchArgs = {
- filters: SearchFilters | null;
- exclude?: string[];
- scopes?: LayerScope[];
- collapseDuplicates: boolean;
- warnings: string[];
- // Set when an argument must stop the call rather than be dropped (a date
- // bound that is not a date). Callers return it as an error and search nothing.
- error?: string;
-};
-
-const SCOPE_TOKENS: ReadonlyArray<LayerScope> = [
- "transcripts",
- "chat",
- "description",
- "tags",
- "metadata",
- "posts",
-];
-
-function parseSearchArgs(args: Record<string, unknown>): ParsedSearchArgs {
- const warnings: string[] = [];
-
- const rawStates = strArray(args.states);
- let states: VideoState[] | undefined;
- if (rawStates) {
- states = rawStates.filter((s): s is VideoState => isVideoState(s));
- const bad = rawStates.filter((s) => !isVideoState(s));
- if (bad.length > 0) {
- warnings.push(
- `unknown state(s) ignored: ${bad.join(", ")} (valid: ${VIDEO_STATES.join(", ")})`,
- );
- }
- if (states.length === 0) {
- states = undefined;
- warnings.push("no valid states given — the state filter was NOT applied");
- }
- }
-
- const mediaType =
- args.media_type === "video" || args.media_type === "livestream"
- ? args.media_type
- : undefined;
- if (args.media_type !== undefined && mediaType === undefined) {
- warnings.push(`unknown media_type ignored: ${String(args.media_type)}`);
- }
- const age =
- args.age === "all_ages" || args.age === "restricted" ? args.age : undefined;
- if (args.age !== undefined && age === undefined) {
- warnings.push(`unknown age ignored: ${String(args.age)}`);
- }
-
- // A date bound the caller cannot have meant is an ERROR, not a warning: an
- // ignored bound widens the search to the whole corpus and the count reads as
- // the bounded one (see dateArg.ts). The common spellings are normalised.
- const from = normalizeDateArg(args.date_from);
- const to = normalizeDateArg(args.date_to);
- const badDates = [
- ["date_from", args.date_from, from],
- ["date_to", args.date_to, to],
- ]
- .filter(([, , v]) => v === null)
- .map(([name, raw]) => `${name}=${JSON.stringify(raw)}`);
- const error = badDates.length
- ? `not a date: ${badDates.join(", ")} — use YYYYMMDD or YYYY-MM-DD. Nothing was searched.`
- : undefined;
-
- // Curated tags. A malformed id is REPORTED, never silently dropped: dropping
- // the only tag in the list would widen the search back to the whole corpus
- // and read as a legitimate result, which is the same failure a typo'd state
- // would cause.
- const rawTags = strArray(args.tags);
- let tags: string[] | undefined;
- if (rawTags) {
- const normalized = rawTags.map((t) => t.trim().toLowerCase());
- tags = normalized.filter((t) => isTagId(t));
- const bad = normalized.filter((t) => !isTagId(t));
- if (bad.length > 0) {
- warnings.push(
- `not a tag id, ignored: ${bad.join(", ")} (ids are lowercase, ` +
- `[a-z0-9._-]; call list_tags)`,
- );
- }
- if (tags.length === 0) {
- tags = undefined;
- warnings.push("no valid tags given — the tag filter was NOT applied");
- }
- }
-
- const anyFilter =
- states !== undefined ||
- mediaType !== undefined ||
- age !== undefined ||
- Boolean(from) ||
- Boolean(to) ||
- tags !== undefined;
-
- const filters: SearchFilters | null = anyFilter
- ? {
- videos: mediaType === undefined || mediaType === "video",
- livestreams: mediaType === undefined || mediaType === "livestream",
- allAges: age === undefined || age === "all_ages",
- restricted: age === undefined || age === "restricted",
- states: new Set<VideoState>(states ?? VIDEO_STATES),
- ...(from ? { dateFrom: from } : {}),
- ...(to ? { dateTo: to } : {}),
- ...(tags ? { curatedTags: tags } : {}),
- }
- : null;
-
- const rawScopes = strArray(args.scopes);
- let scopes: LayerScope[] | undefined;
- if (rawScopes) {
- scopes = rawScopes.filter((s): s is LayerScope =>
- (SCOPE_TOKENS as readonly string[]).includes(s),
- );
- const bad = rawScopes.filter(
- (s) => !(SCOPE_TOKENS as readonly string[]).includes(s),
- );
- if (bad.length > 0) {
- warnings.push(`unknown scope(s) ignored: ${bad.join(", ")}`);
- }
- if (scopes.length === 0) {
- scopes = undefined;
- warnings.push("no valid scopes given — searching captions + title");
- }
- }
-
- return {
- filters,
- exclude: strArray(args.exclude),
- scopes,
- collapseDuplicates: args.collapse_duplicates !== false,
- warnings,
- ...(error ? { error } : {}),
- };
-}
-
// A human note for the footer describing the filters actually applied, so a
// result can never be read as unfiltered when it wasn't.
function describeSearchFilters(p: ParsedSearchArgs): string {
@@ -2121,16 +1928,6 @@ function describeCoverage(result: SearchResult): string {
);
}
-// Coerce a tool arg to a trimmed non-empty string[] (drops non-strings/blanks).
-function strArray(v: unknown): string[] | undefined {
- if (!Array.isArray(v)) return undefined;
- const out = v
- .filter((x): x is string => typeof x === "string")
- .map((x) => x.trim())
- .filter((x) => x !== "");
- return out.length > 0 ? out : undefined;
-}
-
// A human scope note for the search footer: names the resolved scope (whole
// corpus, a named group + channel count, or an N-channel set) and warns about
// any channel/group token that matched nothing — so a typo is surfaced, not
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 umtool/lib/work/*.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 umtool/lib/work/*.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/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -348,7 +348,7 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─
| P0 design | — (`~/reports/umtool-redesign/canvas.html`, version 2) | signed off 2026-10-14 |
| P2a engine | `ux/p2a` → `main` `fe1cb2d3` | LIVE 2026-10-14 (umtool BUILD_ID 4aRwqu6sh…) |
| P1 foundation | `ux/p1` → `main` `37354f70` | LIVE 2026-10-14 (umtool BUILD_ID LQxTh16Pe…) |
-| R1 research | `ux/r1` | in progress |
+| R1 research | `ux/r1` → `ux/integration` `4ce2fc2c` | merged into the integration branch |
| P3 inbox/work/tools/URLs | `ux/p3` (release 28 merged in) | gates green; awaiting merge |
| P2b, P4a, P5, R3, P4b, P6 | — | wait for r28 on `main` |
@@ -545,6 +545,157 @@ capped) and restarted (`~/reports/umtool-redesign/scripts/p1-umtool.sh`). Live s
serves `data-theme="light"`; the rail renders; the decisions API unchanged (825 rows). Ruling on the lane's question:
the Signal-as-link uses in r28's files are swept in P4a, after r28 lands, not now.
+### R1, as shipped
+
+**What.** Research, first-class: `/research` (ask, scope, results, facets, reader, reading log) and
+`/research/archive` (the inventory), over the MCP's own engine, read-only on the corpus.
+
+- **The engine, shared as data** (`mcp/`, additive):
+ - `src/enumerate.ts`: `enumerate(source, args, opts)` is `enumerate_matches`' scan, and the tool now renders its
+ result. `parseSearchArgs` and `strArray` moved there from `server.ts` unchanged. Options a structured caller adds:
+ `includeSnippets` and `snippetsPerVideo` (which recordings match does not change), and `onRecord`.
+ - `searchTranscripts` gains `onRecord`: every record the video pass reads, before any filter or match.
+ - `src/clipTarget.ts`: `fetch_clip`'s cite-to-directory mapping (record channel, `extractVideoId` of its URL for
+ Rumble), factored out of `handleFetchClip`. `fetchClip` takes `requestedBy` (default `mcp`).
+ - `yt-dlp-transcript-mcp/research` (`src/research.ts`): the export umtool imports. No MCP SDK in it.
+- **`umtool/lib/research/`** (server unless noted):
+ - `sources.ts`: the picker. Local = `TRANSCRIPT_LOCAL_DIR`, else `EXPORT_PUBLIC_DIR`, else `<repo>/export/public`
+ (the MCP's default); every `sites/*/site.json` with a `siteUrl` as `remote:`; the hub from
+ `TRANSCRIPT_HUB_URL` or `settings.json` `homepageUrl`. Only an offered handle opens. Sources are the MCP's
+ `SourceRegistry`, cached on `globalThis`; a local one reopens when its `corpus.json` changes.
+ - `corpus.ts`: `scopeOf` (channels, videos and the upload span from the summaries index, filters applied by the
+ engine's own `passesFilters`), `runSearch` (one `enumerate`, snippets on, never paged; hits with timecodes,
+ marks, track, state, duration, mirrors; facets; the session's log; memo 10 min × 8), `windowOf` (cues ±span
+ around the cite, the nearest cue lit, the citation, local media).
+ - **The track census.** Shard records carry `transcriptFormat` (`vtt` = captions, `*-json` = our transcription,
+ absent = unknown). Nothing published counts it per scope, so a search counts it through `onRecord`, per
+ channel, only when it read the channel whole (records seen = the manifest's `slugToPage`). The scope line
+ says "counted by the first full search" until then, and "N of M channels counted" when partial.
+ - `coverage.ts`: published (summaries, by upload year and state) and held (the editor's
+ `GET /api/ops/coverage?slug=&gapDays=60`, as `channel_coverage` asks it). No `WORKER_TOKEN`, an unreachable
+ editor, a 503 (its ops surface off), a 401 or a route it does not have each say which; for the local corpus the
+ held counts are then `common/controller/channelCoverage.ts` on `CHANNELS_DIR`, read only. A 404
+ `Channel "x" not found` is that channel's answer.
+ - `fetch.ts`: Fetch clip = `validateFetchClipArgs` → `resolveClipTarget` → `fetchClip(…, {requestedBy:
+ "umtool"})`, `wait_seconds: 0`, polled by `{job}`. `media.ts`: what plays from this machine (clip windows,
+ `source-media.*`, `audio.*` under the editor's directory id), served by name from the server's own scan, with ranges.
+ - Pure (browser-safe, `node --test`): `query.mjs` (phrase, `/regex/`, `a near:N b` → a regex within one caption
+ line; `markRanges` mirrors `buildMatcher`: substring or regex plus the fired aliases), `facets.mjs` (`trackOf`,
+ facets with zero years kept, the house citation: `"quote" [title @ m:ss](url)`, `[post by a, d](url)`),
+ `rules.mjs` (`candace-owens`, `realcandaceo` local-only, marked on every hit and chip), `log.mjs` (the reading
+ log), `session.mjs` (the session key, node:crypto). `hrefs.ts`: the URL builders (lib/hrefs.ts is P3's).
+- **Routes** `app/api/research/{sources,scope,search,window,coverage,log,media,fetch}`: JSON, `no-store`, errors in
+ words (400 bad input, 404 nothing there, 502 a source that cannot be read).
+- **The reading log**: `REPORTS_ROOT/.umtool/research/sessions/<16 hex>.json`, keyed by query + scope until R2's
+ cases; `{format: "umtool-research-log", session, query, scope, updatedAt, marks}`; the lifecycle store's
+ discipline (serialised, temp + rename, an unreadable file never overwritten, 409).
+- **`/research`** (`components/research/`): the ask bar (`/` focuses it; the hint says phrase, regex or near), scope
+ chips as native `<details>` (source, channels, dates, platform state, videos/streams, + Posts) and the **holds**
+ line before anything runs; the honest header (**N recordings · full coverage** or **Partial — not reached:**, lines,
+ pages, mirrors folded, aliases, "showing n of N", **read x of N**); results as ONE global LitList grouped by
+ recording (timecode, the match marked, read state; the CiteThread on the lit line only); the facets column (year
+ histogram with zeros, channel, text, state, reading; each narrows what is drawn, never re-runs); the ReaderPane
+ (the window with its cue lit and centred, −/+ span, **Copy citation** the one go, **Play from**, **Fetch clip**,
+ the citation as fine print). Keys `j`/`k`, `r` read, `s` skip (both move to the next recording), `u` unread, `c`
+ copy, `/` ask. The query and scope are in the URL (`replaceState`); a `?q=` link runs on arrival. 200 recordings
+ are drawn at a time ("Show 200 more").
+- **`/research/archive`**: channels × years, numbered cells on `--m1..m5` with their inks, the canvas's bins
+ (50/200/600/1,200), the doubt line under a gap year (over 60 days), — for none; Videos held / Videos published;
+ hover or focus for the tooltip (held, published, missing states, transcripts vs captions); arrow keys walk it; Table.
+- `components/ui/cite-thread.tsx` (`ReaderThread`): the 0:00 and end labels give way when the cite's label would
+ sit on them (seen on a cite at 98% of a recording).
+- e2e: `e2e/fixtures/research-fixture.mjs` writes `research-public/` (4 channels, 12 recordings 2019–2026,
+ captions and transcriptions, one deleted, one unlisted, a Rumble mirror cluster, a local-only slug) and two held
+ channels in `CHANNELS_DIR`; `playwright.config.ts` sets `TRANSCRIPT_LOCAL_DIR` to it; `research-enumerate.ts`
+ runs `enumerate_matches` through `createCorpusTools` for the spec.
+
+| Commit | What |
+|---|---|
+| `90d78927` | mcp: `enumerate.ts` (the scan as data, the tool renders it), `clipTarget.ts`, `requestedBy`, `onRecord`, the `./research` export; umtool depends on the mcp package |
+| `915b8e60` | merge `ux/integration` (release 28 on `main`) |
+| `3616a180` | `lib/research` (sources, corpus, coverage, fetch, media, log, query, facets, rules, hrefs, types), the eight routes, the research fixture, `parity.test.ts` |
+| `33ed3d22` | `/research`, `/research/archive`, `e2e/research.spec.ts`, the fixture wired into make-fixture and the config |
+| `210c1548` | the session key moves to `session.mjs`: `facets.mjs` stays browser-safe |
+| `aad7e2d9` | the reader centres the cited cue; ReaderThread labels give way; sites by `siteTitle`; copy only the lit hit's citation |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean (after the merge and at the tip) |
+| `pnpm --filter umtool typecheck` | clean |
+| umtool unit, `node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs` | 783 tests, 781 pass, 2 skipped, 0 fail (13 new: query 4, facets 6, log 3) |
+| `pnpm --filter umtool test` (new: `tsx --test lib/research/*.test.ts`) | 9/9: parity with `enumerate_matches` through `createCorpusTools` on 5 asks (phrase, regex, one channel, a date window, deleted only), the search's facets, the scope preview and census, the window and citation, the inventory's disk fallback |
+| `pnpm run test:scripts` (now with `umtool/lib/research/*.test.mjs`; reads the capped build's traces) | 934 tests, 932 pass, 2 skipped, 0 fail |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | 363/363 after the merge (11 new in `enumerate.test.ts`) |
+| editor unit `pnpm --filter editor test` (imports `createCorpusTools`) | 295/295 |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`, through the heavy slot) | exit 0; compiled 14.8 s, 45 s wall, 1.31 GB max RSS. The ten research routes' traces: 821–842 files each, none from `transcripts/`, `export/public`, `.e2e-song`, `.next-e2e` or `.env*` |
+| full umtool e2e (`pnpm --filter umtool run e2e`, detached, queued) | 348 tests: 342 passed, 0 failed, 6 skipped (the song-data capability skips), 8.8 min. `research.spec.ts` 9/9, 18 s |
+
+**Live check (read-only, offline tsx, 2026-10-14).** The primary's `export/public` (composed for Rekietalyzer:
+`rekietalaw`, `rekietalaw-rumble`, 2,950 videos), REPORTS_DIR in scratch:
+
+| Query | `enumerate_matches` (createCorpusTools) | Research `runSearch` | Same ids, same order |
+|---|---|---|---|
+| `lawsuit` | 1,654, complete, 9.6 s | 1,654, complete, 209 mirrors folded, 90 pages, 10.0 s | yes |
+| `contempt of court` | 70, complete, 10.4 s | 70, complete, 6 mirrors folded, 90 pages, 9.9 s | yes |
+
+After those scans the scope line read 2 channels · 2,950 videos · 2017–2026 · transcripts 9% · captions 74% · unknown
+17% (506 records carry no `transcriptFormat`) · 3 aliases.
+
+**Screenshots and keys.** `/research` (a search, the reader on a lit hit) and `/research/archive` at 1366×768 and
+1440×900, both themes, on the real local corpus with held counts from the live editor's coverage route (read only),
+in the job's scratch `r1-shots/`. Compared with the canvas: same columns (results, 176 px facets, the reader at
+`minmax(360px, 34%)`), the lit line, the meter histogram, the reader with the cue lit. Keyboard-only: every control
+of both pages takes Tab with the 2 px ring (rail 12 stops, then the ask bar, Search, the source, five chips, the
+list's one stop, the facets, the reader's cues); `/`, `j`/`k`, `r`/`s`/`u`, `c` and the inventory's arrows work
+from the keyboard alone; reduced motion is the LitList's.
+
+**Found and left.**
+- No `near` operator exists in the engine; `a near:N b` compiles to a regex and matches inside one caption line, and
+ the ask bar says so.
+- Transcripts vs captions is known only for what a search has read whole (in memory, per source); a published site
+ has no per-scope count. A census survives until umtool restarts or the local corpus is recomposed.
+- The reading log is per query + scope; R2's cases carry their own. A Candace hit is marked local only; R1 exports
+ nothing, and R2's board export must refuse `isLocalOnly` (rules.mjs). The X archive is never put on a site; R1
+ puts nothing on one.
+- On a hub, two member sites with the same channel slug share a facet row and a log key.
+- Not touched (P3's): the rail (no Research place yet: `/research` lights none), `lib/hrefs.ts`, `globals.css`,
+ `AppShell`, `redirects.mjs`. The only shared primitive touched is `ReaderThread`'s labels.
+
+**Follow-up (after review, `885d82ae`).**
+- **Held counts are kept.** Each channel's held count (the editor's answer, the disk's, or "not known" with the
+ reason) is memoised five minutes per source and channel, on `globalThis` (`lib/research/coverage.ts`,
+ `HELD_TTL_MS`). The editor is still asked four at a time, and only for the channels past the memo.
+ `/research/archive` says "Held counts from 3 min ago (kept 5 min)", and **Refresh** asks again
+ (`/api/research/coverage?fresh=1`). The live editor has stalled on the external drive before, and a page load no
+ longer costs a disk walk per channel.
+- **The track census is persisted** (`lib/research/census.mjs`):
+ - Location: `REPORTS_ROOT/.umtool/research/census/<sha1(handle)>.json`.
+ - Key: the source handle plus its build identity (`sources.ts` `buildIdentity`):
+ - a published site or the hub: its `corpus.json` `generatedAt`;
+ - the local dir: that, plus `corpus.json`'s mtime and size.
+ - Writes are atomic and serialised, like `lib/lifecycle.mjs`.
+ - A file from another build is not used, and the scope line says "transcripts vs captions: counted on an earlier
+ build (date); the next full search counts again".
+ - A source whose identity cannot be read (no `corpus.json`, or one that is unreachable) is still counted, but not
+ kept.
+- **The solid Signal box on the lit row comes from P1, not R1. Not changed.** The global `:focus-visible { outline:
+ 2px solid var(--signal) }` in `app/globals.css` sits outside any `@layer`. `.lit-line:focus-visible` (the dashed
+ seam-2 outline) is inside `@layer components`, and unlayered styles beat layered ones whatever the specificity.
+ So every focused lit line draws the 2 px Signal ring: measured on `/research`'s lit row as `solid 2px
+ rgb(63,193,176)`. P1's keyboard pass recorded the same 2 px ring on every control. R1's row markup adds no
+ outline class. The fix belongs in `globals.css` (P3's this phase), for example by scoping the global ring with
+ `:where()` or moving it into `@layer base`.
+- **Gates:**
+ - repo-wide tsc and umtool typecheck: clean.
+ - umtool unit: 785 tests, 783 pass, 2 skipped (census 2 new).
+ - `pnpm --filter umtool test`: 11/11 (memo and census 2 new).
+ - `research.spec.ts` through `pnpm --filter umtool run e2e research.spec.ts`: 12 passed, 0 failed, 52.8 s. The
+ filter also matched `article-research.spec.ts`; research.spec itself was 9/9, and now checks the age line and
+ Refresh.
+ - Fresh dark screenshots of `/research` and `/research/archive` at 1366×768 (job scratch `r1-shots/followup-*`).
+
### P3, as shipped
**What.** The Inbox at `/`, Work, Tools and Settings · system, every page at its new address with the old ones
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
@@ -355,6 +355,9 @@ importers:
yt-dlp-transcript-common:
specifier: workspace:*
version: link:../common
+ yt-dlp-transcript-mcp:
+ specifier: workspace:*
+ version: link:../mcp
devDependencies:
'@playwright/test':
specifier: ^1.59.1
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,22 @@
+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[&fresh=1] -> 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. The held counts are
+// kept five minutes per source and channel; `fresh=1` (Refresh) asks again.
+export async function GET(request: Request) {
+ try {
+ const q = new URL(request.url).searchParams;
+ return ok(await coverageOf(scopeFrom(q), { fresh: q.get("fresh") === "1" }));
+ } 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/app/research/archive/page.tsx b/umtool/app/research/archive/page.tsx
@@ -0,0 +1,64 @@
+import Link from "next/link";
+import AppShell from "@/components/shell/AppShell";
+import ArchiveInventory from "@/components/research/ArchiveInventory";
+import { badgeVariants } from "@/components/ui/badge";
+import { scopeFrom } from "@/lib/research/corpus";
+import { coverageOf } from "@/lib/research/coverage";
+import { researchArchiveHref, researchHref } from "@/lib/research/hrefs";
+import { listSources } from "@/lib/research/sources";
+import type { CoverageResponse } from "@/lib/research/types";
+
+export const dynamic = "force-dynamic";
+
+// THE ARCHIVE INVENTORY (plans/umtool-redesign.md, "Research, first-class" 6):
+// what the archive can and cannot answer -- channels × years, what is held and
+// what is published, the gaps. A static segment under app/research/, so it is
+// never a case id when R2 adds /research/<case>. The numbers are
+// lib/research/coverage.ts's; the grid is the client's (hover, keys, Table).
+export default async function ArchivePage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
+ const sp = await searchParams;
+ const params = new URLSearchParams();
+ for (const [k, v] of Object.entries(sp)) for (const x of Array.isArray(v) ? v : v !== undefined ? [v] : []) params.append(k, x);
+ const sources = await listSources();
+ const scope = scopeFrom(params);
+ if (!scope.source || !sources.some((s) => s.handle === scope.source)) scope.source = sources[0].handle;
+ let data: CoverageResponse | null = null;
+ let error: string | null = null;
+ try {
+ data = await coverageOf(scope);
+ } catch (e) {
+ error = (e as Error).message;
+ }
+ const at = (handle: string) => (handle === sources[0].handle ? undefined : handle);
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="research"
+ crumbs={[{ href: researchHref(), label: "research" }, { label: "archive" }]}
+ meta="what the archive can answer · by year"
+ note={data ? `${data.rows.length} channels · ${data.years.length ? `${data.years[0]}–${data.years[data.years.length - 1]}` : "no dates"}` : undefined}
+ />
+ <nav aria-label="Source" className="flex flex-wrap items-center gap-1.5 border-b border-seam px-7 py-2.5">
+ {sources.map((s) => (
+ <Link
+ key={s.handle}
+ href={researchArchiveHref({ source: at(s.handle) })}
+ aria-current={s.handle === scope.source ? "page" : undefined}
+ className={badgeVariants({ variant: s.handle === scope.source ? "on" : "neutral", size: "md" })}
+ >
+ {s.label}
+ </Link>
+ ))}
+ </nav>
+ <div className="min-h-0 flex-1 overflow-auto px-7 pb-6">
+ {error ? (
+ <p role="alert" className="pt-4 text-[13px] text-reject-text">
+ {error}
+ </p>
+ ) : data ? (
+ <ArchiveInventory data={data} source={scope.source} />
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx
@@ -0,0 +1,47 @@
+import Link from "next/link";
+import AppShell from "@/components/shell/AppShell";
+import ResearchView from "@/components/research/ResearchView";
+import { buttonVariants } from "@/components/ui/button";
+import { scopeFrom, scopeOf } from "@/lib/research/corpus";
+import { researchArchiveHref } from "@/lib/research/hrefs";
+import { listSources } from "@/lib/research/sources";
+import type { ScopeSummary } from "@/lib/research/types";
+
+export const dynamic = "force-dynamic";
+
+// RESEARCH (plans/umtool-redesign.md, R1): ask the corpus, see what the scope
+// holds before anything runs, read every hit in its transcript, keep a
+// reading log. The page is the client's (components/research/ResearchView.tsx);
+// this reads the sources and the scope's preview so the first frame has them.
+// A search itself is never run here: it is one scan, and the page shows it
+// running.
+export default async function ResearchPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
+ const sp = await searchParams;
+ const params = new URLSearchParams();
+ for (const [k, v] of Object.entries(sp)) for (const x of Array.isArray(v) ? v : v !== undefined ? [v] : []) params.append(k, x);
+ const sources = await listSources();
+ const scope = scopeFrom(params);
+ if (!scope.source || !sources.some((s) => s.handle === scope.source)) scope.source = sources[0].handle;
+ let summary: ScopeSummary | null = null;
+ let summaryError: string | null = null;
+ try {
+ summary = await scopeOf(scope);
+ } catch (e) {
+ summaryError = (e as Error).message;
+ }
+ const q = typeof sp.q === "string" ? sp.q : "";
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="research"
+ crumbs={[{ label: "research" }]}
+ actions={
+ <Link href={researchArchiveHref({ source: scope.source === sources[0].handle ? undefined : scope.source })} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Archive inventory
+ </Link>
+ }
+ />
+ <ResearchView sources={sources} initialQuery={q} initialScope={scope} initialSummary={summary} initialSummaryError={summaryError} />
+ </div>
+ );
+}
diff --git a/umtool/components/research/ArchiveInventory.tsx b/umtool/components/research/ArchiveInventory.tsx
@@ -0,0 +1,275 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { Table, TD, TH } from "@/components/ui/table";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { researchCoverageApi } from "@/lib/research/hrefs";
+import { cn } from "@/lib/utils";
+import type { CoverageResponse, CoverageRow } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// THE ARCHIVE INVENTORY (canvas `#view-archive`): channels × years, a number in
+// every cell, the Meter ramp (--m1..--m5, each with its own ink so the number
+// reads on it), a gap over 60 days marked under the cell in the doubt line, "—"
+// where nothing is held. Hover or focus a cell for what it holds; the arrow keys
+// walk the grid; Table shows the same numbers as rows.
+//
+// Two measures: HELD (what the editor has on disk, channel_coverage) and
+// PUBLISHED (what this source's summaries list, by upload year). The ramp is
+// sequential and fixed (the canvas's bins), so two archives read alike.
+// ---------------------------------------------------------------------------
+
+type Measure = "held" | "published";
+
+const BINS = [50, 200, 600, 1200];
+const binOf = (n: number) => (!n ? 0 : 1 + BINS.filter((b) => n >= b).length);
+const RAMP = [
+ "bg-transparent text-muted-2 shadow-[inset_0_0_0_1px_var(--seam)]",
+ "bg-m1 text-[var(--m1-ink)]",
+ "bg-m2 text-[var(--m2-ink)]",
+ "bg-m3 text-[var(--m3-ink)]",
+ "bg-m4 text-[var(--m4-ink)]",
+ "bg-m5 text-[var(--m5-ink)]",
+];
+const nf = new Intl.NumberFormat("en-US");
+
+function countOf(r: CoverageRow, m: Measure, y: string): number {
+ return (m === "held" ? r.held?.byYear[y] : r.published.byYear[y]) ?? 0;
+}
+
+function tipOf(r: CoverageRow, m: Measure, y: string): string {
+ const n = countOf(r, m, y);
+ const parts = [`${r.name} · ${y}`, n ? `${nf.format(n)} ${m === "held" ? "held" : "published"}` : m === "held" ? "nothing held" : "nothing published"];
+ if (m === "held" && r.published.byYear[y]) parts.push(`${nf.format(r.published.byYear[y])} published`);
+ if (m === "published" && r.held?.byYear[y]) parts.push(`${nf.format(r.held.byYear[y])} held`);
+ const t = r.tracks?.[y];
+ if (t && t.transcript + t.captions + t.unknown > 0) parts.push(`transcripts ${t.transcript} · captions ${t.captions}${t.unknown ? ` · unknown ${t.unknown}` : ""}`);
+ const missing = r.published.missingByYear[y];
+ if (missing) parts.push(Object.entries(missing).map(([s, k]) => `${k} ${(VIDEO_STATE_LABELS[s as VideoState] ?? s).toLowerCase()}`).join(", "));
+ if (r.held?.gapYears.includes(y)) parts.push("gap over 60 days");
+ return parts.join(" · ");
+}
+
+/** "just now", "3 min ago", "1 h ago". */
+export function ago(ms: number): string {
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 45) return "just now";
+ const m = Math.round(s / 60);
+ return m < 60 ? `${m} min ago` : `${Math.round(m / 60)} h ago`;
+}
+
+export default function ArchiveInventory({ data: initial, source }: { data: CoverageResponse; source: string }) {
+ const hydrated = useHydrated();
+ const [data, setData] = useState(initial);
+ const [refreshing, setRefreshing] = useState(false);
+ const [refreshError, setRefreshError] = useState<string | null>(null);
+ // The age line re-reads the clock; the counts themselves change only on Refresh.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(id);
+ }, []);
+ const refresh = async () => {
+ setRefreshing(true);
+ setRefreshError(null);
+ try {
+ const r = await fetch(researchCoverageApi({ source }, { fresh: true }), { cache: "no-store" });
+ const body = await r.json().catch(() => null);
+ if (!r.ok) throw new Error(body?.error ?? `HTTP ${r.status}`);
+ setData(body as CoverageResponse);
+ setNow(Date.now());
+ } catch (e) {
+ setRefreshError((e as Error).message);
+ } finally {
+ setRefreshing(false);
+ }
+ };
+ const [measure, setMeasure] = useState<Measure>(data.held.via === "none" ? "published" : "held");
+ const [table, setTable] = useState(false);
+ const [tip, setTip] = useState<{ text: string; x: number; y: number } | null>(null);
+ const [focus, setFocus] = useState<[number, number]>([0, 0]);
+ const host = useRef<HTMLDivElement>(null);
+ const grid = useRef<HTMLTableElement>(null);
+ const { years, rows } = data;
+
+ const showTip = (el: HTMLElement) => {
+ const h = host.current?.getBoundingClientRect();
+ const r = el.getBoundingClientRect();
+ if (!h) return;
+ setTip({ text: el.dataset.tip ?? "", x: r.left - h.left + (host.current?.scrollLeft ?? 0), y: r.bottom - h.top + (host.current?.scrollTop ?? 0) + 6 });
+ };
+
+ const move = (e: React.KeyboardEvent, ri: number, ci: number) => {
+ const d: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
+ const k = d[e.key] ?? (e.key === "Home" ? [0, -ci] : e.key === "End" ? [0, years.length - 1 - ci] : null);
+ if (!k) return;
+ e.preventDefault();
+ const nr = Math.max(0, Math.min(rows.length - 1, ri + k[0]));
+ const nc = Math.max(0, Math.min(years.length - 1, ci + k[1]));
+ setFocus([nr, nc]);
+ grid.current?.querySelector<HTMLElement>(`td[data-cell="${nr}:${nc}"]`)?.focus();
+ };
+
+ const total = (r: CoverageRow) => (measure === "held" ? r.held?.total : r.published.total);
+
+ return (
+ <>
+ <div className="flex flex-wrap items-center gap-x-3.5 gap-y-1.5 py-3.5 text-[12px] text-muted">
+ <span role="group" aria-label="Measure" className="inline-flex gap-1">
+ {(["held", "published"] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ aria-pressed={measure === m}
+ disabled={m === "held" && data.held.via === "none"}
+ className={badgeVariants({ variant: measure === m ? "on" : "neutral", size: "md" })}
+ onClick={() => setMeasure(m)}
+ >
+ {m === "held" ? "Videos held" : "Videos published"}
+ </button>
+ ))}
+ </span>
+ <span className="inline-flex items-center gap-[2px]" aria-label="Ramp">
+ <span className="mr-1 font-mono text-[10.5px]">1</span>
+ {RAMP.slice(1).map((c, i) => (
+ <i key={i} className={cn("inline-block h-3 w-[30px] rounded-[2px]", c)} />
+ ))}
+ <span className="ml-1 font-mono text-[10.5px]">1,200+</span>
+ </span>
+ {measure === "held" && (
+ <span>
+ <i className="mr-1 inline-block h-0 w-3.5 border-b-2 border-doubt align-[3px]" />
+ gap over {data.gapDays} days that year
+ </span>
+ )}
+ <span>— nothing {measure === "held" ? "held" : "published"}</span>
+ <button type="button" aria-pressed={table} className={cn(buttonVariants({ variant: "outline", size: "sm" }), "ml-auto")} onClick={() => setTable((t) => !t)}>
+ {table ? "Heatmap" : "Table"}
+ </button>
+ </div>
+
+ <p data-held-age="" className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span>
+ Held counts from <span data-held-ago="">{ago(now - data.held.at)}</span>
+ {data.held.cached ? " (kept 5 min)" : ""}
+ {data.held.note ? (
+ <span data-held-note={data.held.via}> · {data.held.note}</span>
+ ) : null}
+ </span>
+ <button type="button" disabled={!hydrated || refreshing} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={refresh}>
+ {refreshing ? "Refreshing…" : "Refresh"}
+ </button>
+ {refreshError && (
+ <span role="alert" className="text-reject-text">
+ {refreshError}
+ </span>
+ )}
+ </p>
+
+ {rows.length === 0 ? (
+ <p className="text-[13px] text-text-2">This source lists no channels.</p>
+ ) : table ? (
+ <Table aria-label="Inventory table">
+ <thead>
+ <tr>
+ <TH>Channel</TH>
+ <TH>Year</TH>
+ <TH className="text-right">Held</TH>
+ <TH className="text-right">Published</TH>
+ <TH className="text-right">Transcripts</TH>
+ <TH className="text-right">Captions</TH>
+ <TH>Gap</TH>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.flatMap((r) =>
+ years
+ .filter((y) => r.held?.byYear[y] || r.published.byYear[y])
+ .map((y) => (
+ <tr key={`${r.key}-${y}`}>
+ <TD>{r.name}</TD>
+ <TD numeric className="text-left">
+ {y}
+ </TD>
+ <TD numeric>{r.held ? nf.format(r.held.byYear[y] ?? 0) : "—"}</TD>
+ <TD numeric>{nf.format(r.published.byYear[y] ?? 0)}</TD>
+ <TD numeric>{r.tracks?.[y] ? r.tracks[y].transcript : "—"}</TD>
+ <TD numeric>{r.tracks?.[y] ? r.tracks[y].captions : "—"}</TD>
+ <TD>{r.held?.gapYears.includes(y) ? "over 60 days" : ""}</TD>
+ </tr>
+ )),
+ )}
+ </tbody>
+ </Table>
+ ) : (
+ <div ref={host} className="relative overflow-auto pb-2" onMouseLeave={() => setTip(null)}>
+ <table ref={grid} aria-label="Inventory" data-heat="" className="border-separate border-spacing-[2px] text-[12px]">
+ <thead>
+ <tr>
+ <th />
+ {years.map((y) => (
+ <th key={y} scope="col" className="px-1 py-0.5 text-center font-mono text-[11px] font-medium text-muted">
+ {y.slice(2)}
+ </th>
+ ))}
+ <th scope="col" className="pl-2.5 text-right font-mono text-[11px] font-medium text-meter">
+ {measure}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r, ri) => (
+ <tr key={r.key} data-row={r.slug}>
+ <th scope="row" className="whitespace-nowrap pr-3.5 text-left text-[12.5px] font-medium text-text-2">
+ {r.name}
+ {r.localOnly && <span className="ml-1.5 font-mono text-[9.5px] uppercase tracking-wider text-muted">local only</span>}
+ </th>
+ {years.map((y, ci) => {
+ const n = countOf(r, measure, y);
+ const gap = measure === "held" && r.held?.gapYears.includes(y);
+ const t = tipOf(r, measure, y);
+ return (
+ <td
+ key={y}
+ data-cell={`${ri}:${ci}`}
+ data-year={y}
+ data-n={n}
+ data-gap={gap ? "" : undefined}
+ data-tip={t}
+ aria-label={t}
+ tabIndex={focus[0] === ri && focus[1] === ci ? 0 : -1}
+ onMouseEnter={(e) => showTip(e.currentTarget)}
+ onFocus={(e) => {
+ setFocus([ri, ci]);
+ showTip(e.currentTarget);
+ }}
+ onBlur={() => setTip(null)}
+ onKeyDown={(e) => move(e, ri, ci)}
+ className={cn(
+ "h-[34px] w-[58px] rounded-[2px] text-center font-mono text-[11px] tabular-nums outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-signal",
+ RAMP[binOf(n)],
+ gap && (n ? "shadow-[inset_0_-2px_0_var(--doubt)]" : "shadow-[inset_0_0_0_1px_var(--seam),inset_0_-2px_0_var(--doubt)]"),
+ )}
+ >
+ {n ? nf.format(n) : "—"}
+ </td>
+ );
+ })}
+ <th className="pl-2.5 text-right font-mono text-[11px] font-medium text-meter">{total(r) != null ? nf.format(total(r)!) : "—"}</th>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {tip && (
+ <div role="tooltip" data-heat-tip="" className="pointer-events-none absolute z-10 whitespace-nowrap rounded-[3px] border border-seam-2 bg-panel-2 px-2 py-1.5 text-[12px] text-text" style={{ left: tip.x, top: tip.y }}>
+ {tip.text}
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/umtool/components/research/Facets.tsx b/umtool/components/research/Facets.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { cn } from "@/lib/utils";
+import type { Facets as FacetCounts } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The facets column (canvas `.facets`): the year histogram, channels, the
+// text (our transcription or the platform's captions), the state on the
+// platform, and the reading log's three piles. Every count is MEASUREMENT, so
+// it is Meter; a facet is a button that narrows the list on this page -- the
+// search is not run again, and the header says "showing N of M".
+// ---------------------------------------------------------------------------
+
+export type FacetPick = { year?: string; channel?: string; track?: string; state?: string; reading?: "read" | "skipped" | "unread" };
+
+const TRACK_WORD: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "not known", post: "posts" };
+
+function Row({ label, n, of, on, onClick }: { label: string; n: number; of?: number; on: boolean; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ aria-label={`${label}: ${n}`}
+ aria-pressed={on}
+ onClick={onClick}
+ className={cn(
+ "mb-1.5 grid w-full grid-cols-[minmax(0,1fr)_auto] gap-x-2 gap-y-0.5 rounded-[2px] text-left text-[12px] text-text-2 hover:text-text",
+ on && "text-text underline decoration-muted underline-offset-[3px]",
+ )}
+ >
+ <span className="truncate">{label}</span>
+ <span className="font-mono text-[11.5px] text-meter">{n}</span>
+ {of !== undefined && (
+ <span className="col-span-2 h-[3px] rounded-r-sm bg-seam" aria-hidden="true">
+ <i className="block h-full rounded-r-sm bg-meter" style={{ width: `${of > 0 ? Math.max(4, (n / of) * 100) : 0}%` }} />
+ </span>
+ )}
+ </button>
+ );
+}
+
+export default function Facets({
+ facets,
+ reading,
+ pick,
+ onPick,
+}: {
+ facets: FacetCounts;
+ reading: { read: number; skipped: number; unread: number };
+ pick: FacetPick;
+ onPick: (p: FacetPick) => void;
+}) {
+ const peak = Math.max(1, ...facets.years.map((y) => y.n));
+ const chMax = Math.max(1, ...facets.channels.map((c) => c.n));
+ const set = <K extends keyof FacetPick>(k: K, v: FacetPick[K]) => onPick({ ...pick, [k]: pick[k] === v ? undefined : v });
+ const tracks = Object.entries(facets.tracks).sort((a, b) => b[1] - a[1]);
+ const states = Object.entries(facets.states).sort((a, b) => b[1] - a[1]);
+ return (
+ <aside aria-label="Facets" data-facets="" className="min-h-0 overflow-auto border-l border-seam pb-4 pl-4 pr-[22px] pt-1">
+ {facets.years.length > 0 && (
+ <>
+ <span className="micro mb-2 mt-3 block">Year</span>
+ <div role="group" aria-label="Recordings per year" className="grid h-16 items-end gap-[3px]" style={{ gridTemplateColumns: `repeat(${facets.years.length}, minmax(0, 1fr))` }}>
+ {facets.years.map((y) => (
+ <button
+ key={y.year}
+ type="button"
+ aria-pressed={pick.year === y.year}
+ aria-label={`${y.year}: ${y.n} ${y.n === 1 ? "recording" : "recordings"}`}
+ disabled={y.n === 0}
+ onClick={() => set("year", y.year)}
+ data-year={y.year}
+ className="flex h-full min-w-0 flex-col items-center justify-end disabled:opacity-100"
+ >
+ <em className="mb-0.5 font-mono text-[9.5px] not-italic text-text-2">{y.n}</em>
+ {y.n > 0 ? (
+ <i className={cn("block w-full rounded-t-[2px] bg-meter", pick.year === y.year && "outline outline-2 outline-offset-1 outline-text")} style={{ height: `${(y.n / peak) * 70}%` }} />
+ ) : (
+ <i className="block w-full border-b border-seam-2" />
+ )}
+ <span className="mt-[3px] font-mono text-[9.5px] text-muted-2">{y.year.slice(2)}</span>
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Channel</span>
+ {facets.channels.slice(0, 8).map((c) => (
+ <Row key={c.slug} label={c.name} n={c.n} of={chMax} on={pick.channel === c.slug} onClick={() => set("channel", c.slug)} />
+ ))}
+ {facets.channels.length > 8 && (
+ <div className="mb-1.5 grid grid-cols-[minmax(0,1fr)_auto] gap-x-2 text-[12px] text-muted-2">
+ <span>{facets.channels.length - 8} more</span>
+ <span className="font-mono text-[11.5px] text-meter">{facets.channels.slice(8).reduce((n, c) => n + c.n, 0)}</span>
+ </div>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Text</span>
+ {tracks.map(([t, n]) => (
+ <Row key={t} label={TRACK_WORD[t] ?? t} n={n} on={pick.track === t} onClick={() => set("track", t)} />
+ ))}
+
+ {states.length > 1 && (
+ <>
+ <span className="micro mb-2 mt-3 block">State</span>
+ {states.map(([s, n]) => (
+ <Row key={s} label={VIDEO_STATE_LABELS[s as VideoState] ?? s} n={n} on={pick.state === s} onClick={() => set("state", s)} />
+ ))}
+ </>
+ )}
+
+ <span className="micro mb-2 mt-3 block">Reading</span>
+ {(["read", "skipped", "unread"] as const).map((r) => (
+ <Row key={r} label={r} n={reading[r]} on={pick.reading === r} onClick={() => set("reading", r)} />
+ ))}
+ </aside>
+ );
+}
diff --git a/umtool/components/research/Reader.tsx b/umtool/components/research/Reader.tsx
@@ -0,0 +1,179 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { clock } from "@/components/ui/clock";
+import { EmptyState } from "@/components/ui/empty-state";
+import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane";
+import { isoDate } from "@/lib/research/facets.mjs";
+import { researchMediaApi } from "@/lib/research/hrefs";
+import type { FetchAnswer, LocalMedia, WindowResponse } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The reader on the Research page (canvas `.paper`): the transcript around the
+// lit hit, on the pale surface, the hit's cue lit among dim ones; ± widens or
+// narrows the window; the footer's actions name what they do.
+//
+// Copy citation the house format: "quote" [title @ m:ss](moment link)
+// Play from m:ss a file umtool can play from this machine (a fetched
+// window, a kept source or its audio), from the cite
+// Fetch clip the seconds behind the cite, through the editor's
+// fetch-window route, as the MCP's fetch_clip asks
+// ---------------------------------------------------------------------------
+
+const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "text of unknown kind" };
+
+/** The best local file for a second: a window holding it, else a whole source, else audio. */
+export function playable(media: LocalMedia[], at: number): LocalMedia | null {
+ const windows = media.filter((m) => m.kind === "window" && m.from !== undefined && m.to !== undefined && m.from <= at && at <= m.to);
+ windows.sort((a, b) => a.to! - a.from! - (b.to! - b.from!));
+ return windows[0] ?? media.find((m) => m.kind === "source") ?? media.find((m) => m.kind === "audio") ?? null;
+}
+
+export default function Reader({
+ source,
+ win,
+ error,
+ loading,
+ span,
+ onSpan,
+ copied,
+ onCopy,
+ fetchState,
+ onFetch,
+}: {
+ source: string;
+ win: WindowResponse | null;
+ error: string | null;
+ loading: boolean;
+ span: number;
+ onSpan: (s: number) => void;
+ copied: boolean;
+ onCopy: () => void;
+ fetchState: FetchAnswer | { state: "asking" } | null;
+ onFetch: () => void;
+}) {
+ const [playing, setPlaying] = useState<LocalMedia | null>(null);
+ const video = useRef<HTMLVideoElement>(null);
+ useEffect(() => setPlaying(null), [win?.videoId, win?.at]);
+ // The cited cue in the middle of the window, wherever the window starts.
+ useEffect(() => {
+ const id = requestAnimationFrame(() => {
+ const lit = document.querySelector<HTMLElement>("[data-reader] .reader-cue[data-lit]");
+ const box = lit?.closest<HTMLElement>(".overflow-auto");
+ if (!lit || !box) return;
+ const l = lit.getBoundingClientRect();
+ const b = box.getBoundingClientRect();
+ box.scrollTop += l.top - b.top - b.height / 2 + l.height / 2;
+ });
+ return () => cancelAnimationFrame(id);
+ }, [win?.videoId, win?.at, win?.span]);
+
+ if (!win) {
+ return (
+ <aside aria-label="Reader" data-reader="" className="reader">
+ <div className="flex flex-1 items-center justify-center px-6">
+ {error ? (
+ <p role="alert" className="text-[12.5px] text-reader-ink">
+ {error}
+ </p>
+ ) : (
+ <EmptyState title={loading ? "Reading…" : "Light a line to read it here"} className="text-reader-dim [&_p]:text-reader-2" />
+ )}
+ </div>
+ </aside>
+ );
+ }
+
+ if (win.kind === "post") {
+ return (
+ <ReaderPane
+ source={win.title}
+ byline={[win.channelName, isoDate(win.uploadDate), win.localOnly ? "local only" : null]}
+ footer={
+ <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
+ {copied ? "Copied" : "Copy citation"}
+ </button>
+ }
+ fine={win.citation.text}
+ >
+ <p>{win.text}</p>
+ </ReaderPane>
+ );
+ }
+
+ const file = playable(win.media, win.at);
+ const offset = playing?.kind === "window" ? win.at - (playing.from ?? 0) : win.at;
+ const state = VIDEO_STATE_LABELS[win.state as VideoState] ?? win.state;
+ const fetching = fetchState && (fetchState.state === "asking" || fetchState.state === "queued");
+ return (
+ <ReaderPane
+ key={`${win.videoId}@${win.at}:${win.span}`}
+ source={win.title}
+ byline={[
+ win.channelName,
+ `uploaded ${isoDate(win.uploadDate)}`,
+ state.toLowerCase(),
+ <span key="t" className="font-mono text-[11.5px]">
+ {TRACK[win.track] ?? win.track} · {win.cueCount.toLocaleString("en-US")} cues
+ </span>,
+ win.localOnly ? "local only" : null,
+ ]}
+ cite={win.duration > 0 ? { at: win.at, duration: win.duration } : undefined}
+ note={win.trackLabel ? `The hit is in the ${win.trackLabel}` : undefined}
+ cues={win.cues.map((c, i) => ({ t: c.t, text: c.text, lit: i === win.lit, id: `cue-${c.t}` }))}
+ footer={
+ <>
+ {playing && (
+ <video
+ ref={video}
+ data-player=""
+ controls
+ autoPlay
+ className="mb-1 max-h-[180px] w-full basis-full rounded-[2px] bg-black"
+ src={researchMediaApi({ source, channel: win.channelSlug, video: win.videoId, file: playing.name })}
+ onLoadedMetadata={(e) => {
+ e.currentTarget.currentTime = Math.max(0, offset);
+ }}
+ />
+ )}
+ <button type="button" className={paperButtonVariants({ variant: "go" })} onClick={onCopy}>
+ {copied ? "Copied" : "Copy citation"}
+ </button>
+ {file && (
+ <button type="button" className={paperButtonVariants()} onClick={() => setPlaying(file)}>
+ Play from {clock(win.at)}
+ </button>
+ )}
+ {(!file || file.kind !== "window") && (
+ <button type="button" className={paperButtonVariants()} disabled={!!fetching} onClick={onFetch}>
+ {fetching ? "Fetching…" : "Fetch clip"}
+ </button>
+ )}
+ <span className="ml-auto inline-flex items-center gap-1">
+ <button type="button" aria-label="Narrower window" className={paperButtonVariants()} disabled={span <= 15} onClick={() => onSpan(Math.max(15, Math.round(span / 2)))}>
+ −
+ </button>
+ <button type="button" aria-label="Wider window" className={paperButtonVariants()} disabled={span >= 600} onClick={() => onSpan(Math.min(600, span * 2))}>
+ +
+ </button>
+ </span>
+ {fetchState && fetchState.state !== "asking" && (
+ <span data-fetch-state={fetchState.state} role={fetchState.state === "failed" ? "alert" : "status"} className="basis-full text-[12px] text-reader-2">
+ {fetchState.state === "ready"
+ ? `Clip ${fetchState.cached ? "already held" : "fetched"}${fetchState.from !== undefined ? ` · ${clock(fetchState.from)}–${clock(fetchState.to ?? fetchState.from)}` : ""}`
+ : fetchState.state === "queued"
+ ? `The editor is fetching it (job ${fetchState.job}, ${fetchState.status})`
+ : `Fetch clip: ${fetchState.message}`}
+ </span>
+ )}
+ </>
+ }
+ fine={
+ <>
+ ± {win.span} s · <span data-citation="">{win.citation.text}</span>
+ </>
+ }
+ />
+ );
+}
diff --git a/umtool/components/research/ResearchView.tsx b/umtool/components/research/ResearchView.tsx
@@ -0,0 +1,514 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { EmptyState } from "@/components/ui/empty-state";
+import { KeyHint } from "@/components/ui/kbd";
+import type { LitDetail } from "@/components/ui/lit-list";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { yearOf } from "@/lib/research/facets.mjs";
+import { researchArchiveHref, researchHref, researchScopeApi, researchWindowApi } from "@/lib/research/hrefs";
+import { parseAsk } from "@/lib/research/query.mjs";
+import type { FetchAnswer, LogMarks, ResultHit, Scope, ScopeSummary, SearchResponse, SourceOption, WindowResponse } from "@/lib/research/types";
+import Facets, { type FacetPick } from "./Facets";
+import Reader from "./Reader";
+import Results, { parseLineId } from "./Results";
+import ScopeBar from "./ScopeBar";
+
+// ---------------------------------------------------------------------------
+// RESEARCH (plans/umtool-redesign.md, "Research, first-class"; canvas
+// `#view-research`): the ask bar, the scope and what it holds, the results as
+// lit lines grouped by recording with an honest header, the facets, the
+// reader, and the reading log.
+//
+// A search is ONE call for the whole match set (POST /api/research/search ->
+// enumerate_matches' scan); the page never pages the engine. Facets and "show
+// more" narrow or extend what is DRAWN, never what was searched. The query and
+// the scope live in the URL (replaceState), so a search is a link.
+//
+// Keys: j/k lines (the list), r read · s skip · u unread (the lit recording,
+// then the next), c copy citation, / the ask bar.
+// ---------------------------------------------------------------------------
+
+const PAGE = 200;
+const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+
+type Lit = { key: string; i: number };
+
+const nf = new Intl.NumberFormat("en-US");
+
+async function json<T>(r: Response): Promise<T> {
+ const body = await r.json().catch(() => null);
+ if (!r.ok) throw new Error((body as { error?: string } | null)?.error ?? `HTTP ${r.status}`);
+ return body as T;
+}
+
+function sameScope(a: Scope, b: Scope) {
+ return JSON.stringify({ ...a, channels: [...(a.channels ?? [])].sort() }) === JSON.stringify({ ...b, channels: [...(b.channels ?? [])].sort() });
+}
+
+export default function ResearchView({
+ sources,
+ initialQuery,
+ initialScope,
+ initialSummary,
+ initialSummaryError,
+}: {
+ sources: SourceOption[];
+ initialQuery: string;
+ initialScope: Scope;
+ initialSummary: ScopeSummary | null;
+ initialSummaryError: string | null;
+}) {
+ const hydrated = useHydrated();
+ const askRef = useRef<HTMLInputElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ const [ask, setAsk] = useState(initialQuery);
+ const [scope, setScope] = useState<Scope>(initialScope);
+ const [summary, setSummary] = useState<ScopeSummary | null>(initialSummary);
+ const [summaryError, setSummaryError] = useState<string | null>(initialSummaryError);
+ const [summaryLoading, setSummaryLoading] = useState(false);
+ const [res, setRes] = useState<SearchResponse | null>(null);
+ const [ranScope, setRanScope] = useState<Scope | null>(null);
+ const [searching, setSearching] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [marks, setMarks] = useState<LogMarks>({});
+ const [logError, setLogError] = useState<string | null>(null);
+ const [pick, setPick] = useState<FacetPick>({});
+ const [shown, setShown] = useState(PAGE);
+ const [lit, setLit] = useState<Lit | null>(null);
+ const [span, setSpan] = useState(30);
+ const [win, setWin] = useState<WindowResponse | null>(null);
+ const [winError, setWinError] = useState<string | null>(null);
+ const [winLoading, setWinLoading] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [fetchState, setFetchState] = useState<FetchAnswer | { state: "asking" } | null>(null);
+
+ // ── the scope preview, re-read when the scope changes ──
+ const firstScope = useRef(true);
+ useEffect(() => {
+ if (firstScope.current) {
+ firstScope.current = false;
+ return;
+ }
+ const ctl = new AbortController();
+ setSummaryLoading(true);
+ const t = setTimeout(() => {
+ fetch(researchScopeApi(scope), { signal: ctl.signal, cache: "no-store" })
+ .then((r) => json<ScopeSummary>(r))
+ .then((s) => {
+ setSummary(s);
+ setSummaryError(null);
+ })
+ .catch((e: Error) => {
+ if (e.name !== "AbortError") setSummaryError(e.message);
+ })
+ .finally(() => setSummaryLoading(false));
+ }, 200);
+ return () => {
+ clearTimeout(t);
+ ctl.abort();
+ };
+ }, [scope]);
+
+ // ── search: once, the whole set ──
+ const run = useCallback(
+ async (q: string, s: Scope, fresh = false) => {
+ const parsed = parseAsk(q);
+ if (parsed.error) {
+ setError(parsed.error);
+ return;
+ }
+ setSearching(true);
+ setError(null);
+ try {
+ const r = await json<SearchResponse>(
+ await fetch("/api/research/search", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ q,
+ source: s.source,
+ channels: s.channels,
+ from: s.dateFrom,
+ to: s.dateTo,
+ states: s.states,
+ media: s.mediaType,
+ posts: s.posts,
+ fresh,
+ }),
+ }),
+ );
+ setRes(r);
+ setRanScope(s);
+ setMarks(r.log.marks);
+ setLogError(r.log.error ?? null);
+ setPick({});
+ setShown(PAGE);
+ setLit(null);
+ setWin(null);
+ window.history.replaceState(null, "", researchHref({ q, ...s, source: r.source.handle === sources[0]?.handle ? undefined : r.source.handle }));
+ // The search counted the scope's tracks: the preview can say so now.
+ fetch(researchScopeApi(s), { cache: "no-store" })
+ .then((x) => json<ScopeSummary>(x))
+ .then(setSummary)
+ .catch(() => {});
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setSearching(false);
+ }
+ },
+ [sources],
+ );
+
+ // A link with ?q= runs on arrival.
+ const ranInitial = useRef(false);
+ useEffect(() => {
+ if (ranInitial.current || !initialQuery) return;
+ ranInitial.current = true;
+ void run(initialQuery, initialScope);
+ }, [initialQuery, initialScope, run]);
+
+ // ── what is drawn: the facets narrow it ──
+ const visible = useMemo(() => {
+ if (!res) return [];
+ return res.hits.filter((h) => {
+ if (pick.year && yearOf(h.uploadDate) !== pick.year) return false;
+ if (pick.channel && h.channelSlug !== pick.channel) return false;
+ if (pick.track && h.track !== pick.track) return false;
+ if (pick.state && h.state !== pick.state) return false;
+ if (pick.reading && (marks[h.key]?.state ?? "unread") !== pick.reading) return false;
+ return true;
+ });
+ }, [res, pick, marks]);
+ const drawn = visible.slice(0, shown);
+ const reading = useMemo(() => {
+ const t = { read: 0, skipped: 0, unread: 0 };
+ for (const h of res?.hits ?? []) t[marks[h.key]?.state ?? "unread"]++;
+ return t;
+ }, [res, marks]);
+ const byKey = useMemo(() => new Map((res?.hits ?? []).map((h) => [h.key, h])), [res]);
+ const litHit: ResultHit | null = lit ? (byKey.get(lit.key) ?? null) : null;
+ const litSnip = litHit && lit ? (litHit.snippets[lit.i] ?? null) : null;
+
+ const onLight = useCallback((d: LitDetail) => {
+ const p = parseLineId(d.id);
+ if (p) setLit(p);
+ }, []);
+
+ // ── the reader follows the lit line ──
+ useEffect(() => setSpan(30), [lit?.key, lit?.i]);
+ useEffect(() => {
+ setFetchState(null);
+ setCopied(false);
+ }, [lit?.key, lit?.i]);
+ useEffect(() => {
+ if (!res || !litHit || !litSnip) return;
+ const ctl = new AbortController();
+ setWinLoading(true);
+ setWinError(null);
+ const t = setTimeout(() => {
+ fetch(
+ researchWindowApi({
+ source: res.source.handle,
+ channel: litHit.channelKey,
+ video: litHit.videoId,
+ t: litSnip.t,
+ span,
+ ...(litSnip.track ? { track: litSnip.track } : {}),
+ kind: litHit.kind,
+ }),
+ { signal: ctl.signal, cache: "no-store" },
+ )
+ .then((r) => json<WindowResponse>(r))
+ .then(setWin)
+ .catch((e: Error) => {
+ if (e.name !== "AbortError") {
+ setWin(null);
+ setWinError(e.message);
+ }
+ })
+ .finally(() => setWinLoading(false));
+ }, 120);
+ return () => {
+ clearTimeout(t);
+ ctl.abort();
+ };
+ }, [res, litHit, litSnip, span]);
+
+ // ── the reading log ──
+ const markLit = useCallback(
+ async (state: "read" | "skipped" | "unread") => {
+ if (!res || !litHit) return;
+ const key = litHit.key;
+ setMarks((m) => {
+ const next = { ...m };
+ if (state === "unread") delete next[key];
+ else next[key] = { state, at: new Date().toISOString() };
+ return next;
+ });
+ // On to the next recording, so r r r walks the list.
+ if (state !== "unread") {
+ const sections = [...(listRef.current?.querySelectorAll<HTMLElement>("[data-hit]") ?? [])];
+ const at = sections.findIndex((s) => s.dataset.hit === key);
+ const next = sections[at + 1]?.querySelector<HTMLElement>("[data-lit-line]");
+ if (next) {
+ next.focus({ preventScroll: true });
+ next.scrollIntoView({ block: "nearest" });
+ }
+ }
+ try {
+ const r = await json<{ marks: LogMarks }>(
+ await fetch("/api/research/log", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ session: res.session,
+ key,
+ state,
+ query: res.query,
+ scope: { source: res.source.handle, ...(ranScope ?? {}) },
+ }),
+ }),
+ );
+ setMarks(r.marks);
+ setLogError(null);
+ } catch (e) {
+ setLogError((e as Error).message);
+ }
+ },
+ [res, litHit, ranScope],
+ );
+
+ const copy = useCallback(async () => {
+ // Only the lit hit's own window: never a citation left from the line before.
+ if (!win || !litHit || win.videoId !== litHit.videoId) return;
+ try {
+ await navigator.clipboard.writeText(win.citation.text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1600);
+ } catch {
+ window.prompt("Copy the citation", win.citation.text);
+ }
+ }, [win, litHit]);
+
+ // ── fetch clip, through the editor, polled by job ──
+ const fetchClip = useCallback(async () => {
+ if (!res || !litHit || !win) return;
+ const cue = win.cues[win.lit];
+ const start = cue?.t ?? win.at;
+ const end = cue ? Math.max(cue.end, start + 1) : win.at + 5;
+ setFetchState({ state: "asking" });
+ try {
+ let a = await json<FetchAnswer>(
+ await fetch("/api/research/fetch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ source: res.source.handle,
+ channel: litHit.channelKey,
+ video: litHit.videoId,
+ start,
+ end,
+ reason: `umtool research: "${res.query}" @ ${win.citation.text.match(/@ ([\d:]+)\]/)?.[1] ?? start}`,
+ }),
+ }),
+ );
+ setFetchState(a);
+ for (let n = 0; a.state === "queued" && n < 300; n++) {
+ await new Promise((r) => setTimeout(r, 1500));
+ a = await json<FetchAnswer>(
+ await fetch("/api/research/fetch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ job: a.job }) }),
+ );
+ setFetchState(a);
+ }
+ if (a.state === "ready") {
+ // The clip is in the corpus now: the window's media list offers it.
+ const w = await json<WindowResponse>(
+ await fetch(researchWindowApi({ source: res.source.handle, channel: litHit.channelKey, video: litHit.videoId, t: win.at, span: win.span }), { cache: "no-store" }),
+ );
+ setWin(w);
+ setFetchState(a);
+ }
+ } catch (e) {
+ setFetchState({ state: "failed", message: (e as Error).message });
+ }
+ }, [res, litHit, win]);
+
+ // ── keys ──
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return;
+ if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return;
+ if (e.key === "/") {
+ e.preventDefault();
+ askRef.current?.focus();
+ askRef.current?.select();
+ } else if (e.key === "r") void markLit("read");
+ else if (e.key === "s") void markLit("skipped");
+ else if (e.key === "u") void markLit("unread");
+ else if (e.key === "c") void copy();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [markLit, copy]);
+
+ const stale = !!res && !!ranScope && !sameScope(ranScope, scope);
+ const filtered = visible.length !== (res?.hits.length ?? 0);
+ const parsedAsk = parseAsk(ask);
+
+ return (
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(360px,34%)]">
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <form
+ role="search"
+ className="grid grid-cols-[minmax(0,1fr)_auto] gap-2.5 px-7 pb-2.5 pt-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void run(ask, scope, true);
+ }}
+ >
+ <label className="flex items-center gap-2.5 rounded-[3px] border border-seam-2 bg-panel px-3 py-2 focus-within:border-muted">
+ <span aria-hidden="true" className="font-mono text-muted-2">
+ ⌕
+ </span>
+ <input
+ ref={askRef}
+ name="q"
+ aria-label="Ask"
+ autoComplete="off"
+ spellCheck={false}
+ value={ask}
+ onChange={(e) => setAsk(e.target.value)}
+ placeholder="what was said"
+ className="min-w-0 flex-1 bg-transparent text-[15px] text-text outline-none placeholder:text-muted-2"
+ />
+ <span className="whitespace-nowrap text-[12px] text-muted-2">
+ {ask.trim() && parsedAsk.kind !== "phrase" ? (parsedAsk.kind === "near" ? `near: ${parsedAsk.near?.n} words, one line` : "regex") : "phrase · regex /…/ · a near:8 b"}
+ </span>
+ </label>
+ <button type="submit" disabled={!hydrated || searching} className={buttonVariants({ variant: "outline", size: "md" })}>
+ {searching ? "Searching…" : "Search"} <kbd>↵</kbd>
+ </button>
+ </form>
+
+ <ScopeBar
+ sources={sources}
+ scope={scope}
+ summary={summary}
+ summaryError={summaryError}
+ loading={summaryLoading}
+ disabled={!hydrated}
+ onChange={(next) => setScope({ ...next, source: next.source || scope.source })}
+ />
+
+ {error && (
+ <p role="alert" className="px-7 pt-3 text-[13px] text-reject-text">
+ {error}
+ </p>
+ )}
+
+ {res && (
+ <div data-honest="" className="flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 pb-2.5 pt-3 text-[13px]">
+ <b className="font-semibold" data-total={res.total}>
+ {nf.format(res.total)} {res.total === 1 ? "recording" : "recordings"}
+ </b>
+ <span className="text-text-2">
+ {res.complete ? (
+ <span data-coverage="full">· full coverage</span>
+ ) : (
+ <span data-coverage="partial">
+ · <span className="text-doubt-text">Partial</span> — not reached: {res.notReached.length ? res.notReached.join(", ") : "—"}
+ {res.stopped ? ` · stopped in ${res.stopped.channel} at page ${res.stopped.page} of ${res.stopped.pages}` : ""}
+ </span>
+ )}{" "}
+ · {nf.format(res.matches)} lines · {nf.format(res.scanned.pages)} pages
+ {res.mirrorsFolded > 0 ? ` · ${res.mirrorsFolded} ${res.mirrorsFolded === 1 ? "mirror" : "mirrors"} folded` : ""}
+ {res.aliases.length ? ` · aliases: ${res.aliases.join(", ")}` : ""}
+ {filtered ? ` · showing ${visible.length} of ${res.total}` : ""}
+ </span>
+ {stale && <span className="text-[12px] text-doubt-text">The scope changed: Search to run it</span>}
+ <span data-reading="" className="ml-auto font-mono text-[12px] text-meter">
+ read {reading.read} of {res.total}
+ {reading.skipped ? ` · ${reading.skipped} skipped` : ""}
+ </span>
+ {res.warnings.length > 0 && <span className="basis-full text-[12px] text-doubt-text">{res.warnings.join("; ")}</span>}
+ {logError && (
+ <span role="alert" className="basis-full text-[12px] text-reject-text">
+ The reading log: {logError}
+ </span>
+ )}
+ </div>
+ )}
+
+ {res ? (
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_176px] gap-x-[22px] pl-7">
+ <div ref={listRef} className="min-h-0 overflow-auto pb-4 pr-1">
+ {drawn.length === 0 ? (
+ <EmptyState title={res.total === 0 ? `No recording says “${res.query}”` : "No recording matches these facets"}>
+ {res.total === 0 ? "in this scope" : null}
+ </EmptyState>
+ ) : (
+ <Results key={`${res.session}:${JSON.stringify(pick)}`} hits={drawn} marks={marks} onLight={onLight} />
+ )}
+ {visible.length > drawn.length && (
+ <div className="flex items-center gap-2.5 py-2.5 text-[12.5px] text-muted-2">
+ <span className="font-mono text-[12px] text-meter">{visible.length - drawn.length}</span> more recordings below
+ <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setShown((n) => n + PAGE)}>
+ Show {Math.min(PAGE, visible.length - drawn.length)} more
+ </button>
+ </div>
+ )}
+ {drawn.length > 0 && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 pt-3 text-[11.5px] text-muted-2">
+ <KeyHint keys={["j", "k"]}>line</KeyHint>
+ <KeyHint keys={["r"]}>read</KeyHint>
+ <KeyHint keys={["s"]}>skip</KeyHint>
+ <KeyHint keys={["u"]}>unread</KeyHint>
+ <KeyHint keys={["c"]}>copy citation</KeyHint>
+ <KeyHint keys={["/"]}>ask</KeyHint>
+ <span className="ml-auto">
+ {res.batches} {res.batches === 1 ? "batch" : "batches"} of 8 for a sweep
+ </span>
+ </div>
+ )}
+ </div>
+ <Facets facets={res.facets} reading={reading} pick={pick} onPick={(p) => setPick(p)} />
+ </div>
+ ) : (
+ <div className="flex-1 px-7 pt-6">
+ {searching ? (
+ <p className="text-[13px] text-text-2" role="status">
+ Searching the whole scope, once…
+ </p>
+ ) : (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-2">
+ <KeyHint keys={["/"]}>ask</KeyHint>
+ <KeyHint keys={["↵"]}>search</KeyHint>
+ <span>A search reads the whole scope once and says what it did not reach.</span>
+ <Link href={researchArchiveHref({ source: scope.source === sources[0]?.handle ? undefined : scope.source })} className="ink-link">
+ What the archive holds
+ </Link>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <Reader
+ source={res?.source.handle ?? scope.source}
+ win={litHit && win && win.videoId === litHit.videoId ? win : null}
+ error={winError}
+ loading={winLoading}
+ span={span}
+ onSpan={setSpan}
+ copied={copied}
+ onCopy={copy}
+ fetchState={fetchState}
+ onFetch={fetchClip}
+ />
+ </div>
+ );
+}
diff --git a/umtool/components/research/Results.tsx b/umtool/components/research/Results.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { memo } from "react";
+import { CiteThread } from "@/components/ui/cite-thread";
+import { LitList, type LitDetail } from "@/components/ui/lit-list";
+import { LitLine, LitOnly } from "@/components/ui/lit-line";
+import { isoDate } from "@/lib/research/facets.mjs";
+import { cn } from "@/lib/utils";
+import type { LogMarks, ResultHit, Snip } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The results (canvas `.rec` / `.rs`): one group per RECORDING (mirrors
+// folded into it), one lit line per matching line -- its timecode, the line
+// with the match marked, the recording's reading state -- and the cite thread
+// on the lit line only. The page's one global list: j/k from anywhere.
+// ---------------------------------------------------------------------------
+
+const TRACK: Record<string, string> = { transcript: "transcription", captions: "captions", unknown: "", post: "post" };
+
+function Marked({ s }: { s: Snip }) {
+ const out: React.ReactNode[] = [];
+ let at = 0;
+ for (const [a, b] of s.marks) {
+ if (a > at) out.push(s.text.slice(at, a));
+ out.push(
+ <mark key={a} className="bg-transparent text-inherit underline decoration-seam-2 underline-offset-[3px] group-data-[lit]:text-signal-text group-data-[lit]:decoration-signal">
+ {s.text.slice(a, b)}
+ </mark>,
+ );
+ at = b;
+ }
+ if (at < s.text.length) out.push(s.text.slice(at));
+ return <>{out}</>;
+}
+
+export const lineId = (key: string, i: number) => `${key}|${i}`;
+export const parseLineId = (id: string | null): { key: string; i: number } | null => {
+ if (!id) return null;
+ const bar = id.lastIndexOf("|");
+ return bar < 0 ? null : { key: id.slice(0, bar), i: Number(id.slice(bar + 1)) };
+};
+
+function Group({ h, mark }: { h: ResultHit; mark: "read" | "skipped" | undefined }) {
+ const state = mark ?? "unread";
+ return (
+ <section data-hit={h.key} className="mt-2.5" aria-label={h.title}>
+ <div className="flex items-baseline gap-2.5 pb-1 pt-1.5 text-[12.5px] text-text-2">
+ <b className="max-w-[62%] truncate font-medium text-text">{h.kind === "post" ? `Post by ${h.author ?? h.channelName}` : h.title}</b>
+ <span className="truncate whitespace-nowrap font-mono text-[11px] text-muted-2">
+ {h.channelName} · {isoDate(h.uploadDate)}
+ {h.mirrors?.length ? ` · ⧉ +${h.mirrors.length}` : ""}
+ {h.localOnly ? " · local only" : ""}
+ </span>
+ <span className="ml-auto whitespace-nowrap font-mono text-[11px] text-muted-2">
+ {[TRACK[h.track], h.state !== "available" ? h.state.replace("_", " ") : ""].filter(Boolean).join(" · ")}
+ </span>
+ </div>
+ {h.snippets.map((s, i) => (
+ <LitLine key={i} id={lineId(h.key, i)} className="group grid grid-cols-[62px_minmax(0,1fr)_auto] items-baseline gap-x-3 text-[13px]">
+ <span className="font-mono text-[11.5px] tabular-nums">{s.scope && s.t === 0 ? s.scope : h.kind === "post" ? "post" : s.clock}</span>
+ <span className="truncate">
+ <Marked s={s} />
+ </span>
+ <span data-read={state} className={cn("font-mono text-[11px]", state === "read" ? "text-meter" : "text-muted-2")}>
+ {state}
+ </span>
+ {h.duration && !s.scope ? (
+ <LitOnly className="col-[2/-1] mt-1">
+ <CiteThread at={s.t} duration={h.duration} />
+ </LitOnly>
+ ) : null}
+ </LitLine>
+ ))}
+ {h.matches > h.snippets.length && (
+ <div className="py-1 pl-5 text-[11.5px] text-muted-2">
+ +{h.matches - h.snippets.length} more {h.matches - h.snippets.length === 1 ? "line" : "lines"} in this recording
+ </div>
+ )}
+ </section>
+ );
+}
+
+const MemoGroup = memo(Group);
+
+export default function Results({
+ hits,
+ marks,
+ onLight,
+}: {
+ hits: ResultHit[];
+ marks: LogMarks;
+ onLight: (d: LitDetail) => void;
+}) {
+ return (
+ <LitList label="Results" global onLight={onLight}>
+ {hits.map((h) => (
+ <MemoGroup key={h.key} h={h} mark={marks[h.key]?.state} />
+ ))}
+ </LitList>
+ );
+}
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -0,0 +1,212 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { VIDEO_STATES, VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
+import { badgeVariants } from "@/components/ui/badge";
+import { controlClass } from "@/components/ui/field";
+import { cn } from "@/lib/utils";
+import type { Scope, ScopeSummary, SourceOption } from "@/lib/research/types";
+
+// ---------------------------------------------------------------------------
+// The scope chips and the "holds …" line under them (canvas `.scope`): which
+// corpus, which channels, which dates, states and types, posts or not -- and,
+// BEFORE anything runs, what that scope holds. A chip that opens is a native
+// <details>, so it works from the keyboard with no script of its own; one
+// click outside closes whichever is open.
+// ---------------------------------------------------------------------------
+
+const chip = (on: boolean) =>
+ cn(badgeVariants({ variant: on ? "on" : "neutral", size: "md" }), "cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden");
+
+const nf = new Intl.NumberFormat("en-US");
+const year = (d: string | null) => (d ? d.slice(0, 4) : "");
+const pct = (n: number, of: number) => (of > 0 ? `${Math.round((n / of) * 100)}%` : "0%");
+
+function Pop({ label, on, children, wide = false }: { label: React.ReactNode; on: boolean; children: React.ReactNode; wide?: boolean }) {
+ return (
+ <details className="relative" data-scope-pop="">
+ <summary className={chip(on)}>
+ {label} <span className="text-muted">▾</span>
+ </summary>
+ <div
+ className={cn(
+ "absolute left-0 z-30 mt-1 max-h-[340px] overflow-auto rounded-[3px] border border-seam-2 bg-panel p-2.5 text-[12.5px] shadow-[0_8px_24px_rgb(0_0_0/0.35)]",
+ wide ? "w-[300px]" : "w-[230px]",
+ )}
+ >
+ {children}
+ </div>
+ </details>
+ );
+}
+
+export default function ScopeBar({
+ sources,
+ scope,
+ summary,
+ summaryError,
+ loading,
+ disabled,
+ onChange,
+}: {
+ sources: SourceOption[];
+ scope: Scope;
+ summary: ScopeSummary | null;
+ summaryError: string | null;
+ loading: boolean;
+ disabled: boolean;
+ onChange: (next: Scope) => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ // One click outside closes an open chip.
+ useEffect(() => {
+ const close = (e: MouseEvent) => {
+ for (const d of ref.current?.querySelectorAll<HTMLDetailsElement>("details[open]") ?? []) {
+ if (!d.contains(e.target as Node)) d.open = false;
+ }
+ };
+ document.addEventListener("click", close);
+ return () => document.removeEventListener("click", close);
+ }, []);
+
+ const channels = summary?.channels ?? [];
+ const chosen = new Set(scope.channels ?? []);
+ const states = new Set(scope.states ?? []);
+ const toggle = (set: Set<string>, v: string) => {
+ const next = new Set(set);
+ if (next.has(v)) next.delete(v);
+ else next.add(v);
+ return [...next];
+ };
+ const source = sources.find((s) => s.handle === scope.source) ?? sources[0];
+ const tracks = summary?.tracks;
+ const trackTotal = tracks ? tracks.transcript + tracks.captions + tracks.unknown : 0;
+
+ return (
+ <div ref={ref} data-scope="" className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-seam px-7 pb-3">
+ <label className="sr-only" htmlFor="research-source">
+ Source
+ </label>
+ <select
+ id="research-source"
+ aria-label="Source"
+ disabled={disabled}
+ value={source?.handle ?? ""}
+ onChange={(e) => onChange({ source: e.target.value })}
+ className={cn(controlClass, "max-w-[260px] py-[3px] text-[12px]")}
+ >
+ {sources.map((s) => (
+ <option key={s.handle} value={s.handle}>
+ {s.label}
+ {s.detail ? ` · ${s.detail}` : ""}
+ </option>
+ ))}
+ </select>
+
+ <Pop
+ on={chosen.size > 0}
+ wide
+ label={chosen.size === 0 ? `All ${channels.length} channels` : chosen.size === 1 ? channels.find((c) => chosen.has(c.key))?.name ?? "1 channel" : `${chosen.size} channels`}
+ >
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">Channels</legend>
+ {channels.map((c) => (
+ <label key={c.key} className="flex items-baseline gap-2 text-text-2">
+ <input type="checkbox" checked={chosen.has(c.key)} onChange={() => onChange({ ...scope, channels: toggle(chosen, c.key) })} />
+ <span className="min-w-0 flex-1 truncate">{c.name}</span>
+ {c.localOnly && <span className="font-mono text-[10px] uppercase tracking-wider text-muted">local only</span>}
+ {c.videoCount != null && <span className="font-mono text-[11px] text-meter">{nf.format(c.videoCount)}</span>}
+ </label>
+ ))}
+ {chosen.size > 0 && (
+ <button type="button" className="mt-1 justify-self-start text-[12px] text-muted-2 hover:text-text" onClick={() => onChange({ ...scope, channels: [] })}>
+ Every channel
+ </button>
+ )}
+ </fieldset>
+ </Pop>
+
+ <Pop on={!!(scope.dateFrom || scope.dateTo)} label={scope.dateFrom || scope.dateTo ? `${scope.dateFrom ?? "…"} – ${scope.dateTo ?? "…"}` : "Any date"}>
+ <fieldset disabled={disabled} className="grid gap-2">
+ <legend className="micro mb-1">Uploaded</legend>
+ <label className="grid gap-0.5 text-text-2">
+ From
+ <input type="date" className={controlClass} value={scope.dateFrom ?? ""} onChange={(e) => onChange({ ...scope, dateFrom: e.target.value || undefined })} />
+ </label>
+ <label className="grid gap-0.5 text-text-2">
+ To
+ <input type="date" className={controlClass} value={scope.dateTo ?? ""} onChange={(e) => onChange({ ...scope, dateTo: e.target.value || undefined })} />
+ </label>
+ </fieldset>
+ </Pop>
+
+ <Pop on={states.size > 0} label={states.size === 0 ? "Any state" : [...states].map((s) => VIDEO_STATE_LABELS[s as VideoState] ?? s).join(", ")}>
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">On the platform</legend>
+ {VIDEO_STATES.map((s) => (
+ <label key={s} className="flex items-center gap-2 text-text-2">
+ <input type="checkbox" checked={states.has(s)} onChange={() => onChange({ ...scope, states: toggle(states, s) })} />
+ {VIDEO_STATE_LABELS[s]}
+ </label>
+ ))}
+ </fieldset>
+ </Pop>
+
+ <Pop on={!!scope.mediaType} label={scope.mediaType === "video" ? "Videos" : scope.mediaType === "livestream" ? "Streams" : "Videos and streams"}>
+ <fieldset disabled={disabled} className="grid gap-1">
+ <legend className="micro mb-1.5">Type</legend>
+ {([undefined, "video", "livestream"] as const).map((m) => (
+ <label key={m ?? "any"} className="flex items-center gap-2 text-text-2">
+ <input type="radio" name="research-media" checked={scope.mediaType === m} onChange={() => onChange({ ...scope, mediaType: m })} />
+ {m === "video" ? "Videos only" : m === "livestream" ? "Streams only" : "Both"}
+ </label>
+ ))}
+ </fieldset>
+ </Pop>
+
+ <button
+ type="button"
+ disabled={disabled}
+ aria-pressed={scope.posts === true}
+ className={chip(scope.posts === true)}
+ onClick={() => onChange({ ...scope, posts: !scope.posts })}
+ >
+ {scope.posts ? "Posts included" : "+ Posts"}
+ </button>
+
+ <div data-holds="" aria-live="polite" className="mt-1 basis-full font-mono text-[12px] text-muted">
+ {summaryError ? (
+ <span role="alert" className="text-reject-text">
+ {summaryError}
+ </span>
+ ) : !summary ? (
+ <span>{loading ? "reading the scope…" : "—"}</span>
+ ) : (
+ <>
+ holds{" "}
+ <b className="font-medium text-text-2">
+ {summary.selected} {summary.selected === 1 ? "channel" : "channels"} · {nf.format(summary.videos)} videos
+ {summary.first && summary.last ? ` · ${year(summary.first)}–${year(summary.last)}` : ""}
+ </b>
+ {tracks && trackTotal > 0 ? (
+ <span data-tracks="">
+ {" "}
+ · transcripts {pct(tracks.transcript, trackTotal)} · captions {pct(tracks.captions, trackTotal)}
+ {tracks.unknown > 0 ? ` · unknown ${pct(tracks.unknown, trackTotal)}` : ""}
+ {tracks.counted < tracks.of ? ` (${tracks.counted} of ${tracks.of} channels counted)` : ""}
+ </span>
+ ) : (
+ <span data-tracks-stale={summary.tracksStale ? "" : undefined}>
+ {" "}
+ · transcripts vs captions: {summary.tracksStale ?? "counted by the first full search"}
+ </span>
+ )}
+ {summary.aliases > 0 ? " · aliases on" : ""}
+ {summary.warnings.length > 0 && <span className="text-doubt-text"> · {summary.warnings.join("; ")}</span>}
+ {loading && <span className="text-muted-2"> · updating…</span>}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/ui/cite-thread.tsx b/umtool/components/ui/cite-thread.tsx
@@ -38,9 +38,10 @@ export function ReaderThread({ at, duration, className }: { at: number; duration
return (
<div className={cn("cite-thread mt-2.5", className)} role="img" aria-label={`Cited at ${clock(at)} of ${clock(duration)}`} data-cite-at={at}>
<i style={{ left: `${pct}%` }} />
- <span style={{ left: 0 }}>0:00</span>
- <span style={{ left: `calc(${pct}% - 22px)` }}>{clock(at)}</span>
- <span style={{ left: "auto", right: 0 }}>{clock(duration)}</span>
+ {/* The ends give way when the cite's own label would sit on them. */}
+ {pct >= 12 && <span style={{ left: 0 }}>0:00</span>}
+ <span style={{ left: `clamp(0px, calc(${pct}% - 22px), calc(100% - 56px))` }}>{clock(at)}</span>
+ {pct <= 80 && <span style={{ left: "auto", right: 0 }}>{clock(duration)}</span>}
</div>
);
}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -29,6 +29,7 @@ import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
+import { makeResearchFixture } from "./research-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1929,10 +1930,14 @@ makeMediaSurfacesFixture({ dest, articles: ARTICLES, manifest, cachedWindow: pat
// reports/delete-fixture (a project with two takes); article-delete.spec.ts
// writes its draft (omega) itself.
makeDeleteFixture({ dest, articles: ARTICLES, reports });
+// R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the
+// held channels its inventory reads on disk.
+const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
console.log(`fixture at ${dest}`);
console.log(` SITES_DIR=${SITES}`);
console.log(` ARTICLES_DIR=${ARTICLES}`);
+console.log(` TRANSCRIPT_LOCAL_DIR=${RESEARCH_PUBLIC} (research: 4 channels, 12 recordings)`);
console.log(` video-notes-fixture (generated, built, schedule + take alt), timeline-fixture (teaser, a01-a03, post p1)`);
if (planned) console.log(` planned clip (used in a build): ${planned}`);
console.log(` videos/: alpha (4 cuts, 3 variants), beta (2 cuts), deck (1 cut, 2 variants)`);
diff --git a/umtool/e2e/fixtures/research-enumerate.ts b/umtool/e2e/fixtures/research-enumerate.ts
@@ -0,0 +1,19 @@
+// The fixture's enumerate total, as the MCP gives it: `enumerate_matches`
+// through createCorpusTools (the in-process tools Claude Code's and the
+// generation jobs' agents call) over a composed public dir. research.spec.ts
+// runs it with tsx and holds the page's total and ids to it.
+//
+// tsx e2e/fixtures/research-enumerate.ts <public dir> <query> [<args json>]
+// -> {"total": N, "ids": [...], "partial": false}
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+
+const [dir, query, extra] = process.argv.slice(2);
+const tools = await createCorpusTools({ source: `local:${dir}` });
+try {
+ const text = await tools.call("enumerate_matches", { query, content_types: ["video"], ...(extra ? JSON.parse(extra) : {}) });
+ const total = Number(/(\d+) match\(es\);/.exec(text)?.[1] ?? "0");
+ const ids = [...text.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]);
+ process.stdout.write(`${JSON.stringify({ total, ids, partial: /COVERAGE PARTIAL/.test(text) })}\n`);
+} finally {
+ await tools.close();
+}
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/e2e/research.spec.ts b/umtool/e2e/research.spec.ts
@@ -0,0 +1,278 @@
+import { test, expect, type Page } from "@playwright/test";
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { RESEARCH_PHRASE } from "./fixtures/research-fixture.mjs";
+import { researchArchiveHref, researchHref } from "../lib/research/hrefs";
+import { nearRegex } from "../lib/research/query.mjs";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Research (plans/umtool-redesign.md, R1) on the fixture corpus
+// (e2e/fixtures/research-fixture.mjs: a composed public dir the server reads
+// as its local corpus, TRANSCRIPT_LOCAL_DIR): the scope preview before
+// anything runs, a search whose total and ids ARE enumerate_matches' over the
+// same corpus, the facets, the reading log round trip, the reader's window
+// with the hit lit, the citation in the house format, j/k, the clip fetched
+// through the editor (stubbed), and the archive inventory.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PUBLIC = path.join(FIXTURE, "research-public");
+const SESSIONS = path.join(FIXTURE, ".umtool", "research", "sessions");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+
+/** enumerate_matches through createCorpusTools, over the fixture's public dir. */
+function enumerated(query: string, extra: Record<string, unknown> = {}): { total: number; ids: string[]; partial: boolean } {
+ const r = spawnSync("pnpm", ["exec", "tsx", path.join(HERE, "fixtures", "research-enumerate.ts"), PUBLIC, query, JSON.stringify(extra)], {
+ cwd: path.join(HERE, ".."),
+ encoding: "utf8",
+ });
+ if (r.status !== 0) throw new Error(`research-enumerate failed: ${r.stderr}`);
+ return JSON.parse(r.stdout.trim().split("\n").pop()!);
+}
+
+const holds = (page: Page) => page.locator("[data-holds]");
+const honest = (page: Page) => page.locator("[data-honest]");
+const results = (page: Page) => page.getByRole("group", { name: "Results" });
+const reader = (page: Page) => page.getByRole("complementary", { name: "Reader" });
+const litLine = (page: Page) => results(page).locator("[data-lit-line][data-lit]");
+
+async function search(page: Page, q = RESEARCH_PHRASE) {
+ await page.getByRole("textbox", { name: "Ask" }).fill(q);
+ await page.getByRole("button", { name: /^Search/ }).click();
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+}
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, [researchHref(), researchArchiveHref(), "/api/research/scope", "/api/research/coverage"]);
+});
+
+test("the scope says what it holds before anything runs, and follows the chips", async ({ page }) => {
+ await page.goto(researchHref());
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("research");
+ await expect(holds(page)).toContainText("4 channels · 12 videos · 2019–2026");
+ // Nothing has been searched in this scope by this test yet.
+ await expect(page.locator("[data-honest]")).toHaveCount(0);
+
+ // One channel: its own count and span.
+ await page.getByText("All 4 channels").click();
+ await page.getByRole("checkbox", { name: /Night Desk/ }).check();
+ await expect(holds(page)).toContainText("1 channel · 3 videos · 2022–2025");
+ // A date window narrows the count (the summaries index), before any search.
+ await page.getByText("Any date").click();
+ await page.getByLabel("From").fill("2023-01-01");
+ await expect(holds(page)).toContainText("1 channel · 2 videos · 2023–2025");
+ // A Candace channel is offered on the local corpus, marked local only.
+ await page.locator("[data-scope] summary", { hasText: "Night Desk" }).click();
+ await expect(page.locator("[data-scope] label", { hasText: "Local Only Fixture" })).toContainText("local only");
+});
+
+test("a search finds exactly what enumerate_matches lists for the same scope: total, ids, order", async ({ page }) => {
+ const want = enumerated(RESEARCH_PHRASE);
+ expect(want.total).toBe(8);
+ await page.goto(researchHref());
+ await search(page);
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(want.total));
+ await expect(honest(page)).toContainText(`${want.total} recordings`);
+ await expect(honest(page).locator("[data-coverage]")).toHaveAttribute("data-coverage", "full");
+ await expect(honest(page)).toContainText("1 mirror folded");
+ const keys = await results(page).locator("[data-hit]").evaluateAll((els) => els.map((e) => (e as HTMLElement).dataset.hit!.split("/")[1]));
+ expect(keys).toEqual(want.ids);
+ // The search is a link: the query is in the address.
+ await expect(page).toHaveURL(/[?&]q=lighthouse\+budget/);
+
+ // The scope preview learned transcripts vs captions from the search.
+ await expect(holds(page).locator("[data-tracks]")).toContainText("transcripts 42% · captions 58%");
+
+ // One channel, the same parity.
+ const nd = enumerated(RESEARCH_PHRASE, { channels: ["night-desk"] });
+ await page.goto(researchHref({ q: RESEARCH_PHRASE, channels: ["night-desk"] }));
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(nd.total), { timeout: 30_000 });
+ expect(nd.ids).toEqual(["nd-2023"]);
+});
+
+test("the facets: years with their gaps, channels, text, state -- each narrows what is drawn", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ const facets = page.getByRole("complementary", { name: "Facets" });
+ const years = facets.getByRole("group", { name: "Recordings per year" }).getByRole("button");
+ await expect(years).toHaveCount(8);
+ await expect(facets.getByRole("button", { name: "2020: 0 recordings" })).toBeDisabled();
+ await expect(facets.getByRole("button", { name: "2022: 1 recording" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "Harbor Radio: 5" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "captions: 5" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "transcription: 3" })).toBeVisible();
+ await expect(facets.getByRole("button", { name: "Deleted: 1" })).toBeVisible();
+
+ await facets.getByRole("button", { name: "Night Desk: 1" }).click();
+ await expect(honest(page)).toContainText("showing 1 of 8");
+ await expect(results(page).locator("[data-hit]")).toHaveCount(1);
+ await facets.getByRole("button", { name: "Night Desk: 1" }).click();
+ await facets.getByRole("button", { name: "2024: 1 recording" }).click();
+ await expect(results(page).locator("[data-hit]")).toHaveCount(1);
+ await expect(results(page).locator("[data-hit]")).toHaveAttribute("data-hit", "harbor-radio/hr-2024a");
+});
+
+test("j/k walk the lines; the reader shows the lit hit's window with its cue lit", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await expect(litLine(page)).toHaveCount(1);
+ const first = await litLine(page).getAttribute("data-lit-id");
+ expect(first).toBe("harbor-radio/hr-2019a|0");
+ await page.keyboard.press("j");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ await page.keyboard.press("j");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|1");
+ await page.keyboard.press("k");
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ // The cite thread is on the lit line only.
+ await expect(litLine(page).locator(".cite-thread")).toBeVisible();
+
+ // The audit: its window, the hit lit among dim cues, the length on the thread.
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2024a|0"]').click();
+ const r = reader(page);
+ await expect(r).toContainText("Harbor Radio 140: the audit");
+ await expect(r).toContainText("deleted");
+ const lit = r.locator("[data-lit-line][data-lit]");
+ await expect(lit).toContainText("How much was the lighthouse budget? You cut it all,");
+ await expect(lit).toContainText("1:22:52");
+ await expect(r.locator(".cite-thread").first()).toHaveAttribute("data-cite-at", "4972");
+ expect(await r.locator("[data-lit-line]").count()).toBeGreaterThan(10);
+ // ± narrows and widens the window.
+ const wide = await r.locator("[data-lit-line]").count();
+ await r.getByRole("button", { name: "Narrower window" }).click();
+ await expect(r.getByText("± 15 s")).toBeVisible();
+ expect(await r.locator("[data-lit-line]").count()).toBeLessThan(wide);
+});
+
+test("Copy citation and c put the house format on the clipboard", async ({ page, context }) => {
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2024a|0"]').click();
+ const want =
+ '"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)';
+ await expect(reader(page).locator("[data-citation]")).toHaveText(want);
+ await reader(page).getByRole("button", { name: "Copy citation" }).click();
+ await expect(reader(page).getByRole("button", { name: "Copied" })).toBeVisible();
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(want);
+
+ await page.evaluate(() => navigator.clipboard.writeText(""));
+ await results(page).locator('[data-lit-id="night-desk/nd-2023|0"]').focus();
+ await expect(reader(page).locator("[data-citation]")).toContainText("[Night Desk: the keeper @ 6:40](https://archive.example/?v=night-desk%2Fnd-2023&t=400)");
+ await page.keyboard.press("c");
+ await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(
+ '"the keeper never saw the lighthouse budget" [Night Desk: the keeper @ 6:40](https://archive.example/?v=night-desk%2Fnd-2023&t=400)',
+ );
+});
+
+test("the reading log: r and s mark and move on, survive a reload, and live umtool-side", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE, channels: ["harbor-radio"] }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 0 of 5");
+ await page.keyboard.press("r");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5");
+ // r moved the light to the next recording.
+ await expect(litLine(page)).toHaveAttribute("data-lit-id", "harbor-radio/hr-2021a|0");
+ await page.keyboard.press("s");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5 · 1 skipped");
+ await expect(results(page).locator('[data-hit="harbor-radio/hr-2019a"] [data-read]').first()).toHaveText("read");
+ await expect(results(page).locator('[data-hit="harbor-radio/hr-2021a"] [data-read]').first()).toHaveText("skipped");
+
+ // Stored under REPORTS_ROOT/.umtool/research/sessions/, never in the corpus.
+ await expect.poll(() => (existsSync(SESSIONS) ? readdirSync(SESSIONS).length : 0)).toBeGreaterThan(0);
+ const docs = readdirSync(SESSIONS).map((f) => JSON.parse(readFileSync(path.join(SESSIONS, f), "utf8")));
+ const doc = docs.find((d) => d.marks?.["harbor-radio/hr-2021a"]);
+ expect(doc?.format).toBe("umtool-research-log");
+ expect(doc?.query).toBe(RESEARCH_PHRASE);
+ expect(doc?.marks["harbor-radio/hr-2019a"].state).toBe("read");
+ expect(doc?.marks["harbor-radio/hr-2021a"].state).toBe("skipped");
+
+ await page.reload();
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 1 of 5 · 1 skipped", { timeout: 30_000 });
+ // The Reading facet narrows to the unread.
+ await page.getByRole("complementary", { name: "Facets" }).getByRole("button", { name: "unread: 3" }).click();
+ await expect(results(page).locator("[data-hit]")).toHaveCount(3);
+ // u clears a mark.
+ await page.getByRole("complementary", { name: "Facets" }).getByRole("button", { name: "unread: 3" }).click();
+ await results(page).locator('[data-lit-id="harbor-radio/hr-2019a|0"]').click();
+ await page.keyboard.press("u");
+ await expect(honest(page).locator("[data-reading]")).toHaveText("read 0 of 5 · 1 skipped");
+});
+
+test("/ focuses the ask bar; a regex and near: say what they are", async ({ page }) => {
+ await page.goto(researchHref());
+ await page.locator("body").click();
+ await page.keyboard.press("/");
+ await expect(page.getByRole("textbox", { name: "Ask" })).toBeFocused();
+ await page.keyboard.type("/light\\w+ keeper/");
+ await expect(page.getByRole("search")).toContainText("regex");
+ await page.keyboard.press("Enter");
+ const re = enumerated("light\\w+ keeper", { regex: true });
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(re.total), { timeout: 30_000 });
+ expect(re.total).toBeGreaterThan(0);
+ await search(page, "keeper near:3 lighthouse");
+ await expect(page.getByRole("search")).toContainText("near: 3 words, one line");
+ const near = enumerated(nearRegex("keeper", "lighthouse", 3), { regex: true });
+ await expect(honest(page).locator("[data-total]")).toHaveAttribute("data-total", String(near.total));
+});
+
+test("Fetch clip asks the editor exactly as fetch_clip does, then plays the window", async ({ page }) => {
+ await page.goto(researchHref({ q: RESEARCH_PHRASE }));
+ await expect(honest(page)).toBeVisible({ timeout: 30_000 });
+ await results(page).locator('[data-lit-id="night-desk/nd-2023|0"]').click();
+ const r = reader(page);
+ await expect(r.locator("[data-citation]")).toContainText("Night Desk: the keeper @ 6:40");
+ await expect(r.getByRole("button", { name: /^Play from/ })).toHaveCount(0);
+ await r.getByRole("button", { name: "Fetch clip" }).click();
+ await expect(r.locator("[data-fetch-state=ready]")).toContainText("Clip fetched", { timeout: 20_000 });
+ await expect(r.getByRole("button", { name: "Play from 6:40" })).toBeVisible();
+ const asked = (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[]).filter((q) => q.channelSlug === "night-desk");
+ expect(asked.at(-1)).toMatchObject({ channelSlug: "night-desk", from: 397, to: 406.8, pad: 3, requestedBy: "umtool" });
+ expect(String(asked.at(-1)?.reason)).toContain('umtool research: "lighthouse budget"');
+ await r.getByRole("button", { name: "Play from 6:40" }).click();
+ await expect(r.locator("video[data-player]")).toHaveAttribute("src", /\/api\/research\/media\?/);
+ const res = await page.request.get((await r.locator("video[data-player]").getAttribute("src"))!, { headers: { range: "bytes=0-99" } });
+ expect(res.status()).toBe(206);
+ expect(res.headers()["content-type"]).toBe("video/mp4");
+});
+
+test("the archive inventory: channels × years, held vs published, gaps, keys, a table", async ({ page }) => {
+ await page.goto(researchArchiveHref());
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).locator("h1")).toHaveText("archive");
+ const heat = page.getByRole("table", { name: "Inventory" });
+ await expect(heat).toBeVisible();
+ // No editor answers coverage here (the stub has no such route): read on disk, and said so.
+ await expect(page.locator("[data-held-note=disk]")).toContainText("read on disk instead");
+ // The held counts are kept five minutes (the warm-up read them): the age says so, Refresh asks again.
+ await expect(page.locator("[data-held-age]")).toContainText(/Held counts from (just now|\d+ min ago) \(kept 5 min\)/);
+ await page.getByRole("button", { name: "Refresh" }).click();
+ await expect(page.locator("[data-held-age]")).not.toContainText("kept 5 min");
+ await expect(page.getByRole("button", { name: "Refresh" })).toBeEnabled();
+ await expect(heat.locator("thead th")).toHaveCount(1 + 8 + 1);
+ const hr = heat.locator('tr[data-row="harbor-radio"]');
+ await expect(hr.locator('td[data-year="2022"]')).toHaveText("1");
+ await expect(hr.locator('td[data-year="2020"]')).toHaveText("—");
+ await expect(hr.locator('td[data-year="2020"]')).toHaveAttribute("data-gap", "");
+ await expect(heat.locator('tr[data-row="harbor-radio-rumble"] td[data-year="2025"]')).toHaveText("—");
+
+ // Published: what the source lists, whether held or not.
+ await page.getByRole("button", { name: "Videos published" }).click();
+ await expect(hr.locator('td[data-year="2022"]')).toHaveText("2");
+ await expect(heat.locator('tr[data-row="harbor-radio-rumble"] td[data-year="2025"]')).toHaveText("1");
+
+ // Keys and the tooltip.
+ await hr.locator('td[data-year="2022"]').hover();
+ await expect(page.locator("[data-heat-tip]")).toContainText("Harbor Radio · 2022 · 2 published · 1 held");
+ await hr.locator('td[data-year="2024"]').click();
+ await page.keyboard.press("ArrowRight");
+ await expect(hr.locator('td[data-year="2025"]')).toBeFocused();
+ await expect(page.locator("[data-heat-tip]")).toContainText("Harbor Radio · 2025");
+
+ await page.getByRole("button", { name: "Table" }).click();
+ await expect(page.getByRole("table", { name: "Inventory table" })).toContainText("Night Desk");
+});
diff --git a/umtool/lib/research/census.mjs b/umtool/lib/research/census.mjs
@@ -0,0 +1,105 @@
+// THE TRACK CENSUS, persisted: transcripts vs captions per channel, as far as
+// a search has read each channel whole (lib/research/corpus.ts). Nothing
+// published counts it per scope, so it is learned by searching, and kept here
+// so a restart does not forget it.
+//
+// REPORTS_ROOT/.umtool/research/census/<sha1(handle), 16 hex>.json
+// { format: "umtool-research-census", version: 1, handle, identity,
+// updatedAt, channels: { "<channel key>": { total, transcript, captions,
+// unknown, byYear } } }
+//
+// KEYED BY THE SOURCE AND ITS BUILD. `identity` is the source's build stamp
+// (sources.ts buildIdentity: corpus.json's generatedAt, and for a local dir its
+// mtime too). A file whose identity is not the source's current one is STALE:
+// its counts describe another build, so they are not used, and the scope says
+// so until a full search counts again and overwrites it.
+//
+// Umtool-side state, never in the corpus. Writes are lib/lifecycle.mjs's: one
+// writer, serialised; a whole file to a temp name and a rename.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const CENSUS_FORMAT = "umtool-research-census";
+export const CENSUS_VERSION = 1;
+
+/** The file for one source handle under a reports root. */
+export function censusFile(reportsRoot, handle) {
+ const id = createHash("sha1").update(String(handle)).digest("hex").slice(0, 16);
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research", "census", `${id}.json`);
+}
+
+const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0);
+function cleanCounts(c) {
+ return { transcript: num(c?.transcript), captions: num(c?.captions), unknown: num(c?.unknown) };
+}
+
+/**
+ * The census for a source at a build. `{ channels, updatedAt }` when the file
+ * is this build's; `{ stale: { identity, updatedAt } }` when it is another
+ * build's; `{}` when there is none (or it cannot be read: `error` says why).
+ *
+ * @param {string} reportsRoot
+ * @param {string} handle
+ * @param {string} identity
+ * @returns {Promise<{ channels?: Record<string, any>, updatedAt?: string, stale?: { identity: string, updatedAt: string }, error?: string }>}
+ */
+export async function readCensus(reportsRoot, handle, identity) {
+ let raw;
+ try {
+ raw = JSON.parse(await readFile(/* turbopackIgnore: true */ censusFile(reportsRoot, handle), "utf8"));
+ } catch (err) {
+ if (err?.code === "ENOENT") return {};
+ return { error: `the census cannot be read: ${err?.message ?? err}` };
+ }
+ if (!raw || raw.format !== CENSUS_FORMAT || raw.handle !== handle || typeof raw.channels !== "object" || !raw.channels) {
+ return { error: "not a umtool-research-census file for this source" };
+ }
+ const updatedAt = typeof raw.updatedAt === "string" ? raw.updatedAt : "";
+ if (raw.identity !== identity) return { stale: { identity: String(raw.identity ?? ""), updatedAt } };
+ const channels = {};
+ for (const [k, c] of Object.entries(raw.channels)) {
+ if (!c || typeof c !== "object") continue;
+ const byYear = {};
+ for (const [y, v] of Object.entries(c.byYear ?? {})) byYear[y] = cleanCounts(v);
+ channels[k] = { total: num(c.total), ...cleanCounts(c), byYear };
+ }
+ return { channels, updatedAt };
+}
+
+let chain = Promise.resolve();
+
+/**
+ * Replace the census for a source at a build (the whole map the caller holds).
+ *
+ * @param {string} reportsRoot
+ * @param {string} handle
+ * @param {string} identity
+ * @param {Record<string, unknown>} channels
+ * @param {{ now?: Date }} [opts]
+ */
+export function writeCensus(reportsRoot, handle, identity, channels, { now } = {}) {
+ const run = chain.then(async () => {
+ const file = censusFile(reportsRoot, handle);
+ const doc = {
+ format: CENSUS_FORMAT,
+ version: CENSUS_VERSION,
+ handle,
+ identity,
+ updatedAt: (now ?? new Date()).toISOString(),
+ channels: Object.fromEntries(Object.entries(channels).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 doc;
+ });
+ chain = run.catch(() => {});
+ return run;
+}
diff --git a/umtool/lib/research/census.test.mjs b/umtool/lib/research/census.test.mjs
@@ -0,0 +1,44 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, readdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CENSUS_FORMAT, censusFile, readCensus, writeCensus } from "./census.mjs";
+
+const H = "local:/x/export/public";
+const C = { "ch-a": { total: 3, transcript: 1, captions: 2, unknown: 0, byYear: { 2024: { transcript: 1, captions: 2, unknown: 0 } } } };
+
+test("a census round-trips for its build, and is stale for another", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-"));
+ try {
+ assert.deepEqual(await readCensus(root, H, "b1"), {});
+ await writeCensus(root, H, "b1", C, { now: new Date("2026-10-14T00:00:00Z") });
+ const r = await readCensus(root, H, "b1");
+ assert.deepEqual(r.channels, C);
+ assert.equal(r.updatedAt, "2026-10-14T00:00:00.000Z");
+ assert.deepEqual(await readCensus(root, H, "b2"), { stale: { identity: "b1", updatedAt: "2026-10-14T00:00:00.000Z" } });
+ const doc = JSON.parse(await readFile(censusFile(root, H), "utf8"));
+ assert.equal(doc.format, CENSUS_FORMAT);
+ assert.equal(doc.handle, H);
+ assert.ok(censusFile(root, H).includes(`${path.sep}.umtool${path.sep}research${path.sep}census${path.sep}`));
+ // another source, another file
+ assert.notEqual(censusFile(root, H), censusFile(root, "remote:https://a.example"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("writes are serialised and leave no temp file; bad files are reported, never trusted", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-"));
+ try {
+ await Promise.all(Array.from({ length: 10 }, (_, i) => writeCensus(root, H, `b${i}`, C)));
+ assert.equal((await readCensus(root, H, "b9")).channels["ch-a"].total, 3);
+ assert.deepEqual(await readdir(path.dirname(censusFile(root, H))), [path.basename(censusFile(root, H))]);
+ await writeCensus(root, "other", "b1", C);
+ const { writeFile } = await import("node:fs/promises");
+ await writeFile(censusFile(root, "other"), "{nope");
+ assert.match((await readCensus(root, "other", "b1")).error, /cannot be read/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/research/corpus.ts b/umtool/lib/research/corpus.ts
@@ -0,0 +1,430 @@
+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, trackOf, yearOf } from "./facets.mjs";
+import { sessionKey } from "./session.mjs";
+import { readLog } from "./log.mjs";
+import { writeCensus } from "./census.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]),
+ ...(opened.censusStale && !censusOf(opened, [...keys])
+ ? { tracksStale: `counted on an earlier build (${opened.censusStale.updatedAt.slice(0, 10) || "date unknown"}); the next full search counts again` }
+ : {}),
+ 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> {
+ let counted = 0;
+ 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);
+ counted++;
+ }
+ // Kept umtool-side for this build (census.mjs), so a restart does not forget it.
+ if (counted > 0 && opened.identity) {
+ try {
+ await writeCensus(REPORTS_ROOT, opened.option.handle, opened.identity, Object.fromEntries(opened.census));
+ opened.censusStale = null;
+ } catch {
+ /* the counts still serve this process; the file is a convenience */
+ }
+ }
+}
+
+// ── 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,195 @@
+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;
+ }
+}
+
+// ── the held counts, memoised ──
+//
+// Each channel's held count is a walk of the editor's disk (every held
+// video's metadata), and the editor has stalled on the external drive before:
+// a page load must not cost a walk per channel. So a channel's answer --
+// the editor's, the disk's, or "not known" with the reason -- is kept
+// HELD_TTL_MS per source and channel, on globalThis (one copy for every route
+// bundle). `fresh` (the page's Refresh) asks again. The editor is still asked
+// four at a time.
+export const HELD_TTL_MS = 5 * 60_000;
+type HeldMemo = { at: number; held: Held | null; via: CoverageResponse["held"]["via"]; note?: string };
+const g = globalThis as { __umtoolResearchHeld?: Map<string, HeldMemo> };
+const heldMemo = (g.__umtoolResearchHeld ??= new Map());
+
+export async function coverageOf(scope: Scope, opts: { fresh?: boolean; now?: () => number } = {}): Promise<CoverageResponse> {
+ const now = opts.now ?? Date.now;
+ 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: {}, missingByYear: {} });
+ 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;
+ if (y && v.state !== "available") {
+ const m = (p.missingByYear[y] ??= {});
+ m[v.state] = (m[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 memo, else the editor, else (local corpus) the disk.
+ const memoKey = (ch: ChannelRef) => `${opened.option.handle}\u0000${ch.key}`;
+ const t = now();
+ const todo = channels.filter((ch) => {
+ const m = heldMemo.get(memoKey(ch));
+ return opts.fresh || !m || t - m.at >= HELD_TTL_MS;
+ });
+ if (todo.length > 0) {
+ let note: string | undefined;
+ let stopped = false;
+ const fromEditor = new Map<string, Held | null>();
+ await mapConcurrent(todo, 4, async (ch) => {
+ if (stopped) return;
+ const a = await askEditor(ch.slug);
+ if (a.ok) fromEditor.set(ch.key, heldOf(a.body));
+ else if (a.stop) {
+ stopped = true;
+ note ??= a.why;
+ } else fromEditor.set(ch.key, null);
+ });
+ const at = now();
+ if (!stopped) {
+ for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: fromEditor.get(ch.key) ?? null, via: "editor" });
+ } else if (opened.option.kind === "local") {
+ const why = `${note}; read on disk instead`;
+ await mapConcurrent(todo, 8, async (ch) => heldMemo.set(memoKey(ch), { at, held: await fromDisk(ch.slug), via: "disk", note: why }));
+ } else {
+ const why = `${note}; held counts need the editor for a published source`;
+ for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: null, via: "none", note: why });
+ }
+ }
+ const memos = channels.map((ch) => heldMemo.get(memoKey(ch))!).filter(Boolean);
+ const held = new Map(channels.map((ch) => [ch.key, heldMemo.get(memoKey(ch))?.held ?? null]));
+ // The page says where the counts came from, and how old the oldest is.
+ const odd = memos.find((m) => m.via === "disk") ?? memos.find((m) => m.via === "none");
+ const via: CoverageResponse["held"]["via"] = odd?.via ?? "editor";
+ const note = odd?.note;
+ const at = memos.length ? Math.min(...memos.map((m) => m.at)) : t;
+
+ 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 } : {}), at, cached: todo.length === 0, asked: todo.length },
+ gapDays: GAP_DAYS,
+ };
+}
diff --git a/umtool/lib/research/facets.mjs b/umtool/lib/research/facets.mjs
@@ -0,0 +1,77 @@
+// The Research results' facets, keys and citation text: pure and
+// browser-safe, so the server that builds a result, the page that filters it
+// and the tests agree. (The session key needs node:crypto: session.mjs.)
+
+/**
+ * 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,
+ };
+}
+
+/**
+ * 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,66 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { citationText, facetsOf, hitKey, isoDate, trackOf, yearOf } from "./facets.mjs";
+import { sessionKey } from "./session.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>, opts: { fresh?: boolean } = {}): string {
+ return withQuery("/api/research/coverage", { ...scopeQuery(s), fresh: opts.fresh === true });
+}
+
+/** 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,203 @@
+// 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.published.missingByYear, { "2024": { deleted: 1 }, "2026": { unlisted: 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);
+ assert.equal(c.held.asked, 4);
+ assert.equal(c.held.cached, false);
+});
+
+test("the held counts are kept five minutes per source and channel; fresh asks again", async () => {
+ let t = Date.now() + 1000;
+ const now = () => t;
+ const kept = await lib.coverage.coverageOf({ source: "" }, { now });
+ assert.equal(kept.held.cached, true);
+ assert.equal(kept.held.asked, 0);
+ const firstAt = kept.held.at;
+ assert.ok(firstAt <= t);
+ // One channel past the memo is asked again; the others stay kept.
+ t += lib.coverage.HELD_TTL_MS;
+ const later = await lib.coverage.coverageOf({ source: "", channels: ["night-desk"] }, { now });
+ assert.equal(later.held.asked, 1);
+ assert.equal(later.held.at, t);
+ const fresh = await lib.coverage.coverageOf({ source: "" }, { fresh: true, now });
+ assert.equal(fresh.held.asked, 4);
+ assert.equal(fresh.rows.find((r) => r.slug === "harbor-radio")!.held?.total, 5);
+});
+
+test("the track census is kept per source and build: it survives a restart, and another build's is stale", async () => {
+ const { censusFile, readCensus, writeCensus } = await import("./census.mjs");
+ const sources = await import("./sources");
+ const handle = `local:${pub}`;
+ const id = await sources.buildIdentity({ handle, kind: "local", label: "Local corpus" });
+ assert.ok(id);
+ // The searches above wrote it for this build.
+ const kept = await readCensus(process.env.REPORTS_DIR!, handle, id!);
+ assert.equal(Object.keys(kept.channels ?? {}).length, 4);
+ // A restart: the process's sources forgotten, the counts read back.
+ (globalThis as { __umtoolResearchSources?: Map<string, unknown> }).__umtoolResearchSources!.clear();
+ const again = await lib.corpus.scopeOf({ source: "" });
+ assert.deepEqual(again.tracks, { transcript: 5, captions: 7, unknown: 0, counted: 4, of: 4 });
+ assert.equal(again.tracksStale, undefined);
+ // Another build's census is not used, and the scope says so.
+ await writeCensus(process.env.REPORTS_DIR!, handle, "an-older-build", kept.channels!, { now: new Date("2026-10-01T00:00:00Z") });
+ (globalThis as { __umtoolResearchSources?: Map<string, unknown> }).__umtoolResearchSources!.clear();
+ const stale = await lib.corpus.scopeOf({ source: "" });
+ assert.equal(stale.tracks, null);
+ assert.match(stale.tracksStale ?? "", /earlier build \(2026-10-01\)/);
+ // The next full search counts again, for this build.
+ await lib.corpus.runSearch({ source: "", query: "the", fresh: true });
+ const recounted = await lib.corpus.scopeOf({ source: "" });
+ assert.equal(recounted.tracks?.counted, 4);
+ assert.equal(recounted.tracksStale, undefined);
+ assert.equal(JSON.parse((await import("node:fs")).readFileSync(censusFile(process.env.REPORTS_DIR!, handle), "utf8")).identity, id);
+});
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/session.mjs b/umtool/lib/research/session.mjs
@@ -0,0 +1,23 @@
+// The reading log's scratch session key (server side: node:crypto).
+import { createHash } from "node:crypto";
+
+/**
+ * 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);
+}
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -0,0 +1,195 @@
+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, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
+import { readCensus } from "./census.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; siteTitle?: 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?.siteTitle === "string" && site.siteTitle ? site.siteTitle : 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>;
+ /** The source's build (buildIdentity); null when it cannot be told, and then nothing is persisted. */
+ identity: string | null;
+ /** A persisted census from another build: not used, and said so. */
+ censusStale: { identity: string; updatedAt: string } | null;
+};
+
+const IDENTITY_TIMEOUT_MS = 10_000;
+
+/**
+ * Which BUILD a source is, for the persisted census (census.mjs): a published
+ * site's or a hub's corpus.json `generatedAt`; for the local dir that and the
+ * file's mtime and size (a recomposed export/public changes both). Null when
+ * it cannot be told -- then the census is counted but not kept.
+ */
+export async function buildIdentity(option: SourceOption): Promise<string | null> {
+ if (option.kind === "local") {
+ const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json");
+ const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
+ if (!st) return null;
+ const corpus = await readJson<{ generatedAt?: unknown }>(file);
+ return `${typeof corpus?.generatedAt === "string" ? corpus.generatedAt : "-"}|${st.mtimeMs}|${st.size}`;
+ }
+ const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, "");
+ try {
+ const res = await fetch(`${url}/corpus.json`, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
+ if (!res.ok) return null;
+ const j = (await res.json()) as { generatedAt?: unknown };
+ return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null;
+ } catch {
+ return null;
+ }
+}
+
+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);
+ }
+ // What a search counted for this source before, when it was this build.
+ const identity = await buildIdentity(option);
+ const census = new Map<string, ChannelCensus>();
+ let censusStale: Opened["censusStale"] = null;
+ if (identity) {
+ const kept = await readCensus(REPORTS_ROOT, option.handle, identity);
+ for (const [k, c] of Object.entries(kept.channels ?? {})) census.set(k, c as ChannelCensus);
+ if (kept.stale) censusStale = kept.stale;
+ }
+ const opened: Opened = { option, source, census, identity, censusStale };
+ 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,228 @@
+// 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;
+ /** A kept count from another build of this source: not used, said so. */
+ tracksStale?: string;
+ /** 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>;
+ /** The states that are not "available", per year. */
+ missingByYear: Record<string, 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;
+ /** When the oldest of these held counts was read (ms since the epoch): they are kept 5 minutes. */
+ at: number;
+ /** Every count came from the memo; `asked` channels were read this time. */
+ cached: boolean;
+ asked: number;
+ };
+ 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": {
@@ -19,7 +20,8 @@
"react-dom": "19.2.4",
"umtool-report-to-video": "workspace:*",
"tailwind-merge": "^3.6.0",
- "yt-dlp-transcript-common": "workspace:*"
+ "yt-dlp-transcript-common": "workspace:*",
+ "yt-dlp-transcript-mcp": "workspace:*"
},
"devDependencies": {
"@playwright/test": "^1.59.1",
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -135,6 +135,9 @@ export default defineConfig({
// The article store (/articles, release 26): the fixture's own, for the
// same reason -- an article's notes.json is written beside it.
`ARTICLES_DIR=${FIXTURE}/articles ` +
+ // Research's local corpus (R1): the fixture's composed public dir, read as
+ // the MCP's --local reads one -- never the checkout's export/public.
+ `TRANSCRIPT_LOCAL_DIR=${FIXTURE}/research-public TRANSCRIPT_HUB_URL= ` +
// The generation usage ledger (release 27): the fixture's, never the
// checkout's .generation/usage.jsonl.
`GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` +