// 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 }).__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 }).__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); });