// 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: `- | 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"]); });