commit ffee4005180f18b198e3b24beab3887ea5a071ee
parent 22e2ca7180f2b936511c42adb202591a6bf76f8b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 16:17:33 -0400
x search: an X search channel — config.xSearch, the window walk over any query, the leads, never on a site
Release 38 lane S, the common half. `config.xSearch = {query, since?, until?,
windowMonths?, lang?, exclude?}` on an X posts channel (lib/xSearch/config.ts,
a client-safe leaf in the one set of coercions): X's operators pass through,
since:/until:/max_id: and their kin are refused, a pasted search URL's dates
are lifted out. The fetch (controller/fetchXSearch.ts, from fetchPosts) walks
ONE stretch per run, planned by lib/xSearch/walk.ts — a walk in progress, the
first walk (until/tomorrow down to since), the new days, the earlier days —
through the older walk's own loop, factored out unchanged
(xGalleryDlFetcher.ts walkSearchWindows; SocialFetcher.fetchSearch): the
same windows, pacing, login, budget and max_id resume point. State in
posts-state.json `search`. Leads (lib/xSearch/leads.ts,
controller/xSearchLeads.ts): accounts ranked by matching posts, hidden ones
apart, the accounts an X channel already archives named; Archive this
account plans <handle>-x, Never archive / Restore write xSearch.exclude
through patchChannelConfig's new `derive`. writeSite refuses a site that
names a search channel. Tests over a fake gallery-dl answering search URLs.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
20 files changed, 1890 insertions(+), 13 deletions(-)
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -15,6 +15,7 @@
// Article's link is known as one before its page is opened.
import path from "node:path";
+import { isXSearchChannel } from "../lib/xSearch/config";
import { readChannelConfig } from "./channels";
import type { Paths } from "../lib/paths";
import type { PostAvailability } from "../lib/posts";
@@ -131,7 +132,9 @@ export async function capturePosts(
const problem = capturePostsProblem(fetcher);
if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher.");
- const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? "";
+ // An X search channel has no account (release 38): its posts are any
+ // author's, and the X capture opens each by its status id alone.
+ const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) ? slug : "");
if (!handle) return fail(`Could not determine an account handle for ${slug}`);
const stray = strayCaptureIds(ids, await readSeenPostIds(channelRoot));
diff --git a/common/controller/channels.ts b/common/controller/channels.ts
@@ -531,6 +531,10 @@ export type PatchChannelConfigOptions = {
// Keys to delete before the patch is applied — how a caller says "clear
// this override" (a key absent from `patch` is left alone).
unset?: ReadonlyArray<keyof ChannelConfig>;
+ // A patch computed from the config as it is NOW, inside the lock — for a key
+ // whose new value depends on its old one (an X search channel's
+ // `xSearch.exclude`, release 38). Applied after `patch`.
+ derive?: (current: ChannelConfig) => Partial<ChannelConfig>;
};
// READ-MODIFY-WRITE ONE CHANNEL'S CONFIG, and the only way to change some keys
@@ -553,6 +557,7 @@ export async function patchChannelConfig(
const next: ChannelConfig = { ...current };
for (const key of opts.unset ?? []) delete next[key];
Object.assign(next, patch);
+ if (opts.derive) Object.assign(next, opts.derive(next));
return writeChannelConfig(paths, slug, next);
});
}
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -15,6 +15,8 @@ import type { Paths } from "../lib/paths";
import type { Post } from "../lib/posts";
import { isSocialChannel } from "../lib/channelConfig";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import { isXSearchChannel } from "../lib/xSearch/config";
+import { fetchXSearchPosts, X_SEARCH_OLDER_REFUSAL } from "./fetchXSearch";
import {
alwaysCookies,
resolveCookiePolicy,
@@ -211,6 +213,35 @@ export async function fetchPosts(
};
}
+ // AN X SEARCH CHANNEL (release 38): its query across accounts, walked in
+ // search windows — no handle, no timeline, no older walk (fetchXSearch.ts).
+ if (isXSearchChannel(config) && config.xSearch) {
+ if (opts.older) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_OLDER_REFUSAL };
+ }
+ if (opts.drain?.aborted) {
+ log("Drained before the fetch started; nothing was read.");
+ return { ok: true, written: 0, skipped: 0, complete: false, drained: true };
+ }
+ const policy = resolveCookiePolicy(settings, config);
+ const xLogin = await resolveXCookieSourceFor(paths, settings, policy.cookies);
+ return fetchXSearchPosts({
+ paths,
+ slug,
+ config: { ...config, xSearch: config.xSearch },
+ fetcher,
+ full: opts.full,
+ limit: opts.limit,
+ cookies: alwaysCookies(policy),
+ cookieSource: xLogin.source,
+ browserCookies: xLogin.browserSpec,
+ windowPauseMs: opts.olderWindowPauseMs,
+ onLog,
+ signal,
+ drain: opts.drain,
+ });
+ }
+
const handle =
config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? "";
if (!handle) {
diff --git a/common/controller/fetchXSearch.test.ts b/common/controller/fetchXSearch.test.ts
@@ -0,0 +1,298 @@
+// 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<string, unknown>): Promise<string> {
+ 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;
+}
+
+const { fetchPosts } = await import("./fetchPosts");
+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<string[][]> {
+ 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<string, unknown> = {}) => {
+ 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/);
+});
diff --git a/common/controller/fetchXSearch.ts b/common/controller/fetchXSearch.ts
@@ -0,0 +1,234 @@
+// An X SEARCH channel's fetch (release 38 lane S): one walk of search windows
+// over the channel's query, newest first, resumable, landing the matching
+// posts — from any author — in the channel's own posts archive (the same shard
+// writer, deduped by status id within the channel, as every posts channel).
+// The walk is the older walk's (fetcher.fetchSearch; xGalleryDlFetcher.ts):
+// the same windows, the same 45–120 s between them and 4–10 s between
+// requests, the same login, the same 3-hour budget, a 429 waited out by
+// gallery-dl as there. lib/xSearch/walk.ts plans which stretch a run walks.
+//
+// Called by fetchPosts for a channel with `config.xSearch`, after its own
+// checks (the channel exists, is social, has a fetcher); the walk's state is
+// posts-state.json's `search`, every other field carried as it was.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Post } from "../lib/posts";
+import type { ChannelConfig } from "../lib/channelConfig";
+import {
+ readPostFetchState,
+ readSeenPostIds,
+ writePostFetchState,
+ writePosts,
+ type OlderBackfillPosition,
+ type XSearchWalkState,
+} from "../lib/posts-server";
+import { describeXSearch, type XSearchConfig } from "../lib/xSearch/config";
+import {
+ coverAfterWalk,
+ planXSearchWalk,
+ xSearchStateFor,
+ type XSearchWalk,
+} from "../lib/xSearch/walk";
+import type { SocialFetcher } from "../social/fetchers";
+import type { XCookieSource } from "../social/xCookieSource";
+import { patchChannelConfig } from "./channels";
+
+// Refused for a search channel, before any job: it has no timeline and no
+// older walk — its fetch IS the window walk.
+export const X_SEARCH_OLDER_REFUSAL =
+ "An X search channel has one walk, its search windows: run a plain fetch. " +
+ "Its dates are the channel's since and until (Configure).";
+
+export function xSearchFetcherProblem(
+ fetcher: Pick<SocialFetcher, "label" | "fetchSearch"> | undefined,
+): string | null {
+ if (!fetcher) return "This channel has no post fetcher.";
+ return typeof fetcher.fetchSearch === "function"
+ ? null
+ : `${fetcher.label} cannot walk an X search (use x-gallery-dl).`;
+}
+
+export type FetchXSearchOptions = {
+ paths: Paths;
+ slug: string;
+ config: ChannelConfig & { xSearch: XSearchConfig };
+ fetcher: SocialFetcher;
+ // Start the walk afresh: forget what was covered (posts are kept and
+ // deduped, so this re-reads, never duplicates).
+ full?: boolean;
+ limit?: number;
+ cookies?: string;
+ cookieSource?: XCookieSource;
+ browserCookies?: string;
+ windowPauseMs?: number;
+ now?: Date;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ drain?: AbortSignal;
+};
+
+export type FetchXSearchResult = {
+ ok: boolean;
+ written: number;
+ skipped: number;
+ complete: boolean;
+ error?: string;
+ needsCookies?: boolean;
+ drained?: boolean;
+};
+
+export async function fetchXSearchPosts(opts: FetchXSearchOptions): Promise<FetchXSearchResult> {
+ const { paths, slug, config, fetcher } = opts;
+ const log = (line: string) => opts.onLog?.(line);
+ const search = config.xSearch;
+ const channelRoot = path.join(paths.channelsDir, slug);
+ const problem = xSearchFetcherProblem(fetcher);
+ if (problem) return { ok: false, written: 0, skipped: 0, complete: false, error: problem };
+
+ const priorState = await readPostFetchState(channelRoot);
+ const stored = opts.full ? undefined : priorState?.search;
+ let state: XSearchWalkState = xSearchStateFor(search, stored);
+ if (priorState?.search && state !== priorState.search) {
+ log(
+ opts.full
+ ? "Starting the search walk afresh, as asked (posts already archived are kept)."
+ : "The query changed since the last walk: starting it afresh (posts already archived are kept).",
+ );
+ }
+ const plan = planXSearchWalk(search, state, opts.now);
+ const seenIds = await readSeenPostIds(channelRoot);
+ const startedAt = new Date().toISOString();
+ const stateNow = (extra: Partial<XSearchWalkState> = {}): XSearchWalkState => ({
+ ...state,
+ lastRunAt: startedAt,
+ ...extra,
+ });
+ // Every field but the search walk's (and the run stamps) is carried as it
+ // was.
+ const save = (search: XSearchWalkState, more: { lastFetchedCount?: number; lastError?: string; needsCookies?: boolean } = {}) =>
+ writePostFetchState(channelRoot, {
+ ...(priorState ?? {}),
+ lastFetchedAt: startedAt,
+ ...(more.lastFetchedCount !== undefined ? { lastFetchedCount: more.lastFetchedCount } : {}),
+ lastError: more.lastError,
+ needsCookies: more.needsCookies,
+ search,
+ });
+
+ if (plan.kind === "none") {
+ log(`X search ${describeXSearch(search)}: ${plan.reason}. Nothing to walk.`);
+ await save(stateNow({ lastWritten: 0 }), { lastFetchedCount: 0 });
+ await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() });
+ return { ok: true, written: 0, skipped: 0, complete: true };
+ }
+
+ const walk: XSearchWalk = plan.walk;
+ log(
+ `Fetching X search ${describeXSearch(search)} for ${slug} via ${fetcher.label}: ` +
+ ({
+ resume: "resuming the walk at ",
+ first: "the first walk, starting at ",
+ new: "the new days, starting at ",
+ earlier: "the earlier days, starting at ",
+ } as const)[plan.kind] +
+ `${walk.since} – ${walk.until}` +
+ (walk.floor ? `, down to ${walk.floor}` : ", until a year of windows holds no match") +
+ `; ${seenIds.size} already archived.`,
+ );
+
+ let written = 0;
+ let skipped = 0;
+ const shards = new Set<string>();
+ const walkAt = (at: OlderBackfillPosition): XSearchWalk => ({
+ top: walk.top,
+ ...(walk.floor !== undefined ? { floor: walk.floor } : {}),
+ since: at.since,
+ until: at.until,
+ emptyWindows: at.emptyWindows,
+ ...(at.maxId ? { maxId: at.maxId } : {}),
+ });
+ const onCheckpoint = async (cp: { posts: Post[]; position: OlderBackfillPosition }) => {
+ const w = await writePosts(channelRoot, cp.posts);
+ written += w.written;
+ skipped += w.skipped;
+ for (const shard of w.shards) shards.add(shard);
+ state = { ...state, walk: walkAt(cp.position) };
+ await save(stateNow({ lastWritten: written }), { lastFetchedCount: written });
+ if (w.written > 0) log(`Saved ${w.written} matching post(s) (${written} so far this run); resume point recorded.`);
+ };
+
+ const controller = new AbortController();
+ let result;
+ try {
+ result = await fetcher.fetchSearch!({
+ channelSlug: slug,
+ seenIds,
+ cookies: opts.cookies,
+ cookieSource: opts.cookieSource,
+ browserCookies: opts.browserCookies,
+ limit: opts.limit,
+ signal: opts.signal ?? controller.signal,
+ drain: opts.drain,
+ onLog: log,
+ position: { since: walk.since, until: walk.until, emptyWindows: walk.emptyWindows, ...(walk.maxId ? { maxId: walk.maxId } : {}) },
+ ...(walk.floor !== undefined ? { floor: walk.floor } : {}),
+ ...(search.windowMonths ? { months: search.windowMonths } : {}),
+ search: { query: search.query, ...(search.lang ? { lang: search.lang } : {}) },
+ windowPauseMs: opts.windowPauseMs,
+ onCheckpoint,
+ });
+ } catch (err) {
+ const message = (err as Error).message;
+ log(`[error] ${message}`);
+ // Whatever was checkpointed is on disk with its position; keep that one.
+ state = { ...state, walk: state.walk ?? walk };
+ await save(stateNow({ lastWritten: written, lastError: message }), { lastFetchedCount: written, lastError: message });
+ return { ok: false, written, skipped, complete: false, error: message };
+ }
+
+ const final = await writePosts(channelRoot, result.posts);
+ written += final.written;
+ skipped += final.skipped;
+ for (const shard of final.shards) shards.add(shard);
+ if (result.complete) {
+ const covered = coverAfterWalk(state, walk, result.position.since);
+ const reason =
+ plan.kind === "new" || (plan.kind === "resume" && state.coveredUntil)
+ ? `searched down to ${walk.floor ?? result.position.since}`
+ : (result.completeReason ?? "walked to its end");
+ const { walk: _done, ...rest } = state;
+ void _done;
+ state = { ...rest, ...covered, completeReason: reason, completedAt: new Date().toISOString() };
+ } else {
+ state = { ...state, walk: walkAt(result.position) };
+ }
+ log(
+ `Wrote ${written} matching post(s), skipped ${skipped} already archived` +
+ (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") +
+ (result.complete
+ ? ` — searched ${state.coveredSince} – ${state.coveredUntil}.`
+ : ` — the next fetch resumes at ${state.walk!.since} – ${state.walk!.until}.`),
+ );
+ if (result.error) log(`[error] ${result.error}`);
+ await save(
+ stateNow({ lastWritten: written, ...(result.error ? { lastError: result.error } : { lastError: undefined }) }),
+ {
+ lastFetchedCount: written,
+ ...(result.error ? { lastError: result.error } : {}),
+ ...(result.needsCookies ? { needsCookies: true } : {}),
+ },
+ );
+ // The scheduler paces a search channel as any posts channel: by its
+ // lastSyncedAt. A patch, re-read at write time (fetchPosts' rule).
+ await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() });
+ return {
+ ok: !result.error,
+ written,
+ skipped,
+ complete: result.complete,
+ ...(result.needsCookies ? { needsCookies: true } : {}),
+ ...(result.error ? { error: result.error } : {}),
+ ...(result.drained ? { drained: true } : {}),
+ };
+}
diff --git a/common/controller/xSearchLeads.test.ts b/common/controller/xSearchLeads.test.ts
@@ -0,0 +1,154 @@
+// An X search channel's leads, read and acted on, over a temp corpus: the
+// ranking names the accounts an X channel already archives, Never archive and
+// Restore go through the config lock and keep every other key, Archive this
+// account plans `<handle>-x` and refuses an archived account or a taken slug,
+// and no site may carry a search channel (writeSite refuses it).
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xSearchLeads.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { 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(), "xsearch-leads-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const { getPaths } = await import("../lib/paths");
+const { writePosts } = await import("../lib/posts-server");
+const { readXSearchLeads, setXSearchLeadHidden, planArchiveXLead } = await import("./xSearchLeads");
+const { writeSite, X_SEARCH_NOT_ON_A_SITE } = await import("../lib/site");
+const paths = getPaths();
+
+async function channel(slug: string, config: Record<string, unknown>): Promise<string> {
+ const dir = path.join(ROOT, "channels", slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config }));
+ return dir;
+}
+
+let n = 0;
+const post = (author: string, day: string) => {
+ n++;
+ const id = String(1899000000000000000n + BigInt(n));
+ return {
+ id,
+ slug: `demo-search/${id}`,
+ channelSlug: "demo-search",
+ author,
+ createdAt: `${day}T12:00:00.000Z`,
+ uploadDate: day.replace(/-/g, ""),
+ text: `zephyr ${n}`,
+ url: `https://x.com/${author}/status/${id}`,
+ platform: "twitter" as const,
+ isReply: false,
+ isRepost: false,
+ links: [],
+ };
+};
+
+const searchRoot = await channel("demo-search", {
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-gallery-dl",
+ url: "https://x.com/search?q=zephyr&f=live",
+ syncIntervalMinutes: 720,
+ xSearch: { query: "zephyr", since: "2025-01-01" },
+});
+await writePosts(searchRoot, [
+ post("alice", "2025-02-01"),
+ post("alice", "2025-03-01"),
+ post("bob", "2025-04-01"),
+ post("carol", "2025-05-01"),
+]);
+// bob is archived already, by handle (case aside).
+await channel("bob-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "Bob", url: "https://x.com/Bob" });
+// A slug taken by something else entirely.
+await channel("carol-x", { url: "https://www.youtube.com/@carol" });
+await channel("plain-video", { url: "https://www.youtube.com/@plain" });
+
+test("the leads: ranked, archived accounts named, the walk described", async () => {
+ const view = await readXSearchLeads(paths, "demo-search");
+ assert.ok(view.ok);
+ assert.equal(view.query, "zephyr");
+ assert.equal(view.walk, "not searched yet");
+ assert.deepEqual(view.leads.map((l) => [l.key, l.count]), [["alice", 2], ["carol", 1], ["bob", 1]]);
+ assert.deepEqual(view.leads.find((l) => l.key === "bob")?.archivedAs, ["bob-x"]);
+ const limited = await readXSearchLeads(paths, "demo-search", { limit: 1 });
+ assert.ok(limited.ok);
+ assert.equal(limited.more, 2);
+ const notSearch = await readXSearchLeads(paths, "plain-video");
+ assert.deepEqual(notSearch, { ok: false, error: "plain-video is not an X search channel (its config has no xSearch query)." });
+});
+
+test("Never archive and Restore: one handle in or out of xSearch.exclude, every other key kept", async () => {
+ const hide = await setXSearchLeadHidden(paths, "demo-search", "@Alice", true);
+ assert.deepEqual(hide, { ok: true, exclude: ["alice"], changed: true });
+ const again = await setXSearchLeadHidden(paths, "demo-search", "alice", true);
+ assert.deepEqual(again, { ok: true, exclude: ["alice"], changed: false });
+ const config = JSON.parse(await readFile(path.join(searchRoot, "config.json"), "utf8"));
+ assert.deepEqual(config.xSearch, { query: "zephyr", since: "2025-01-01", exclude: ["alice"] });
+ assert.equal(config.syncIntervalMinutes, 720);
+ const view = await readXSearchLeads(paths, "demo-search");
+ assert.ok(view.ok);
+ assert.deepEqual(view.leads.map((l) => l.key), ["carol", "bob"]);
+ assert.deepEqual(view.hidden, [{ handle: "alice", count: 2 }]);
+
+ const restore = await setXSearchLeadHidden(paths, "demo-search", "alice", false);
+ assert.deepEqual(restore, { ok: true, exclude: [], changed: true });
+ const after = JSON.parse(await readFile(path.join(searchRoot, "config.json"), "utf8"));
+ assert.deepEqual(after.xSearch, { query: "zephyr", since: "2025-01-01" });
+
+ assert.deepEqual(await setXSearchLeadHidden(paths, "demo-search", "not a handle", true), {
+ ok: false,
+ error: '"not a handle" is not an X handle (letters, digits and "_")',
+ });
+ assert.equal((await setXSearchLeadHidden(paths, "plain-video", "alice", true)).ok, false);
+});
+
+test("Archive this account: <handle>-x on no site; an archived account or a taken slug refused", async () => {
+ assert.deepEqual(await planArchiveXLead(paths, "demo-search", "Alice", "Alice A"), {
+ ok: true,
+ slug: "alice-x",
+ fields: {
+ name: "Alice A (X)",
+ handling: "transcribe",
+ url: "https://x.com/Alice",
+ platform: "twitter",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ socialHandle: "Alice",
+ },
+ });
+ assert.deepEqual(await planArchiveXLead(paths, "demo-search", "bob"), {
+ ok: false,
+ error: "@bob is already archived: bob-x.",
+ });
+ const taken = await planArchiveXLead(paths, "demo-search", "carol");
+ assert.equal(taken.ok, false);
+ assert.match((taken as { error: string }).error, /A channel "carol-x" already exists/);
+ assert.equal((await planArchiveXLead(paths, "plain-video", "alice")).ok, false);
+});
+
+test("no site may carry an X search channel, as a member or a cited channel", async () => {
+ const site = {
+ siteId: "demo-site",
+ siteTitle: "Demo",
+ siteDescription: "",
+ headerTitle: "Demo",
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [{ slug: "plain-video", groupId: "default" }],
+ };
+ await writeSite(site as never, paths);
+ await assert.rejects(
+ writeSite({ ...site, channels: [...site.channels, { slug: "demo-search", groupId: "default" }] } as never, paths),
+ { message: X_SEARCH_NOT_ON_A_SITE("demo-search") },
+ );
+ await assert.rejects(
+ writeSite({ ...site, citedChannels: [{ slug: "demo-search" }] } as never, paths),
+ { message: "demo-search is an X search channel: it is never put on a site." },
+ );
+});
diff --git a/common/controller/xSearchLeads.ts b/common/controller/xSearchLeads.ts
@@ -0,0 +1,132 @@
+// AN X SEARCH CHANNEL'S LEADS, read and acted on (release 38 lane S): the
+// accounts its matching posts came from (lib/xSearch/leads.ts ranks them),
+// and the two things the operator does with one — archive the account as its
+// own X channel (on no site; the editor's create-channel path does it, from
+// planArchiveXLead's fields) or never archive it (`xSearch.exclude`, which
+// hides it from the view). No model, no request: everything is on disk.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { readAllPosts, readPostFetchState } from "../lib/posts-server";
+import {
+ describeXSearch,
+ isXSearchChannel,
+ xLeadHandle,
+} from "../lib/xSearch/config";
+import { describeXSearchWalk } from "../lib/xSearch/walk";
+import {
+ rankXSearchLeads,
+ xLeadChannelFields,
+ xLeadChannelSlug,
+ type XSearchLeads,
+} from "../lib/xSearch/leads";
+import { handleFromAccountUrl } from "../social/fetchers";
+import { channelExists, listChannelConfigs, patchChannelConfig, readChannelConfig } from "./channels";
+
+export const NOT_AN_X_SEARCH_CHANNEL = (slug: string) =>
+ `${slug} is not an X search channel (its config has no xSearch query).`;
+
+// X channels that archive ONE account (not a search), by lower-case handle.
+export async function archivedXAccounts(paths: Paths): Promise<Map<string, string[]>> {
+ const out = new Map<string, string[]>();
+ for (const { slug, config } of await listChannelConfigs(paths)) {
+ if (config.sourceKind !== "social" || config.platform !== "twitter" || isXSearchChannel(config)) continue;
+ const handle = xLeadHandle(config.socialHandle ?? handleFromAccountUrl(config.url ?? "") ?? "");
+ if (!handle) continue;
+ out.set(handle, [...(out.get(handle) ?? []), slug]);
+ }
+ return out;
+}
+
+export type XSearchLeadsView = XSearchLeads & {
+ ok: true;
+ slug: string;
+ query: string;
+ search: string; // describeXSearch
+ walk: string; // describeXSearchWalk
+};
+
+export async function readXSearchLeads(
+ paths: Paths,
+ slug: string,
+ opts: { limit?: number } = {},
+): Promise<XSearchLeadsView | { ok: false; error: string }> {
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isXSearchChannel(config) || !config.xSearch) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) };
+ const channelRoot = path.join(paths.channelsDir, slug);
+ const [posts, state, archived] = await Promise.all([
+ readAllPosts(channelRoot),
+ readPostFetchState(channelRoot),
+ archivedXAccounts(paths),
+ ]);
+ return {
+ ok: true,
+ slug,
+ query: config.xSearch.query,
+ search: describeXSearch(config.xSearch),
+ walk: describeXSearchWalk(state?.search),
+ ...rankXSearchLeads(posts, {
+ exclude: config.xSearch.exclude,
+ archived,
+ ...(opts.limit !== undefined ? { limit: opts.limit } : {}),
+ }),
+ };
+}
+
+// "Never archive" (hidden = true) and its undo: the handle into, or out of,
+// the channel's `xSearch.exclude`, re-read and written under the config lock.
+export async function setXSearchLeadHidden(
+ paths: Paths,
+ slug: string,
+ handle: string,
+ hidden: boolean,
+): Promise<{ ok: true; exclude: string[]; changed: boolean } | { ok: false; error: string }> {
+ const key = xLeadHandle(handle);
+ if (!key) return { ok: false, error: `"${handle}" is not an X handle (letters, digits and "_")` };
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isXSearchChannel(config)) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) };
+ let changed = false;
+ let exclude: string[] = [];
+ const written = await patchChannelConfig(paths, slug, {}, {
+ derive: (current: ChannelConfig) => {
+ if (!current.xSearch) return {};
+ const was = current.xSearch.exclude ?? [];
+ exclude = hidden ? (was.includes(key) ? was : [...was, key]) : was.filter((h) => h !== key);
+ changed = exclude.length !== was.length;
+ const { exclude: _old, ...rest } = current.xSearch;
+ void _old;
+ return { xSearch: exclude.length > 0 ? { ...rest, exclude } : rest };
+ },
+ });
+ if (!written) return { ok: false, error: `No such channel: ${slug}` };
+ return { ok: true, exclude, changed };
+}
+
+export const LEAD_ALREADY_ARCHIVED = (handle: string, slugs: string[]) =>
+ `@${handle} is already archived: ${slugs.join(", ")}.`;
+
+// What "Archive this account" creates: `<handle>-x`, an X account channel on
+// NO site, with the New channel form's fields. Refused when the account is
+// already archived by an X channel, or the slug is taken.
+export async function planArchiveXLead(
+ paths: Paths,
+ slug: string,
+ handle: string,
+ name?: string,
+): Promise<{ ok: true; slug: string; fields: Record<string, string> } | { ok: false; error: string }> {
+ const key = xLeadHandle(handle);
+ if (!key) return { ok: false, error: `"${handle}" is not an X handle (letters, digits and "_")` };
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isXSearchChannel(config)) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) };
+ const archived = (await archivedXAccounts(paths)).get(key);
+ if (archived && archived.length > 0) return { ok: false, error: LEAD_ALREADY_ARCHIVED(handle.replace(/^@/, ""), archived) };
+ const newSlug = xLeadChannelSlug(key);
+ if (await channelExists(paths, newSlug)) {
+ return { ok: false, error: `A channel "${newSlug}" already exists; create @${key}'s channel by hand with another slug.` };
+ }
+ return { ok: true, slug: newSlug, fields: xLeadChannelFields({ handle: handle.replace(/^@/, ""), ...(name ? { name } : {}) }) };
+}
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -1,5 +1,6 @@
import { PLATFORM_VALUES, type Platform } from "./platform";
import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config";
+import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config";
import {
isDownloadFormatPreset,
isSourceVideoQuality,
@@ -160,6 +161,8 @@ export type ChannelConfig = {
mirror?: MirrorConfig;
// Release 37: a Wayback pages channel's scope (lib/waybackPages/config.ts).
wayback?: WaybackPagesConfig;
+ // Release 38: an X search channel's query (lib/xSearch/config.ts).
+ xSearch?: XSearchConfig;
};
// In the order parseChannelConfig emits (and CHANNEL.md lists) them.
@@ -228,6 +231,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
"For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped.",
wayback:
'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked.',
+ xSearch:
+ 'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.',
};
// Every key a config.json may carry, in emission order. The unknown-key oracle:
@@ -436,6 +441,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
recordedDate: coerceRecordedDateRule,
mirror: coerceMirrorConfig,
wayback: coerceWaybackPagesConfig,
+ xSearch: coerceXSearchConfig,
};
// A channel's config.json as a ChannelConfig, or null when it is not a channel
diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 37); // release 37: `wayback`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 38); // release 38: `xSearch`
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -80,6 +80,7 @@ export const channelConfigObjectSchema = z.object({
recordedDate: field("recordedDate"),
mirror: field("mirror"),
wayback: field("wayback"),
+ xSearch: field("xSearch"),
});
// Drop every own key whose value is `undefined` (the OMIT rule, above).
diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts
@@ -491,6 +491,32 @@ export type PostFetchState = {
// `cursor` so a normal fetch never resumes backwards, and carried through
// every write a normal fetch makes.
older?: OlderBackfillState;
+ // An X SEARCH channel's walk (release 38, controller/fetchXSearch.ts): its
+ // only walk — it has no timeline and no older walk.
+ search?: XSearchWalkState;
+};
+
+// Where an X search channel's walk stands. A walk goes BACKWARDS in search
+// windows from a `top` day to a `floor`; what finished walks have searched
+// end to end is [coveredSince, coveredUntil). A later fetch walks only what
+// is outside it: the new days above, and below when `since` is moved earlier.
+export type XSearchWalkState = {
+ // The query (and language) this state belongs to (xSearchQueryKey): a
+ // change of query starts the walk afresh.
+ queryKey: string;
+ // The walk in progress, when one is: its bounds and its position.
+ walk?: OlderBackfillPosition & {
+ top: string; // YYYY-MM-DD, exclusive — the first window's `until`
+ floor?: string; // YYYY-MM-DD — the walk stops there; absent = after empty windows
+ };
+ coveredSince?: string;
+ coveredUntil?: string;
+ // Why the last walk to finish ended, as a sentence.
+ completeReason?: string;
+ completedAt?: string;
+ lastRunAt?: string;
+ lastWritten?: number;
+ lastError?: string;
};
// Where the older-posts backfill stands. The window is in UTC days, as X's
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -11,6 +11,8 @@ import {
type SocialLink,
} from "./settings";
import { socialLinksForSave } from "./socialLinks";
+import { parseChannelConfig } from "./channelConfig";
+import { isXSearchChannel } from "./xSearch/config";
import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
import {
isListedSite,
@@ -226,6 +228,24 @@ function storedSocialLinks(file: string): SocialLink[] {
}
}
+export const X_SEARCH_NOT_ON_A_SITE = (slug: string) =>
+ `${slug} is an X search channel: it is never put on a site.`;
+
+// The first member of `site` (or of its cited scope) that is an X search
+// channel, by its config.json — or null. One small read per member.
+export function xSearchChannelOnSite(
+ site: Pick<Site, "channels" | "citedChannels">,
+ paths: Paths,
+): string | null {
+ const slugs = [...site.channels.map((c) => c.slug), ...(site.citedChannels ?? []).map((c) => c.slug)];
+ for (const slug of slugs) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) continue;
+ const raw = readJsonFileSync(path.join(paths.channelsDir, slug, "config.json"));
+ if (raw.ok && isXSearchChannel(parseChannelConfig(raw.value))) return slug;
+ }
+ return null;
+}
+
export async function writeSite(
site: Site,
paths: Paths = getPaths(),
@@ -252,6 +272,10 @@ export async function writeSite(
// A search-off site publishes only its pages: one with none is refused (D5).
const searchProblem = siteSearchProblem(site);
if (searchProblem) throw new Error(searchProblem);
+ // An X search channel is never put on a site (release 38): refused here, at
+ // the one writer every site edit goes through.
+ const searchChannel = xSearchChannelOnSite(site, paths);
+ if (searchChannel) throw new Error(X_SEARCH_NOT_ON_A_SITE(searchChannel));
// undefined socialLinks = inherit the global default; only validate/persist a
// key when the site explicitly overrides (an array, even empty).
// A link whose SVG is unchanged from the file on disk is kept as it is; a new
diff --git a/common/lib/xSearch/config.test.ts b/common/lib/xSearch/config.test.ts
@@ -0,0 +1,145 @@
+// An X search channel's config: the query passes X's operators through, the
+// walk's own operators are refused, a URL copied from X becomes a config with
+// its dates lifted out, and the window query is the operator's terms plus the
+// window. Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/config.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ coerceXSearchConfig,
+ describeXSearch,
+ isXSearchChannel,
+ isXSearchUrl,
+ xLeadHandle,
+ xQueryHasLang,
+ xQueryTerms,
+ xSearchFromUrl,
+ xSearchQueryKey,
+ xSearchQueryOfUrl,
+ xSearchQueryProblem,
+ xSearchUrl,
+ xSearchWindowQuery,
+} from "./config";
+import { parseChannelConfig } from "../channelConfig";
+
+test("X's operators pass through untouched", () => {
+ for (const q of [
+ "zephyr",
+ '"exact phrase" OR other',
+ "zephyr -noise -from:spam_bot",
+ "from:alice OR from:bob",
+ "to:alice @bob url:example.com",
+ "zephyr filter:links lang:en",
+ "(zephyr OR archive) min_faves:10",
+ "#tag $cash",
+ ]) {
+ assert.equal(xSearchQueryProblem(q), null, q);
+ }
+});
+
+test("an empty query, a two-line one, an open quote and the walk's own operators are refused", () => {
+ assert.match(xSearchQueryProblem("")!, /needs a query/);
+ assert.match(xSearchQueryProblem(" ")!, /needs a query/);
+ assert.match(xSearchQueryProblem(undefined)!, /needs a query/);
+ assert.match(xSearchQueryProblem("a\nb")!, /one line/);
+ assert.match(xSearchQueryProblem('"open phrase')!, /quote open/);
+ assert.match(xSearchQueryProblem("x".repeat(501))!, /at most 500/);
+ const dated = xSearchQueryProblem("zephyr since:2020-01-01 until:2021-01-01")!;
+ assert.match(dated, /Take since:, until: out of the query/);
+ assert.match(dated, /since and until dates set the search windows/);
+ assert.match(xSearchQueryProblem("zephyr max_id:123")!, /max_id:/);
+ assert.match(xSearchQueryProblem("zephyr SINCE:2020-01-01")!, /since:/);
+ assert.match(xSearchQueryProblem("zephyr -until:2020-01-01")!, /until:/);
+ // Inside a phrase it is text, not an operator.
+ assert.equal(xSearchQueryProblem('"since:2020 was a year"'), null);
+});
+
+test("terms split outside quotes", () => {
+ assert.deepEqual(xQueryTerms('a "b c" d'), ["a", '"b c"', "d"]);
+ assert.equal(xQueryTerms('a "b'), null);
+ assert.equal(xQueryHasLang("zephyr lang:de"), true);
+ assert.equal(xQueryHasLang("zephyr -lang:de"), false);
+ assert.equal(xQueryHasLang('"lang:de"'), false);
+});
+
+test("a search URL from X: its query, + as a space, dates lifted out", () => {
+ const url = "https://x.com/search?q=%22zephyr%20archive%22+OR+zephyrs%20since%3A2021-01-01%20until%3A2022-06-30&src=typed_query&f=live";
+ assert.equal(isXSearchUrl(url), true);
+ assert.equal(xSearchQueryOfUrl(url), '"zephyr archive" OR zephyrs since:2021-01-01 until:2022-06-30');
+ assert.deepEqual(xSearchFromUrl(url), {
+ query: '"zephyr archive" OR zephyrs',
+ since: "2021-01-01",
+ until: "2022-06-30",
+ });
+ assert.equal(isXSearchUrl("https://twitter.com/search?q=zephyr"), true);
+ assert.equal(isXSearchUrl("https://mobile.twitter.com/search/?q=zephyr"), true);
+ assert.equal(isXSearchUrl("https://x.com/search?q="), false);
+ assert.equal(isXSearchUrl("https://x.com/zephyr"), false);
+ assert.equal(isXSearchUrl("https://example.com/search?q=zephyr"), false);
+ assert.equal(xSearchFromUrl("https://x.com/zephyr"), null);
+ // A date that is not a day stays in the query (and is refused there).
+ assert.deepEqual(xSearchFromUrl("https://x.com/search?q=a%20since%3A2021-02-30"), { query: "a since:2021-02-30" });
+});
+
+test("the stored URL is the search page of the query, encoded whole", () => {
+ assert.equal(xSearchUrl('"a b" c+d'), "https://x.com/search?q=%22a%20b%22%20c%2Bd&f=live");
+ assert.equal(xSearchQueryOfUrl(xSearchUrl('"a b" c+d')), '"a b" c+d');
+});
+
+test("the coercion keeps what is valid and drops the rest, one member at a time", () => {
+ assert.equal(coerceXSearchConfig({ query: "" }), undefined);
+ assert.equal(coerceXSearchConfig({ query: "a since:2020-01-01" }), undefined);
+ assert.equal(coerceXSearchConfig("zephyr"), undefined);
+ assert.deepEqual(
+ coerceXSearchConfig({
+ query: " zephyr ",
+ since: "2020-01-01",
+ until: "2019-12-31",
+ windowMonths: 13,
+ lang: "EN",
+ exclude: ["@Alice", "alice", "bad handle", 3],
+ extra: true,
+ }),
+ { query: "zephyr", since: "2020-01-01", lang: "en", exclude: ["alice"] },
+ );
+ assert.deepEqual(coerceXSearchConfig({ query: "z", until: "2021-01-01", windowMonths: 1 }), {
+ query: "z",
+ until: "2021-01-01",
+ windowMonths: 1,
+ });
+});
+
+test("a channel config carries xSearch through the one set of coercions", () => {
+ const config = parseChannelConfig({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ url: xSearchUrl("zephyr"),
+ xSearch: { query: "zephyr", since: "2024-01-01" },
+ });
+ assert.deepEqual(config?.xSearch, { query: "zephyr", since: "2024-01-01" });
+ assert.equal(isXSearchChannel(config), true);
+ assert.equal(isXSearchChannel({ sourceKind: "social", platform: "twitter" }), false);
+ assert.equal(isXSearchChannel({ sourceKind: "social", platform: "bluesky", xSearch: { query: "a" } }), false);
+});
+
+test("one window's query: the operator's terms, the language, the window and the resume point", () => {
+ assert.equal(
+ xSearchWindowQuery({ query: '"zephyr archive" OR -noise from:alice', lang: "en" }, { since: "2024-01-01", until: "2024-04-01" }),
+ '"zephyr archive" OR -noise from:alice lang:en since:2024-01-01 until:2024-04-01',
+ );
+ assert.equal(
+ xSearchWindowQuery({ query: "zephyr lang:de", lang: "en" }, { since: "2024-01-01", until: "2024-04-01", maxId: "1899" }),
+ "zephyr lang:de since:2024-01-01 until:2024-04-01 max_id:1899",
+ );
+ assert.throws(() => xSearchWindowQuery({ query: "a until:2020-01-01" }, { since: "2024-01-01", until: "2024-04-01" }), /until:/);
+ assert.throws(() => xSearchWindowQuery({ query: "a" }, { since: "2024-01-01", until: "2024-04-01", maxId: "x1" }), /not a post id/);
+});
+
+test("the query key ignores the dates; leads' handles are lower case", () => {
+ assert.equal(xSearchQueryKey({ query: " zephyr ", lang: "en" }), "zephyr lang:en");
+ assert.equal(xSearchQueryKey({ query: "zephyr" }), "zephyr");
+ assert.equal(xLeadHandle("@Alice_1"), "alice_1");
+ assert.equal(xLeadHandle("not a handle"), null);
+ assert.match(describeXSearch({ query: "zephyr", since: "2024-01-01" }), /zephyr · since 2024-01-01/);
+});
diff --git a/common/lib/xSearch/config.ts b/common/lib/xSearch/config.ts
@@ -0,0 +1,253 @@
+// AN X SEARCH CHANNEL (release 38 lane S, plans/release-38/x-search.md): a saved
+// X search across accounts — a posts channel on platform "twitter",
+// `sourceKind: "social"`, whose records are the posts that match ONE query,
+// from any author. `config.xSearch` holds the query and the dates it is walked
+// between; the walk itself (search windows, newest first, resumable) is the
+// older-posts backfill's, with the operator's query in place of `from:<handle>`.
+//
+// Client-safe and a LEAF (no imports): lib/channelConfig.ts composes the
+// coercion below into its one set of coercions, and the channel form imports
+// the URL and query helpers.
+
+export type XSearchConfig = {
+ // The query, as X's search box takes it: words, "quoted phrases", OR,
+ // -term, from:/to:/@mention, url:, filter:, lang:, … — passed through as
+ // typed. Never since:/until: (the windows add those) or max_id: and its
+ // kin (the walk pages with max_id).
+ query: string;
+ // The earliest day searched (YYYY-MM-DD, inclusive): the walk stops there.
+ // Absent: it stops after a year of windows in a row with no match.
+ since?: string;
+ // The day the walk starts below (YYYY-MM-DD, exclusive, as X's until:).
+ // Absent: tomorrow — and each later fetch searches what is new since.
+ until?: string;
+ // Each search window's span in months (1–12). Absent: 3, the older walk's.
+ windowMonths?: number;
+ // A language code (en, de, pt-br …): `lang:<code>` is added to the query
+ // unless it names a lang: of its own.
+ lang?: string;
+ // Authors hidden from the leads view ("Never archive"), bare handles in
+ // lower case. The search itself is not narrowed by them.
+ exclude?: string[];
+};
+
+export const X_SEARCH_QUERY_MAX = 500;
+export const X_SEARCH_WINDOW_MONTHS_MAX = 12;
+
+// The operators the walk writes itself, refused in a query. since:/until:
+// bound the windows; max_id: is the walk's resume point (gallery-dl rewrites
+// it after every page); the others would fight both.
+const RESERVED_OPERATORS = ["since", "until", "max_id", "since_id", "until_id", "since_time", "until_time"];
+
+const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
+const HANDLE_RE = /^[A-Za-z0-9_]{1,50}$/;
+const LANG_RE = /^[a-z]{2,3}(?:-[a-z]{2,4})?$/;
+
+function isDay(v: unknown): v is string {
+ if (typeof v !== "string" || !DAY_RE.test(v)) return false;
+ const ms = Date.parse(`${v}T00:00:00Z`);
+ return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === v;
+}
+
+// The query's terms, split on whitespace OUTSIDE double quotes: a quoted
+// phrase is one term, quotes kept. Null when a quote is left open.
+export function xQueryTerms(query: string): string[] | null {
+ const terms: string[] = [];
+ let cur = "";
+ let quoted = false;
+ for (const ch of query) {
+ if (ch === '"') {
+ quoted = !quoted;
+ cur += ch;
+ continue;
+ }
+ if (!quoted && /\s/.test(ch)) {
+ if (cur) terms.push(cur);
+ cur = "";
+ continue;
+ }
+ cur += ch;
+ }
+ if (quoted) return null;
+ if (cur) terms.push(cur);
+ return terms;
+}
+
+// The operator name a term uses (`-from:x` → "from"), or null for a plain word
+// or a phrase.
+function operatorOf(term: string): string | null {
+ const m = /^[-(]*([A-Za-z_]+):/.exec(term);
+ return m ? m[1].toLowerCase() : null;
+}
+
+// Why this query cannot be an X search channel's, as a sentence — or null.
+export function xSearchQueryProblem(query: unknown): string | null {
+ if (typeof query !== "string" || !query.trim()) {
+ return "An X search channel needs a query (what you would type in X's search box).";
+ }
+ const q = query.trim();
+ if (q.length > X_SEARCH_QUERY_MAX) {
+ return `An X search query is at most ${X_SEARCH_QUERY_MAX} characters (this one is ${q.length}).`;
+ }
+ if (/[\r\n]/.test(q)) return "An X search query is one line.";
+ const terms = xQueryTerms(q);
+ if (!terms) return "The X search query leaves a quote open.";
+ const reserved = [
+ ...new Set(
+ terms
+ .map(operatorOf)
+ .filter((op): op is string => op !== null && RESERVED_OPERATORS.includes(op)),
+ ),
+ ];
+ if (reserved.length > 0) {
+ return (
+ `Take ${reserved.map((op) => `${op}:`).join(", ")} out of the query: ` +
+ "the channel's since and until dates set the search windows, and the walk adds them itself."
+ );
+ }
+ return null;
+}
+
+// True when the query names a lang: of its own.
+export function xQueryHasLang(query: string): boolean {
+ return (xQueryTerms(query) ?? []).some((t) => operatorOf(t) === "lang" && !t.startsWith("-"));
+}
+
+// A bare X handle in lower case, or null.
+export function xLeadHandle(input: unknown): string | null {
+ if (typeof input !== "string") return null;
+ const bare = input.trim().replace(/^@/, "");
+ return HANDLE_RE.test(bare) ? bare.toLowerCase() : null;
+}
+
+// `config.xSearch`: an object with a valid query, else omitted. The optional
+// members are omitted one by one when invalid, never repaired; an `until` at
+// or before `since` drops `until`.
+export function coerceXSearchConfig(v: unknown): XSearchConfig | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ if (xSearchQueryProblem(r.query) !== null) return undefined;
+ const out: XSearchConfig = { query: (r.query as string).trim() };
+ if (isDay(r.since)) out.since = r.since;
+ if (isDay(r.until) && !(out.since && r.until <= out.since)) out.until = r.until;
+ if (
+ typeof r.windowMonths === "number" &&
+ Number.isInteger(r.windowMonths) &&
+ r.windowMonths >= 1 &&
+ r.windowMonths <= X_SEARCH_WINDOW_MONTHS_MAX
+ ) {
+ out.windowMonths = r.windowMonths;
+ }
+ if (typeof r.lang === "string" && LANG_RE.test(r.lang.trim().toLowerCase())) {
+ out.lang = r.lang.trim().toLowerCase();
+ }
+ if (Array.isArray(r.exclude)) {
+ const handles = [...new Set(r.exclude.map(xLeadHandle).filter((h): h is string => h !== null))];
+ if (handles.length > 0) out.exclude = handles;
+ }
+ return out;
+}
+
+// An X search channel: a posts channel on platform "twitter" with a query.
+// Structural, so this leaf needs no import of the channel config's type.
+export function isXSearchChannel(
+ config: { sourceKind?: string; platform?: string; xSearch?: unknown } | null | undefined,
+): boolean {
+ return config?.sourceKind === "social" && config.platform === "twitter" && Boolean(config.xSearch);
+}
+
+const X_HOST_RE = /^(?:www\.|mobile\.)?(?:x|twitter)\.com$/i;
+
+// X's search page for a query — the URL a search channel stores, and the one
+// gallery-dl's search extractor matches. The query is percent-encoded whole
+// (gallery-dl turns "+" into a space BEFORE it unquotes, so an encoded "+"
+// survives); `f=live` is X's "Latest" tab.
+export function xSearchUrl(query: string): string {
+ return `https://x.com/search?q=${encodeURIComponent(query)}&f=live`;
+}
+
+// The query of an X search page URL (x.com or twitter.com /search?q=…), or
+// null. `+` reads as a space, as X writes it.
+export function xSearchQueryOfUrl(input: string | undefined | null): string | null {
+ if (!input) return null;
+ let u: URL;
+ try {
+ u = new URL(input.trim());
+ } catch {
+ return null;
+ }
+ if (!X_HOST_RE.test(u.hostname)) return null;
+ if (u.pathname.replace(/\/+$/, "") !== "/search") return null;
+ const q = u.searchParams.get("q");
+ return q && q.trim() ? q.trim() : null;
+}
+
+export function isXSearchUrl(input: string | undefined | null): boolean {
+ return xSearchQueryOfUrl(input) !== null;
+}
+
+// A search channel's config from a URL copied out of X: its query, with any
+// one since:/until: day lifted out into the channel's dates (X writes them in
+// the query; the channel keeps them apart). Anything else stays in the query,
+// to be refused or kept by xSearchQueryProblem.
+export function xSearchFromUrl(input: string | undefined | null): XSearchConfig | null {
+ const raw = xSearchQueryOfUrl(input);
+ if (raw === null) return null;
+ const terms = xQueryTerms(raw);
+ if (!terms) return { query: raw };
+ const out: XSearchConfig = { query: "" };
+ const kept: string[] = [];
+ for (const term of terms) {
+ const m = /^(since|until):(\d{4}-\d{2}-\d{2})$/i.exec(term);
+ const key = m?.[1].toLowerCase() as "since" | "until" | undefined;
+ if (m && key && isDay(m[2]) && out[key] === undefined) {
+ out[key] = m[2];
+ continue;
+ }
+ kept.push(term);
+ }
+ out.query = kept.join(" ");
+ return out;
+}
+
+// What the walk's saved state belongs to: a change of query or language starts
+// the walk afresh. The dates are not in it — widening them walks only what is
+// newly in range.
+export function xSearchQueryKey(config: Pick<XSearchConfig, "query" | "lang">): string {
+ return `${config.query.trim()}${config.lang ? ` lang:${config.lang}` : ""}`;
+}
+
+// The query for ONE window: the operator's terms, the language, the window's
+// days and, inside a window, the resume point. Throws on a query the channel
+// could not hold (the fetcher never runs one).
+export function xSearchWindowQuery(
+ config: Pick<XSearchConfig, "query" | "lang">,
+ position: { since: string; until: string; maxId?: string },
+): string {
+ const problem = xSearchQueryProblem(config.query);
+ if (problem) throw new Error(problem);
+ if (!isDay(position.since) || !isDay(position.until)) {
+ throw new Error(`"${position.since} – ${position.until}" is not a window of days`);
+ }
+ const terms = [config.query.trim()];
+ if (config.lang && !xQueryHasLang(config.query)) terms.push(`lang:${config.lang}`);
+ terms.push(`since:${position.since}`, `until:${position.until}`);
+ if (position.maxId) {
+ if (!/^\d+$/.test(position.maxId)) throw new Error(`"${position.maxId}" is not a post id`);
+ terms.push(`max_id:${position.maxId}`);
+ }
+ return terms.join(" ");
+}
+
+// One line for the channel page and the ops read.
+export function describeXSearch(config: XSearchConfig): string {
+ const range =
+ config.since && config.until
+ ? `${config.since} – ${config.until}`
+ : config.since
+ ? `since ${config.since}`
+ : config.until
+ ? `before ${config.until}`
+ : "all dates";
+ return `${config.query}${config.lang ? ` (lang ${config.lang})` : ""} · ${range}`;
+}
diff --git a/common/lib/xSearch/leads.test.ts b/common/lib/xSearch/leads.test.ts
@@ -0,0 +1,106 @@
+// An X search channel's leads: authors ranked by matching posts, a sample the
+// account wrote itself, hidden handles kept apart, accounts already archived
+// named, and the channel an "Archive this account" makes.
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/leads.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { Post } from "../posts";
+import { rankXSearchLeads, xLeadChannelFields, xLeadChannelSlug } from "./leads";
+
+let n = 0;
+function post(author: string, createdAt: string, extra: Partial<Post> = {}): Post {
+ n++;
+ const id = String(1899000000000000000n + BigInt(n));
+ return {
+ id,
+ slug: `demo-search/${id}`,
+ channelSlug: "demo-search",
+ author,
+ createdAt,
+ uploadDate: createdAt.slice(0, 10).replace(/-/g, ""),
+ text: `post ${n} by ${author} about zephyr`,
+ url: `https://x.com/${author}/status/${id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ ...extra,
+ };
+}
+
+test("most matches first, then the most recent, then the handle", () => {
+ const posts = [
+ post("alice", "2026-01-01T00:00:00.000Z", { authorName: "Alice A" }),
+ post("Alice", "2026-03-01T00:00:00.000Z", { authorName: "Alice B" }),
+ post("alice", "2026-02-01T00:00:00.000Z", { isRepost: true }),
+ post("bob", "2026-04-01T00:00:00.000Z"),
+ post("carol", "2026-05-01T00:00:00.000Z"),
+ post("dave", "2026-05-01T00:00:00.000Z"),
+ ];
+ // The same post read twice (two shards) counts once.
+ const out = rankXSearchLeads([...posts, posts[0]]);
+ assert.deepEqual(
+ out.leads.map((l) => [l.key, l.count]),
+ [["alice", 3], ["carol", 1], ["dave", 1], ["bob", 1]],
+ );
+ const alice = out.leads[0];
+ assert.equal(alice.handle, "Alice");
+ assert.equal(alice.name, "Alice B");
+ assert.equal(alice.reposts, 1);
+ assert.equal(alice.first, "2026-01-01T00:00:00.000Z");
+ assert.equal(alice.last, "2026-03-01T00:00:00.000Z");
+ assert.equal(alice.sample.id, posts[1].id);
+ assert.equal(out.posts, 6);
+ assert.equal(out.authors, 4);
+ assert.equal(out.more, 0);
+});
+
+test("the sample is the account's own newest post, else its newest repost; long text is cut", () => {
+ const own = post("erin", "2026-01-01T00:00:00.000Z", { text: "x".repeat(400) });
+ const repost = post("erin", "2026-06-01T00:00:00.000Z", { isRepost: true });
+ const [erin] = rankXSearchLeads([own, repost]).leads;
+ assert.equal(erin.sample.id, own.id);
+ assert.equal(erin.sample.text.length, 280);
+ assert.ok(erin.sample.text.endsWith("…"));
+ const [only] = rankXSearchLeads([post("fay", "2026-01-01T00:00:00.000Z", { isRepost: true })]).leads;
+ assert.equal(only.sample.createdAt, "2026-01-01T00:00:00.000Z");
+});
+
+test("hidden handles are kept apart, archived accounts named, the list capped", () => {
+ const posts = [
+ post("alice", "2026-01-01T00:00:00.000Z"),
+ post("alice", "2026-01-02T00:00:00.000Z"),
+ post("bob", "2026-01-03T00:00:00.000Z"),
+ post("carol", "2026-01-04T00:00:00.000Z"),
+ ];
+ const out = rankXSearchLeads(posts, {
+ exclude: ["ALICE", "ghost"],
+ archived: new Map([["bob", ["bob-x", "bob-x-replies"]]]),
+ limit: 1,
+ });
+ assert.deepEqual(out.leads.map((l) => l.key), ["carol"]);
+ assert.equal(out.more, 1);
+ assert.deepEqual(out.hidden, [
+ { handle: "alice", count: 2 },
+ { handle: "ghost", count: 0 },
+ ]);
+ const all = rankXSearchLeads(posts, { archived: new Map([["bob", ["bob-x-replies", "bob-x"]]]) });
+ assert.deepEqual(all.leads.find((l) => l.key === "bob")?.archivedAs, ["bob-x", "bob-x-replies"]);
+});
+
+test("Archive this account makes <handle>-x with the form's fields", () => {
+ assert.equal(xLeadChannelSlug("@Some_Account"), "some_account-x");
+ assert.equal(xLeadChannelSlug("_under"), "x_under-x");
+ assert.throws(() => xLeadChannelSlug("not one"), /not an X handle/);
+ assert.deepEqual(xLeadChannelFields({ handle: "Some_Account", name: "Some Account" }), {
+ name: "Some Account (X)",
+ handling: "transcribe",
+ url: "https://x.com/Some_Account",
+ platform: "twitter",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ socialHandle: "Some_Account",
+ });
+ assert.equal(xLeadChannelFields({ handle: "@bob" }).name, "bob (X)");
+});
diff --git a/common/lib/xSearch/leads.ts b/common/lib/xSearch/leads.ts
@@ -0,0 +1,153 @@
+// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): the accounts its matching
+// posts came from, ranked by how many — the "who keeps saying this" view the
+// operator acts on (Archive this account / Never archive). Pure: posts in,
+// rows out; no model. controller/xSearchLeads.ts reads the posts and the
+// channels it needs.
+
+import type { Post } from "../posts";
+import { xLeadHandle } from "./config";
+
+export type XSearchLeadSample = {
+ id: string;
+ url: string;
+ text: string;
+ createdAt: string;
+};
+
+export type XSearchLead = {
+ // The handle as the newest post writes it; `key` is its lower case.
+ handle: string;
+ key: string;
+ name?: string;
+ // Matching posts by this account (its reposts among them).
+ count: number;
+ reposts: number;
+ first: string; // ISO, the oldest matching post
+ last: string; // ISO, the newest
+ // The newest matching post the account wrote itself (else its newest repost).
+ sample: XSearchLeadSample;
+ // Posts channels already archiving this account (an X channel whose handle
+ // is this one), when there are.
+ archivedAs?: string[];
+};
+
+export type XSearchLeads = {
+ leads: XSearchLead[];
+ // Authors hidden by "Never archive", with their counts.
+ hidden: Array<{ handle: string; count: number }>;
+ // Matching posts read, and distinct authors among them (hidden included).
+ posts: number;
+ authors: number;
+ // Leads past `limit` that were not listed.
+ more: number;
+};
+
+export const X_SEARCH_LEADS_DEFAULT_LIMIT = 100;
+export const X_SEARCH_LEAD_SAMPLE_CHARS = 280;
+
+function sampleOf(p: Post): XSearchLeadSample {
+ const text = p.text.replace(/\s+/g, " ").trim();
+ return {
+ id: p.id,
+ url: p.url,
+ text: text.length > X_SEARCH_LEAD_SAMPLE_CHARS ? `${text.slice(0, X_SEARCH_LEAD_SAMPLE_CHARS - 1)}…` : text,
+ createdAt: p.createdAt,
+ };
+}
+
+// Ranked: most matching posts first, then the most recent, then by handle.
+// A post is counted once by id, whatever its shard.
+export function rankXSearchLeads(
+ posts: ReadonlyArray<Post>,
+ opts: {
+ exclude?: ReadonlyArray<string>;
+ // Lower-case handle → the slugs of X channels that archive it.
+ archived?: ReadonlyMap<string, string[]>;
+ limit?: number;
+ } = {},
+): XSearchLeads {
+ const exclude = new Set((opts.exclude ?? []).map((h) => h.toLowerCase()));
+ type Acc = { lead: XSearchLead; own?: Post; anyNewest: Post; newestAt: string };
+ const byKey = new Map<string, Acc>();
+ const seen = new Set<string>();
+ for (const p of posts) {
+ if (seen.has(p.id)) continue;
+ seen.add(p.id);
+ const key = xLeadHandle(p.author);
+ if (!key) continue;
+ let acc = byKey.get(key);
+ if (!acc) {
+ acc = {
+ lead: {
+ handle: p.author.replace(/^@/, ""),
+ key,
+ count: 0,
+ reposts: 0,
+ first: p.createdAt,
+ last: p.createdAt,
+ sample: sampleOf(p),
+ },
+ anyNewest: p,
+ newestAt: p.createdAt,
+ };
+ byKey.set(key, acc);
+ }
+ const lead = acc.lead;
+ lead.count++;
+ if (p.isRepost) lead.reposts++;
+ if (p.createdAt < lead.first) lead.first = p.createdAt;
+ if (p.createdAt > lead.last) lead.last = p.createdAt;
+ if (p.createdAt >= acc.newestAt) {
+ acc.newestAt = p.createdAt;
+ acc.anyNewest = p;
+ lead.handle = p.author.replace(/^@/, "");
+ if (p.authorName) lead.name = p.authorName;
+ } else if (!lead.name && p.authorName) {
+ lead.name = p.authorName;
+ }
+ if (!p.isRepost && (!acc.own || p.createdAt > acc.own.createdAt)) acc.own = p;
+ }
+ const all = [...byKey.values()].map((acc) => {
+ acc.lead.sample = sampleOf(acc.own ?? acc.anyNewest);
+ const slugs = opts.archived?.get(acc.lead.key);
+ if (slugs && slugs.length > 0) acc.lead.archivedAs = [...slugs].sort();
+ return acc.lead;
+ });
+ all.sort(
+ (a, b) => b.count - a.count || (b.last > a.last ? 1 : b.last < a.last ? -1 : 0) || a.key.localeCompare(b.key),
+ );
+ const shown = all.filter((l) => !exclude.has(l.key));
+ const hidden = all.filter((l) => exclude.has(l.key)).map((l) => ({ handle: l.handle, count: l.count }));
+ // A handle excluded that matched nothing (yet) is still listed as hidden.
+ for (const h of exclude) if (!byKey.has(h)) hidden.push({ handle: h, count: 0 });
+ const limit = opts.limit ?? X_SEARCH_LEADS_DEFAULT_LIMIT;
+ return {
+ leads: shown.slice(0, limit),
+ hidden,
+ posts: seen.size,
+ authors: byKey.size,
+ more: Math.max(0, shown.length - limit),
+ };
+}
+
+// The channel an "Archive this account" makes: `<handle>-x`, on no site. The
+// New channel form's field names (create-channel's `fields`).
+export function xLeadChannelSlug(handle: string): string {
+ const key = xLeadHandle(handle);
+ if (!key) throw new Error(`"${handle}" is not an X handle (letters, digits and "_")`);
+ // A slug starts with a letter or a digit; a handle may start with "_".
+ return /^[a-z0-9]/.test(key) ? `${key}-x` : `x${key}-x`;
+}
+
+export function xLeadChannelFields(lead: { handle: string; name?: string }): Record<string, string> {
+ const handle = lead.handle.replace(/^@/, "");
+ return {
+ name: `${lead.name?.trim() || handle} (X)`,
+ handling: "transcribe",
+ url: `https://x.com/${handle}`,
+ platform: "twitter",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ socialHandle: handle,
+ };
+}
diff --git a/common/lib/xSearch/walk.test.ts b/common/lib/xSearch/walk.test.ts
@@ -0,0 +1,81 @@
+// An X search channel's walk, planned: the first walk from until/tomorrow down
+// to since, a resume before anything else, the new days with a day of overlap,
+// the earlier days when since moves back, and nothing when all is covered.
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/walk.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ coverAfterWalk,
+ describeXSearchWalk,
+ planXSearchWalk,
+ startXSearchWalk,
+ xSearchStateFor,
+} from "./walk";
+
+const NOW = new Date("2026-10-20T12:00:00Z");
+
+test("the first walk starts at tomorrow (or until) and its windows reach no lower than since", () => {
+ const state = xSearchStateFor({ query: "zephyr" }, undefined);
+ assert.deepEqual(state, { queryKey: "zephyr" });
+ assert.deepEqual(planXSearchWalk({ query: "zephyr" }, state, NOW), {
+ kind: "first",
+ walk: { top: "2026-10-21", since: "2026-07-21", until: "2026-10-21", emptyWindows: 0 },
+ });
+ assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2026-09-01", until: "2026-10-01", windowMonths: 1 }, state, NOW), {
+ kind: "first",
+ walk: { top: "2026-10-01", floor: "2026-09-01", since: "2026-09-01", until: "2026-10-01", emptyWindows: 0 },
+ });
+ assert.equal(planXSearchWalk({ query: "zephyr", since: "2026-11-01" }, state, NOW).kind, "none");
+});
+
+test("a walk in progress is resumed before anything else", () => {
+ const walk = { ...startXSearchWalk("2026-10-21", "2025-01-01", 3), maxId: "1899" };
+ const plan = planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, { queryKey: "zephyr", walk, coveredUntil: "2026-01-01" }, NOW);
+ assert.deepEqual(plan, { kind: "resume", walk });
+});
+
+test("after a finished walk: the new days with a day of overlap, then the earlier days, then nothing", () => {
+ const covered = { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: "2026-10-15" };
+ assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, covered, NOW), {
+ kind: "new",
+ walk: { top: "2026-10-21", floor: "2026-10-14", since: "2026-10-14", until: "2026-10-21", emptyWindows: 0 },
+ });
+ const upToDate = { ...covered, coveredUntil: "2026-10-21" };
+ const none = planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, upToDate, NOW);
+ assert.equal(none.kind, "none");
+ assert.match((none as { reason: string }).reason, /already searched 2025-01-01 – 2026-10-21/);
+ assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2024-06-01" }, upToDate, NOW), {
+ kind: "earlier",
+ walk: { top: "2025-01-02", floor: "2024-06-01", since: "2024-10-02", until: "2025-01-02", emptyWindows: 0 },
+ });
+ // A fixed until already covered: nothing new above it.
+ assert.equal(planXSearchWalk({ query: "zephyr", since: "2025-01-01", until: "2026-10-15" }, covered, NOW).kind, "none");
+});
+
+test("a new query starts afresh; the dates alone do not", () => {
+ const stored = { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: "2026-10-15" };
+ assert.equal(xSearchStateFor({ query: "zephyr" }, stored), stored);
+ assert.deepEqual(xSearchStateFor({ query: "zephyr OR zephyrs" }, stored), { queryKey: "zephyr OR zephyrs" });
+ assert.deepEqual(xSearchStateFor({ query: "zephyr", lang: "en" }, stored), { queryKey: "zephyr lang:en" });
+});
+
+test("coverage after a walk is the union of what was covered and what was walked", () => {
+ assert.deepEqual(coverAfterWalk({}, { top: "2026-10-21" }, "2025-01-01"), {
+ coveredSince: "2025-01-01",
+ coveredUntil: "2026-10-21",
+ });
+ assert.deepEqual(coverAfterWalk({ coveredSince: "2025-01-01", coveredUntil: "2026-10-15" }, { top: "2026-10-21" }, "2026-10-14"), {
+ coveredSince: "2025-01-01",
+ coveredUntil: "2026-10-21",
+ });
+ assert.deepEqual(coverAfterWalk({ coveredSince: "2025-01-01", coveredUntil: "2026-10-21" }, { top: "2025-01-02" }, "2024-06-01"), {
+ coveredSince: "2024-06-01",
+ coveredUntil: "2026-10-21",
+ });
+ assert.equal(describeXSearchWalk(undefined), "not searched yet");
+ assert.equal(
+ describeXSearchWalk({ queryKey: "z", coveredSince: "2025-01-01", coveredUntil: "2026-10-21", walk: { top: "2025-01-02", floor: "2024-06-01", since: "2024-10-02", until: "2025-01-02", emptyWindows: 0, maxId: "9" } }),
+ "searched 2025-01-01 – 2026-10-21; walking 2024-10-02 – 2025-01-02 (down to 2024-06-01), resuming inside the window",
+ );
+});
diff --git a/common/lib/xSearch/walk.ts b/common/lib/xSearch/walk.ts
@@ -0,0 +1,119 @@
+// An X search channel's walk, planned (pure: no I/O, so every step is testable
+// without a fetcher). A walk goes BACKWARDS in search windows from a `top` day
+// to a `floor`, newest first — the older walk's arithmetic
+// (social/olderBackfill.ts) over the channel's query. What finished walks have
+// searched end to end is [coveredSince, coveredUntil); each fetch walks ONE
+// stretch outside it, newest first:
+// - the first walk: from `until` (or tomorrow) down to `since` (or until a
+// year of windows in a row holds no match);
+// - the new days: from `until`/tomorrow down to the day before
+// `coveredUntil` (one day of overlap, deduped);
+// - the earlier days, when `since` was moved below `coveredSince`.
+// A walk cut short (budget, cancel, drain, a limit, an error) is resumed from
+// its saved position by the next fetch before anything else.
+
+import type { XSearchWalkState } from "../posts-server";
+import {
+ addUtcDays,
+ addUtcMonths,
+ OLDER_WINDOW_MONTHS,
+ utcDayOf,
+} from "../../social/olderBackfill";
+import { xSearchQueryKey, type XSearchConfig } from "./config";
+
+export type XSearchWalk = NonNullable<XSearchWalkState["walk"]>;
+
+export type XSearchWalkKind = "resume" | "first" | "new" | "earlier";
+
+export type XSearchWalkPlan =
+ | { kind: XSearchWalkKind; walk: XSearchWalk }
+ | { kind: "none"; reason: string };
+
+const later = (a: string, b: string | undefined): string => (b !== undefined && b > a ? b : a);
+
+// The first window of a walk from `top` down to `floor`.
+export function startXSearchWalk(top: string, floor: string | undefined, months: number): XSearchWalk {
+ return {
+ top,
+ ...(floor !== undefined ? { floor } : {}),
+ since: later(addUtcMonths(top, -months), floor),
+ until: top,
+ emptyWindows: 0,
+ };
+}
+
+// The state this config's walk continues from: the stored one when it belongs
+// to the same query, else a fresh one (a new query is a new search).
+export function xSearchStateFor(
+ config: Pick<XSearchConfig, "query" | "lang">,
+ stored: XSearchWalkState | undefined,
+): XSearchWalkState {
+ const queryKey = xSearchQueryKey(config);
+ return stored && stored.queryKey === queryKey ? stored : { queryKey };
+}
+
+// What the next fetch walks.
+export function planXSearchWalk(
+ config: XSearchConfig,
+ state: XSearchWalkState,
+ now: Date = new Date(),
+): XSearchWalkPlan {
+ const months = config.windowMonths ?? OLDER_WINDOW_MONTHS;
+ if (state.walk) return { kind: "resume", walk: state.walk };
+ const top = config.until ?? addUtcDays(utcDayOf(now), 1);
+ if (config.since !== undefined && config.since >= top) {
+ return { kind: "none", reason: `nothing to search: ${config.since} is not before ${top}` };
+ }
+ if (!state.coveredUntil) {
+ return { kind: "first", walk: startXSearchWalk(top, config.since, months) };
+ }
+ if (top > state.coveredUntil) {
+ // One day of overlap below what was covered: a post made on the day the
+ // last walk started is read again (and skipped) rather than missed.
+ const floor = later(addUtcDays(state.coveredUntil, -1), config.since);
+ return { kind: "new", walk: startXSearchWalk(top, floor, months) };
+ }
+ if (config.since !== undefined && state.coveredSince !== undefined && config.since < state.coveredSince) {
+ return {
+ kind: "earlier",
+ walk: startXSearchWalk(addUtcDays(state.coveredSince, 1), config.since, months),
+ };
+ }
+ return {
+ kind: "none",
+ reason:
+ `already searched ${state.coveredSince ?? "?"} – ${state.coveredUntil}` +
+ (config.until ? "" : "; the next fetch after today searches the new days"),
+ };
+}
+
+// The covered span once `walk` has been walked to its end, its last window
+// starting at `endSince`.
+export function coverAfterWalk(
+ state: Pick<XSearchWalkState, "coveredSince" | "coveredUntil">,
+ walk: Pick<XSearchWalk, "top">,
+ endSince: string,
+): { coveredSince: string; coveredUntil: string } {
+ return {
+ coveredSince:
+ state.coveredSince !== undefined && state.coveredSince < endSince ? state.coveredSince : endSince,
+ coveredUntil:
+ state.coveredUntil !== undefined && state.coveredUntil > walk.top ? state.coveredUntil : walk.top,
+ };
+}
+
+// One line for the channel page and the ops read.
+export function describeXSearchWalk(state: XSearchWalkState | undefined): string {
+ if (!state) return "not searched yet";
+ const parts: string[] = [];
+ if (state.coveredUntil) parts.push(`searched ${state.coveredSince ?? "?"} – ${state.coveredUntil}`);
+ if (state.walk) {
+ parts.push(
+ `walking ${state.walk.since} – ${state.walk.until}` +
+ (state.walk.floor ? ` (down to ${state.walk.floor})` : "") +
+ (state.walk.maxId ? ", resuming inside the window" : ""),
+ );
+ }
+ if (parts.length === 0) return "not searched yet";
+ return parts.join("; ");
+}
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -145,6 +145,35 @@ export type OlderPostFetchResult = {
drained?: boolean;
};
+// Input for an X SEARCH channel's walk (`SocialFetcher.fetchSearch`, release
+// 38): the older walk's windows, login, limit, signal, log and checkpoints,
+// with a query across accounts in place of an account's handle.
+export type SearchPostFetchInput = Pick<
+ OlderPostFetchInput,
+ | "channelSlug"
+ | "seenIds"
+ | "cookies"
+ | "cookieSource"
+ | "browserCookies"
+ | "limit"
+ | "signal"
+ | "drain"
+ | "onLog"
+ | "position"
+ | "floor"
+ | "windowPauseMs"
+ | "onCheckpoint"
+> & {
+ // The channel's query and language (lib/xSearch/config.ts); the walk adds
+ // each window's since:/until: and its max_id: resume point.
+ search: { query: string; lang?: string };
+ // Each window's span in months. Default: the older walk's.
+ months?: number;
+ // Windows in a row with no match before the walk ends. Default: none with
+ // a floor (every window down to it is searched), else the older walk's.
+ maxEmptyWindows?: number;
+};
+
export type SocialFetcherProbe = {
ok: boolean;
// Display name for the account, used to autofill the channel form.
@@ -287,6 +316,10 @@ export type SocialFetcher = {
// reach (X: search windows). A fetcher without it has no such backfill, and
// the channel page offers no "Fetch older posts" for it.
fetchOlder?(input: OlderPostFetchInput): Promise<OlderPostFetchResult>;
+ // Optional: walk a SEARCH across accounts in windows (an X search channel,
+ // release 38). A fetcher without it cannot hold such a channel, and its
+ // fetch refuses by name.
+ fetchSearch?(input: SearchPostFetchInput): Promise<OlderPostFetchResult>;
// Optional: capture specific archived posts — a screenshot and the attached
// media — into `posts-media/<id>/` (X: the logged-in profile shoots the
// post, gallery-dl downloads its media). A fetcher without it cannot, and
diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts
@@ -34,7 +34,13 @@ import { cookieArgs } from "../lib/cookiePolicy";
import type { Post } from "../lib/posts";
import type { OlderBackfillPosition } from "../lib/posts-server";
import { normalizeXTweet, xCreatedAt, type XTweetRaw } from "./xNormalize";
-import { olderFloorDay, stepOlderWindow } from "./olderBackfill";
+import {
+ OLDER_MAX_EMPTY_WINDOWS,
+ OLDER_WINDOW_MONTHS,
+ olderFloorDay,
+ stepOlderWindow,
+} from "./olderBackfill";
+import { xSearchUrl as xSearchPageUrl, xSearchWindowQuery } from "../lib/xSearch/config";
import {
launchXProfile,
readXSessionStatus,
@@ -58,6 +64,7 @@ import {
type PostFetchResult,
type SocialFetcher,
type SocialFetcherProbe,
+ type SearchPostFetchInput,
type OnePostFetchInput,
type OnePostFetchResult,
} from "./fetchers";
@@ -432,7 +439,7 @@ export function xSearchQuery(
// into a space BEFORE it unquotes, so an encoded "+" survives as itself.
// `f=live` is X's own "Latest" tab, which is also what gallery-dl asks for.
export function xSearchUrl(query: string): string {
- return `https://x.com/search?q=${encodeURIComponent(query)}&f=live`;
+ return xSearchPageUrl(query);
}
export function buildGalleryDlSearchArgs(
@@ -441,6 +448,16 @@ export function buildGalleryDlSearchArgs(
position: Pick<OlderBackfillPosition, "since" | "until" | "maxId">;
},
): string[] {
+ return buildGalleryDlQueryArgs({ ...opts, query: xSearchQuery(opts.handle, opts.position) });
+}
+
+// The argv for ONE search window, whatever the query: an account's older walk
+// (`from:<handle>`, above) or an X search channel's own query
+// (lib/xSearch/config.ts, xSearchWindowQuery). The query already carries the
+// window's since:/until: and its max_id: resume point.
+export function buildGalleryDlQueryArgs(
+ opts: GalleryDlLoginAndCap & { query: string },
+): string[] {
const args = galleryDlCommonArgs(opts);
args.push(
// Newest first, paged by max_id — the order the resume point relies on.
@@ -449,7 +466,7 @@ export function buildGalleryDlSearchArgs(
"-o",
"extractor.twitter.search-pagination=max_id",
);
- args.push(xSearchUrl(xSearchQuery(opts.handle, opts.position)));
+ args.push(xSearchUrl(opts.query));
return args;
}
@@ -835,8 +852,6 @@ const SEARCH_NEEDS_LOGIN =
export async function fetchOlderViaSearch(
input: OlderPostFetchInput,
): Promise<OlderPostFetchResult> {
- const { channelSlug, seenIds, signal, onLog } = input;
- const bin = getPaths().galleryDlBin;
let handle: string;
try {
handle = xSearchHandle(input.handle);
@@ -848,6 +863,61 @@ export async function fetchOlderViaSearch(
error: (err as Error).message,
};
}
+ return walkSearchWindows(input, {
+ queryFor: (at) => xSearchQuery(handle, at),
+ accountHandle: handle,
+ opening: `Searching @${handle}'s posts backwards`,
+ doneLabel: "Older-posts backfill complete",
+ });
+}
+
+// AN X SEARCH CHANNEL'S WALK (release 38, controller/fetchXSearch.ts): the
+// same windows, pacing, budget, login and resume point as the older walk,
+// with the channel's own query (any author) in place of `from:<handle>`. The
+// floor is the channel's `since`; with one, every window down to it is
+// searched (an empty stretch is not the end of a query's history), and
+// without one the walk ends after a year of empty windows.
+export async function fetchSearchViaWindows(
+ input: SearchPostFetchInput,
+): Promise<OlderPostFetchResult> {
+ const months = input.months ?? OLDER_WINDOW_MONTHS;
+ try {
+ xSearchWindowQuery(input.search, input.position);
+ } catch (err) {
+ return { posts: [], complete: false, position: input.position, error: (err as Error).message };
+ }
+ return walkSearchWindows(
+ { ...input, handle: "", accountUrl: "" },
+ {
+ queryFor: (at) => xSearchWindowQuery(input.search, at),
+ opening: `Searching X for ${JSON.stringify(input.search.query)} backwards`,
+ doneLabel: "Search walk complete",
+ months,
+ maxEmptyWindows:
+ input.maxEmptyWindows ??
+ (input.floor !== undefined ? Number.POSITIVE_INFINITY : OLDER_MAX_EMPTY_WINDOWS),
+ },
+ );
+}
+
+type SearchWalkSpec = {
+ // The query for one window (its since:/until:/max_id: included).
+ queryFor: (position: OlderBackfillPosition) => string;
+ // The account whose `user` record carries its creation date (an older
+ // walk); a search across accounts has none.
+ accountHandle?: string;
+ opening: string;
+ doneLabel: string;
+ months?: number;
+ maxEmptyWindows?: number;
+};
+
+async function walkSearchWindows(
+ input: OlderPostFetchInput,
+ spec: SearchWalkSpec,
+): Promise<OlderPostFetchResult> {
+ const { channelSlug, seenIds, signal, onLog } = input;
+ const bin = getPaths().galleryDlBin;
const { cookies, cookieFile } = await galleryDlLoginFor(input);
if (!cookies && !cookieFile) {
onLog?.(`[auth] ${SEARCH_NEEDS_LOGIN}`);
@@ -911,7 +981,7 @@ export async function fetchOlderViaSearch(
};
onLog?.(
- `Searching @${handle}'s posts backwards, ${position.since} – ${position.until}` +
+ `${spec.opening}, ${position.since} – ${position.until}` +
(position.maxId ? " from the saved resume point" : "") +
` (up to ${Math.round(BACKFILL_BUDGET_MS / 60_000)} min this run; progress is saved as it goes)`,
);
@@ -943,12 +1013,11 @@ export async function fetchOlderViaSearch(
channelSlug,
seenIds,
stopAtKnown: false,
- accountHandle: handle,
+ accountHandle: spec.accountHandle,
onLog,
});
- const args = buildGalleryDlSearchArgs({
- handle,
- position: windowStart,
+ const args = buildGalleryDlQueryArgs({
+ query: spec.queryFor(windowStart),
cookies,
cookieFile,
limit: remainingLimit,
@@ -1053,9 +1122,11 @@ export async function fetchOlderViaSearch(
hadPosts: stream.distinct > 0 || Boolean(windowStart.maxId),
floor: olderFloorDay(input.floor, accountCreatedAt),
nothingFound: nothingArchived && read === 0,
+ ...(spec.months !== undefined ? { months: spec.months } : {}),
+ ...(spec.maxEmptyWindows !== undefined ? { maxEmptyWindows: spec.maxEmptyWindows } : {}),
});
if (step.complete) {
- onLog?.(`Older-posts backfill complete: ${step.reason}.`);
+ onLog?.(`${spec.doneLabel}: ${step.reason}.`);
return {
posts: carried,
complete: true,
@@ -1347,6 +1418,8 @@ export const xGalleryDlFetcher: SocialFetcher = {
fetchOlder: fetchOlderViaSearch,
+ fetchSearch: fetchSearchViaWindows,
+
captureByIds: captureXPostsByIds,
};