// An X SEARCH channel's fetch (fetchPosts on a channel with `xSearch`), end to // end against a fake gallery-dl that answers X search URLs from a fixed set of // posts by several authors: the operator's query passes through with each // window's since:/until: (and no from:), the walk tiles from until down to // since, resumes across runs at its max_id: point, starts afresh on a new // query, searches the new days above what was covered, refuses an older walk // and a guest run, and keeps its own copy of a post another X channel holds. // No real X traffic. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchXSearch.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-xsearch-")); const BIN = path.join(ROOT, "fake-gallery-dl.mjs"); const ARGS_LOG = path.join(ROOT, "argv.jsonl"); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.GALLERY_DL_BIN = BIN; process.env.FAKE_ARGS_LOG = ARGS_LOG; const TODAY = new Date().toISOString().slice(0, 10); // [date, author, text]. Ids carry the creation time in their high bits, as // X's do, so they order as dates do. const POSTS: Array<[string, string, string]> = [ [`${TODAY} 08:00:00`, "dora", "a zephyr today"], ["2025-11-10 12:00:00", "alice", "the zephyr archive again"], ["2025-09-01 09:00:00", "bob", "zephyr breeze"], ["2025-08-01 09:00:00", "carol", "only a breeze"], ["2025-03-15 18:30:00", "alice", "zephyr, once more"], ["2024-12-01 22:15:00", "alice", "an old zephyr"], ]; // The walk drops a post the channel already holds as it reads (the stream's // seen-id check), so a re-read shows in the log's "already archived", not in // `skipped`. // // The fake: a search URL's plain words must all be in a post's text (any one // of them with an OR; an operator — from:, -term, lang:, a quoted phrase — is // ignored), since:/until: // bound its day, max_id: its id; newest first; --post-range honoured. await writeFile( BIN, `#!/usr/bin/env node import { appendFileSync } from "node:fs"; const args = process.argv.slice(2); appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); const url = new URL(args[args.length - 1]); if (!url.pathname.startsWith("/search")) process.exit(0); const q = url.searchParams.get("q"); const terms = q.split(" "); const term = (k) => (terms.find((t) => t.startsWith(k + ":")) || "").slice(k.length + 1) || undefined; const since = term("since"), until = term("until"), maxId = term("max_id"); const words = terms.filter((t) => /^[a-z]+$/.test(t) && t !== "OR"); const range = args[args.indexOf("--post-range") + 1]; const cap = args.includes("--post-range") ? Number(range.split("-")[1]) : Infinity; const posts = ${JSON.stringify(POSTS)}; const idOf = (d) => (BigInt(Date.parse(d.replace(" ", "T") + "Z") - 1288834974657) << 22n); const hits = posts .filter(([d, , text]) => d.slice(0, 10) >= since && d.slice(0, 10) < until) .filter(([d]) => !maxId || idOf(d) <= BigInt(maxId)) .filter(([, , text]) => words[terms.includes("OR") ? "some" : "every"]((w) => text.includes(w))) .sort((a, b) => (a[0] < b[0] ? 1 : -1)); for (const [d, author, text] of hits.slice(0, cap)) { const user = { name: author, nick: author.toUpperCase() }; process.stdout.write('{"tweet_id": ' + idOf(d) + ', "date": "' + d + '", "content": ' + JSON.stringify(text) + ', "author": ' + JSON.stringify(user) + ', "user": ' + JSON.stringify(user) + '}\\n'); } `, ); await chmod(BIN, 0o755); const channelsDir = path.join(ROOT, "transcripts", "channels"); async function makeSearchChannel(slug: string, xSearch: Record): Promise { const channelRoot = path.join(channelsDir, slug); await mkdir(channelRoot, { recursive: true }); await writeFile( path.join(channelRoot, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", platform: "twitter", name: `${slug} (X search)`, url: "https://x.com/search?q=zephyr&f=live", xSearch, }), ); return channelRoot; } // An X fetch runs only as the editor's job (X_ONLY_AS_A_JOB): these calls stand where one does. const { fetchPosts: fetchPostsDirect, X_ONLY_AS_A_JOB } = await import("./fetchPosts"); const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); const fetchPosts = insideEditorJob(fetchPostsDirect); const { X_SEARCH_OLDER_REFUSAL } = await import("./fetchXSearch"); const { readPostFetchState, readSeenPostIds, readAllPosts, writePosts, writePostFetchState } = await import( "../lib/posts-server" ); const { normalizeXTweet } = await import("../social/xNormalize"); const { getPaths } = await import("../lib/paths"); const LOGIN = { cookiesFromBrowser: "firefox" }; async function argvLines(): Promise { try { return (await readFile(ARGS_LOG, "utf8")) .trim() .split("\n") .filter(Boolean) .map((l) => JSON.parse(l) as string[]); } catch { return []; } } const queryOf = (argv: string[]) => new URL(argv[argv.length - 1]).searchParams.get("q") ?? ""; const run = (slug: string, extra: Record = {}) => { const log: string[] = []; return fetchPosts({ paths: getPaths(), slug, settings: LOGIN, olderWindowPauseMs: 0, onLog: (l) => log.push(l), ...extra, }).then((r) => ({ ...r, log })); }; test("the first walk tiles from until down to since with the operator's query, from any author", async () => { const slug = "zephyr-search"; const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01", until: "2026-01-01", windowMonths: 6, }); const before = (await argvLines()).length; const res = await run(slug); assert.equal(res.ok, true, res.log.join("\n")); assert.equal(res.complete, true); assert.equal(res.written, 3); const runs = (await argvLines()).slice(before); assert.deepEqual(runs.map(queryOf), [ "zephyr since:2025-07-01 until:2026-01-01", "zephyr since:2025-01-01 until:2025-07-01", ]); // The search argv: newest first, paged by max_id, never a from:. assert.ok(runs[0].includes("extractor.twitter.search-pagination=max_id")); assert.ok(runs.every((a) => !queryOf(a).includes("from:"))); const posts = await readAllPosts(channelRoot); assert.deepEqual( posts.map((p) => [p.author, p.createdAt.slice(0, 10)]), [ ["alice", "2025-11-10"], ["bob", "2025-09-01"], ["alice", "2025-03-15"], ], ); assert.ok(posts.every((p) => p.channelSlug === slug)); const state = await readPostFetchState(channelRoot); assert.equal(state?.search?.queryKey, "zephyr"); assert.equal(state?.search?.walk, undefined); assert.equal(state?.search?.coveredSince, "2025-01-01"); assert.equal(state?.search?.coveredUntil, "2026-01-01"); assert.equal(state?.lastFetchedCount, 3); // A search channel's fetch is a sync: the scheduler paces it by this stamp. const config = JSON.parse(await readFile(path.join(channelRoot, "config.json"), "utf8")); assert.ok(config.lastSyncedAt); // Everything is covered and until is fixed: a second fetch searches nothing. const mid = (await argvLines()).length; const again = await run(slug); assert.equal(again.ok, true); assert.equal(again.written, 0); assert.equal((await argvLines()).length, mid); assert.match(again.log.join("\n"), /already searched 2025-01-01 – 2026-01-01/); }); test("a run cut short resumes at its max_id: point; nothing is written twice", async () => { const slug = "resume-search"; const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01", until: "2026-01-01", windowMonths: 6 }); const first = await run(slug, { limit: 1 }); assert.equal(first.ok, true, first.log.join("\n")); assert.equal(first.complete, false); assert.equal(first.written, 1, first.log.join("\n")); const state = await readPostFetchState(channelRoot); assert.equal(state?.search?.walk?.since, "2025-07-01"); assert.ok(state?.search?.walk?.maxId, "a resume point inside the window"); assert.equal(state?.search?.coveredUntil, undefined); const before = (await argvLines()).length; const second = await run(slug); assert.equal(second.ok, true, second.log.join("\n")); assert.equal(second.complete, true); const queries = (await argvLines()).slice(before).map(queryOf); assert.match(queries[0], new RegExp(`^zephyr since:2025-07-01 until:2026-01-01 max_id:${state!.search!.walk!.maxId}$`)); assert.equal(second.written, 2); // The post at the resume point is read again and dropped as archived. assert.match(second.log.join("\n"), /2025-07-01 – 2026-01-01: read 2 post\(s\), 1 new, 1 already archived/); assert.equal((await readSeenPostIds(channelRoot)).size, 3); }); test("operators pass through untouched; a new query starts the walk afresh, posts deduped", async () => { const slug = "operator-search"; const channelRoot = await makeSearchChannel(slug, { query: '"zephyr archive" OR zephyr -from:spam_bot', lang: "en", since: "2025-07-01", until: "2026-01-01", windowMonths: 6, }); const before = (await argvLines()).length; const res = await run(slug); assert.equal(res.ok, true, res.log.join("\n")); assert.deepEqual((await argvLines()).slice(before).map(queryOf), [ '"zephyr archive" OR zephyr -from:spam_bot lang:en since:2025-07-01 until:2026-01-01', ]); assert.equal(res.written, 2, res.log.join("\n")); const config = JSON.parse(await readFile(path.join(channelRoot, "config.json"), "utf8")); config.xSearch.query = "zephyr OR breeze"; await writeFile(path.join(channelRoot, "config.json"), JSON.stringify(config)); const again = await run(slug); assert.equal(again.ok, true, again.log.join("\n")); assert.match(again.log.join("\n"), /The query changed since the last walk: starting it afresh/); assert.equal(again.written, 1); assert.match(again.log.join("\n"), /read 3 post\(s\), 1 new, 2 already archived/); const state = await readPostFetchState(channelRoot); assert.equal(state?.search?.queryKey, "zephyr OR breeze lang:en"); }); test("with no until, a later fetch searches the new days down to a day below what was covered", async () => { const slug = "new-days-search"; const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01" }); const day = (offset: number) => new Date(Date.parse(`${TODAY}T00:00:00Z`) + offset * 86_400_000).toISOString().slice(0, 10); await writePostFetchState(channelRoot, { search: { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: day(-3) }, }); const before = (await argvLines()).length; const res = await run(slug); assert.equal(res.ok, true, res.log.join("\n")); assert.deepEqual((await argvLines()).slice(before).map(queryOf), [`zephyr since:${day(-4)} until:${day(1)}`]); assert.equal(res.written, 1); const [post] = await readAllPosts(channelRoot); assert.equal(post.author, "dora"); const state = await readPostFetchState(channelRoot); assert.equal(state?.search?.coveredUntil, day(1)); assert.equal(state?.search?.coveredSince, "2025-01-01"); assert.match(state?.search?.completeReason ?? "", /searched down to/); }); test("an older walk and a guest run are refused before anything is searched", async () => { const slug = "refusals-search"; await makeSearchChannel(slug, { query: "zephyr", until: "2026-01-01" }); const before = (await argvLines()).length; const older = await run(slug, { older: true }); assert.equal(older.ok, false); assert.equal(older.error, X_SEARCH_OLDER_REFUSAL); const guest = await fetchPosts({ paths: getPaths(), slug, settings: {}, olderWindowPauseMs: 0 }); assert.equal(guest.ok, false); assert.equal(guest.needsCookies, true); assert.match(guest.error ?? "", /X search needs a logged-in session/); assert.equal((await argvLines()).length, before); }); test("a post another X channel holds is kept in the search channel too, once — the archive dedupes per channel", async () => { // An account channel already holding alice's 2025-11-10 post. const accountRoot = path.join(channelsDir, "alice-x"); await mkdir(accountRoot, { recursive: true }); await writeFile( path.join(accountRoot, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "alice", url: "https://x.com/alice" }), ); const id = String(BigInt(Date.parse("2025-11-10T12:00:00Z") - 1288834974657) << 22n); const held = normalizeXTweet({ tweet_id: id, date: "2025-11-10 12:00:00", content: "the zephyr archive again", author: { name: "alice" } }, "alice-x"); assert.ok(held); await writePosts(accountRoot, [held]); const slug = "dedupe-search"; const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-07-01", until: "2026-01-01", windowMonths: 6 }); const res = await run(slug); assert.equal(res.written, 2, res.log.join("\n")); const mine = await readAllPosts(channelRoot); assert.equal(mine.filter((p) => p.id === id).length, 1); assert.equal(mine.find((p) => p.id === id)?.channelSlug, slug); // The account channel is untouched. assert.deepEqual((await readAllPosts(accountRoot)).map((p) => p.id), [id]); // Searching again from the top re-reads, and writes nothing twice. const full = await run(slug, { full: true }); assert.equal(full.ok, true, full.log.join("\n")); assert.equal(full.written, 0); assert.match(full.log.join("\n"), /read 2 post\(s\), 0 new, 2 already archived/); assert.match(full.log.join("\n"), /Starting the search walk afresh, as asked/); }); // Lane x-followups: X is asked only by the editor's jobs — an X search channel too. test("an X search fetch outside the editor's job is refused and spawns nothing", async () => { const slug = "outside-search"; await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01", until: "2025-03-01" }); const before = (await argvLines()).length; for (const mode of [{}, { full: true }, { older: true }, { backfill: true }]) { const r = await fetchPostsDirect({ paths: getPaths(), slug, settings: LOGIN, olderWindowPauseMs: 0, ...mode }); assert.equal(r.ok, false); assert.equal(r.error, X_ONLY_AS_A_JOB(slug), JSON.stringify(mode)); } assert.equal((await argvLines()).length, before); });