commit f73bd4f827a70f565d8bc81dd9c5cd6d68a9e286
parent 8c8874945692adc946bd6d9b778f17bbec6baa98
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 19:00:33 -0500
x-trending S1: the page reader, the read job's controller, and the privacy layers
social/xTrendingRead.ts opens x.com/i/trending/<id> in the connected X profile's
browser (headless; "headed" through launchHeadedContext), keeps every GraphQL JSON
answer the page itself fetched in responses.jsonl with a screenshot, scrolls to the
bottom with the X request gap between, and stops at the caps, after two scrolls with
nothing new, and at once on a 429, a 401 or X's login page. No request is built and
no header is read.
controller/readXTrending.ts is the job's body: the posts are parsed from the saved
file and written with writePosts, the read recorded against a topic; `probe` writes
no post; a capture with no post the parser knows ends "read saved, nothing
recognised" (no failure, no alert); `reparse` parses a saved capture again offline.
A login wall raises the X alert; a 429 does not.
Kinds read-x-trending (network, X's queue, started by a person, never replayed) and
reparse-x-trending (offline). A library is refused by writeSite, skipped by
buildIndex, refused by fetch-posts and left out of the X run. bin/xTrendingPrivacy
pins the three layers over a real index build and compose. The fake X profile
browser plays an invented trending page back.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
14 files changed, 1772 insertions(+), 13 deletions(-)
diff --git a/common/bin/xTrendingPrivacy.test.ts b/common/bin/xTrendingPrivacy.test.ts
@@ -0,0 +1,222 @@
+// AN X TRENDING LIBRARY IS ON NO SITE AND IN NO BUILD (lane x-trending, hard
+// rule 1). Three layers, each pinned here over a temp corpus with a marker in
+// every private file:
+//
+// 1. the site writer refuses a library as a member or a cited channel
+// (lib/site.ts writeSite — the one writer every site edit goes through);
+// 2. the index build skips it: no export index file and no LMDB record
+// carries its posts — EVEN WHEN a site.json written by hand names it
+// (the case layer 1 cannot catch), and even on a PRIVATE site, the most
+// permissive build there is;
+// 3. the site compose then has nothing of it to copy: the public dir,
+// site.json, corpus.json and llms.txt never name it.
+// A positive control (an ordinary X account channel's post, on the same
+// private site) proves each consumer did read posts. The MCP's corpus tools
+// over this kind of composed dir: mcp/src/xTrendingPrivacy.test.ts.
+//
+// Run with: node_modules/.bin/tsx --test common/bin/xTrendingPrivacy.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-privacy-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+});
+delete process.env.ARCHILYZER_INDEX_ALLOW_HELD;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { main: composeSite } = await import("./compose-site");
+const { getSite, writeSite } = await import("../lib/site");
+const { writePosts } = await import("../lib/posts-server");
+const { recordXTrendingRead, trendingReadDir, listXTrending } = await import("../lib/xTrending/store");
+const { X_TRENDING_NOT_ON_A_SITE } = await import("../lib/xTrending/config");
+const { open } = await import("lmdb");
+
+const paths = getPaths();
+const LIB = "trending-lib";
+const PUBLIC_X = "kettle-org-x";
+const PUBLIC_POST = "an ordinary archived post about kettles";
+const POST_MARK = "trendpostmarkerq7x";
+const HANDLE_MARK = "trendhandlemarkerz4k";
+const TOPIC_MARK = "trendtopicmarkerw2p";
+const RAW_MARK = "trendrawmarkerj9m";
+const MARKS = [POST_MARK, HANDLE_MARK, TOPIC_MARK, RAW_MARK];
+const READ = "tr-01JA0000000000000000000000";
+const quiet = () => {};
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+
+const post = (channelSlug: string, id: string, author: string, text: string) => ({
+ id,
+ slug: `${channelSlug}/${id}`,
+ channelSlug,
+ author,
+ createdAt: "2026-11-16T12:00:00.000Z",
+ uploadDate: "20261116",
+ text,
+ url: `https://x.com/${author}/status/${id}`,
+ platform: "twitter" as const,
+ isReply: false,
+ isRepost: false,
+ links: [],
+});
+
+writeJson(paths.settingsFile, {});
+writeJson(path.join(paths.channelsDir, PUBLIC_X, "config.json"), {
+ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Kettle Org (X)",
+ url: "https://x.com/kettle_org", socialHandle: "kettle_org",
+});
+await writePosts(path.join(paths.channelsDir, PUBLIC_X), [post(PUBLIC_X, "1900000000000005001", "kettle_org", PUBLIC_POST)]);
+
+const libRoot = path.join(paths.channelsDir, LIB);
+writeJson(path.join(libRoot, "config.json"), {
+ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {},
+});
+await writePosts(libRoot, [post(LIB, "1900000000000006001", HANDLE_MARK, `a trending post ${POST_MARK}`)]);
+await recordXTrendingRead(libRoot, {
+ readId: READ,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" },
+ topic: `Topic ${TOPIC_MARK}`,
+ postIds: ["1900000000000006001"],
+ added: 1,
+});
+mkdirSync(trendingReadDir(libRoot, READ), { recursive: true });
+writeFileSync(path.join(trendingReadDir(libRoot, READ), "responses.jsonl"), `${JSON.stringify({ n: 1, op: "Op", status: 200, body: { t: RAW_MARK } })}\n`);
+
+const site = (channels: string[]) => ({
+ siteId: "priv", siteTitle: "priv", siteDescription: "fixture", headerTitle: "priv", homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: channels.map((slug) => ({ slug, groupId: "default" })),
+ siteUrl: "https://priv.example.test", archives: false, audience: "private",
+});
+// Written BY HAND, naming the library: what the site writer would refuse.
+writeJson(path.join(paths.sitesDir, "priv", "site.json"), site([PUBLIC_X, LIB]));
+
+function filesUnder(dir: string): { rel: string; text: string }[] {
+ const out: { rel: string; text: string }[] = [];
+ const walk = (d: string) => {
+ for (const e of readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.isFile() || (e.isSymbolicLink() && statSync(p).isFile())) out.push({ rel: path.relative(dir, p), text: readFileSync(p).toString("latin1") });
+ }
+ };
+ walk(dir);
+ return out;
+}
+
+// No file is named for the library, and none holds a marker or its slug.
+function assertNoLeak(files: { rel: string; text: string }[], where: string, opts: { slugInText?: boolean } = {}) {
+ for (const f of files) {
+ assert.ok(!f.rel.split(path.sep).includes(LIB), `${where}: a file under ${f.rel}`);
+ for (const mark of MARKS) assert.ok(!f.text.includes(mark), `${where}: ${f.rel} holds ${mark}`);
+ if (opts.slugInText !== false) assert.ok(!f.text.includes(LIB), `${where}: ${f.rel} names ${LIB}`);
+ }
+}
+
+const hasPublicPost = (files: { text: string }[]) => files.some((f) => f.text.includes(PUBLIC_POST));
+
+test("layer 1: the site writer refuses a library as a member and as a cited channel", async () => {
+ const stored = getSite("priv", paths);
+ await assert.rejects(writeSite({ ...stored, channels: [{ slug: LIB, groupId: "default" }] }, paths), {
+ message: X_TRENDING_NOT_ON_A_SITE(LIB),
+ });
+ await assert.rejects(
+ writeSite({ ...stored, channels: [{ slug: PUBLIC_X, groupId: "default" }], citedChannels: [{ slug: LIB }] } as never, paths),
+ { message: `${LIB} is an X trending library: it is private, and never put on a site.` },
+ );
+ // The same site without it is written.
+ await writeSite({ ...stored, channels: [{ slug: PUBLIC_X, groupId: "default" }] }, paths);
+ // And the hand-written one is put back for the layers below.
+ writeJson(path.join(paths.sitesDir, "priv", "site.json"), site([PUBLIC_X, LIB]));
+});
+
+test("layer 2: the index build skips the library — no export index file, no LMDB record — though a site.json names it", async () => {
+ const log: string[] = [];
+ await buildIndex({ paths, onLog: (l: string) => log.push(l) });
+ assert.ok(log.some((l) => l.includes(`Skipping channel ${LIB}: an X trending library`)), "the build says it skipped it");
+ const files = filesUnder(paths.exportIndexDir);
+ assert.ok(hasPublicPost(files), "control: the account channel's post is in the index");
+ // The site's own manifest may list the slug the hand-written site.json
+ // names; no file is the library's and none holds its words.
+ assertNoLeak(files, "export index", { slugInText: false });
+ const root = open({ path: paths.lmdbPath, maxDbs: 18, compression: true });
+ try {
+ let seenPublic = false;
+ for (const name of ["sums", "cues", "subs", "alts", "mtimes", "byChannel", "pageHashes", "subPageHashes", "channelStats", "posts", "postPageHashes", "channelPostsStats", "digests", "digestPageHashes", "channelDigestStats", "videoState", "meta"]) {
+ const db = root.openDB({ name, encoding: "msgpack" });
+ for (const { key, value } of db.getRange()) {
+ const text = JSON.stringify([key, value]);
+ if (text.includes(PUBLIC_POST)) seenPublic = true;
+ for (const mark of MARKS) assert.ok(!text.includes(mark), `LMDB ${name}: a record holds ${mark}`);
+ // `meta` keeps each site's membership fingerprint, which repeats the
+ // slug the hand-written site.json names; no other record may.
+ if (name !== "meta") assert.ok(!text.includes(LIB), `LMDB ${name}: a record names ${LIB}`);
+ }
+ }
+ assert.ok(seenPublic, "control: the account channel's post is in LMDB");
+ } finally {
+ await root.close();
+ }
+});
+
+test("layer 3: the composed site — pages, site.json, corpus.json, llms.txt — carries nothing of the library", async () => {
+ await buildIndex({ paths, onLog: quiet });
+ const log = console.log;
+ const warn = console.warn;
+ console.log = quiet;
+ console.warn = quiet;
+ try {
+ await composeSite({ siteId: "priv", paths });
+ } finally {
+ console.log = log;
+ console.warn = warn;
+ }
+ const files = filesUnder(paths.exportPublicDir);
+ assert.ok(hasPublicPost(files), "control: the account channel's post is composed");
+ assertNoLeak(files, "public dir");
+ for (const name of ["corpus.json", "llms.txt", "site.json"]) {
+ const f = files.find((x) => x.rel === name);
+ assert.ok(f, `${name} was composed`);
+ assert.ok(f!.text.includes(PUBLIC_X), `control: ${name} names the account channel`);
+ }
+});
+
+test("the library's own listing needs no index: it reads its files", async () => {
+ const listing = await listXTrending(libRoot);
+ assert.equal(listing.total, 1);
+ assert.equal(listing.posts[0].author, HANDLE_MARK);
+ assert.ok(listing.posts[0].text.includes(POST_MARK));
+ // And never the raw capture.
+ assert.ok(!JSON.stringify(listing).includes(RAW_MARK));
+});
+
+test("the search itself catches a leak", () => {
+ assert.throws(() => assertNoLeak([{ rel: path.join("posts", LIB, "page-0001.json"), text: "" }], "x"));
+ for (const mark of MARKS) assert.throws(() => assertNoLeak([{ rel: "page-0001.json", text: `{"q":"${mark}"}` }], "x"));
+ assert.throws(() => assertNoLeak([{ rel: "corpus.json", text: `{"slug":"${LIB}"}` }], "x"));
+ assert.doesNotThrow(() => assertNoLeak([{ rel: "page-0001.json", text: PUBLIC_POST }], "x"));
+});
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -151,6 +151,7 @@ import {
postsAvailabilityPath,
} from "../lib/posts-server";
import { isRemoteOnlyChannel, isSocialChannel } from "../lib/channelConfig";
+import { isXTrendingChannel } from "../lib/xTrending/config";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import {
DIGESTS_MANIFEST_VERSION,
@@ -454,6 +455,13 @@ async function scanSource(
log(`Skipping channel ${ch.name}: remote-only`);
continue;
}
+ // An X trending library (lane x-trending) is PRIVATE: in no index build,
+ // so no staging index, posts page, site, hub or corpus.json carries its
+ // posts. Its own listing reads its files (lib/xTrending/store.ts).
+ if (isXTrendingChannel(cfg)) {
+ log(`Skipping channel ${ch.name}: an X trending library (private, never indexed)`);
+ continue;
+ }
channels.set(ch.name, cfg);
// A social channel carries posts, not videos: it has no data/ dir to walk,
// and routing it through the video scan would only ever produce noise. Its
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -16,6 +16,7 @@ import type { Post } from "../lib/posts";
import { isSocialChannel } from "../lib/channelConfig";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { isXSearchChannel } from "../lib/xSearch/config";
+import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "../lib/xTrending/config";
import { fetchXSearchPosts, X_SEARCH_OLDER_REFUSAL } from "./fetchXSearch";
import {
alwaysCookies,
@@ -278,6 +279,12 @@ export async function fetchPosts(
return { ok: false, written: 0, skipped: 0, complete: false, error: WAYBACK_PAGES_NOT_FETCHED };
}
+ // An X trending library has no timeline to fetch: its pages are read one at
+ // a time (controller/readXTrending.ts).
+ if (isXTrendingChannel(config)) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: X_TRENDING_NOT_FETCHED(slug) };
+ }
+
const accountUrl = config.url ?? "";
const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl);
if (!fetcher) {
diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts
@@ -0,0 +1,281 @@
+// read-x-trending end to end over a page that plays invented answers back: no
+// browser, no request, no wait, a temp corpus.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/readXTrending.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readAllPosts } from "../lib/posts-server";
+import { listXTrending, readXTrendingReadRecord } from "../lib/xTrending/store";
+import { fakeTrendingPage, type FakeTrendingPage } from "../social/fakeXProfileBrowser";
+import {
+ FIXTURE_TIMELINE_OP,
+ FIXTURE_TREND_ID,
+ FIXTURE_TREND_URL,
+ fixtureTimelineBody,
+ fixtureTrendingResponses,
+} from "../social/__fixtures__/xTrendingCapture";
+import {
+ NO_X_PROFILE_FOR_TRENDING,
+ planReadXTrending,
+ reparseXTrendingRead,
+ runXTrendingRead,
+ type ReadXTrendingAsk,
+ type ReadXTrendingResult,
+} from "./readXTrending";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "read-x-trending-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+const READ_1 = "tr-01JA0000000000000000000000";
+const READ_2 = "tr-01JB0000000000000000000000";
+
+function corpus(name: string): Paths {
+ const transcriptsDir = path.join(TMP, name);
+ const channelsDir = path.join(transcriptsDir, "channels");
+ const lib = (slug: string, config: Record<string, unknown>) => {
+ mkdirSync(path.join(channelsDir, slug), { recursive: true });
+ writeFileSync(path.join(channelsDir, slug, "config.json"), JSON.stringify(config));
+ };
+ lib("trending", { handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} });
+ lib("account-x", { handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/example", socialHandle: "example" });
+ return { transcriptsDir, channelsDir } as unknown as Paths;
+}
+
+const withProfile = { hasProfile: async () => true };
+
+async function run(
+ paths: Paths,
+ trending: FakeTrendingPage,
+ ask: Partial<ReadXTrendingAsk> = {},
+ over: { readId?: string; at?: string; profileBusy?: () => string | null } = {},
+): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[] }> {
+ const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, ...ask }, withProfile);
+ assert.ok(planned.ok, planned.ok ? "" : planned.error);
+ assert.equal(planned.plan.mode, "read");
+ const notes: Array<Record<string, unknown>> = [];
+ const log: string[] = [];
+ const page = fakeTrendingPage(() => ({ trending }));
+ const result = await runXTrendingRead({
+ paths,
+ plan: planned.plan as never,
+ onLog: (l) => log.push(l),
+ deps: {
+ openPage: async () => ({ page, close: async () => {} }),
+ pauseMs: () => 0,
+ pause: async () => {},
+ now: () => Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"),
+ readId: over.readId ?? READ_1,
+ ...(over.profileBusy ? { profileBusy: over.profileBusy } : {}),
+ noteOutcome: async (_p, outcome) => {
+ notes.push(outcome as Record<string, unknown>);
+ return null;
+ },
+ },
+ });
+ return { result, notes, log };
+}
+
+const root = (paths: Paths) => path.join(paths.channelsDir, "trending");
+
+test("every refusal before a job is a sentence", async () => {
+ const paths = corpus("refusals");
+ const plan = (ask: Partial<ReadXTrendingAsk>, deps = withProfile) =>
+ planReadXTrending(paths, { slug: "trending", ...ask }, deps);
+ const error = async (p: ReturnType<typeof plan>) => {
+ const r = await p;
+ assert.equal(r.ok, false);
+ return r.ok ? "" : r.error;
+ };
+ assert.equal(await error(planReadXTrending(paths, { slug: "nope", url: FIXTURE_TREND_URL }, withProfile)), "No such channel: nope");
+ assert.match(await error(planReadXTrending(paths, { slug: "account-x", url: FIXTURE_TREND_URL }, withProfile)), /account-x is not an X trending library/);
+ assert.match(await error(plan({})), /Give "url" .* or "reparse"/);
+ assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /one of them/);
+ assert.match(await error(plan({ url: "https://x.com/example/status/1" })), /not a trending page URL/);
+ assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 21 })), /"scrolls" is a whole number, 1–20/);
+ assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 201 })), /"posts" is a whole number, 1–200/);
+ assert.match(await error(plan({ url: FIXTURE_TREND_URL, topic: " " })), /topic/);
+ assert.equal(await error(plan({ url: FIXTURE_TREND_URL }, { hasProfile: async () => false })), NO_X_PROFILE_FOR_TRENDING);
+ assert.match(await error(plan({ reparse: "nope" })), /not a trending read id/);
+ assert.match(await error(plan({ reparse: READ_1 })), /holds no saved read/);
+ assert.match(await error(plan({ reparse: READ_1, probe: true })), /apply to a read of a page/);
+ // Nothing was made by a refusal.
+ assert.equal(existsSync(path.join(root(paths), "trending")), false);
+});
+
+test("a read writes the page's posts, records the read against a topic, and says so", async () => {
+ const paths = corpus("read");
+ const { result, notes } = await run(paths, fixtureTrendingResponses(), { topic: "Kettle Festival" });
+ assert.equal(result.ok, true);
+ assert.equal(result.outcome, "read");
+ assert.equal(result.mode, "read");
+ assert.equal(result.trendId, FIXTURE_TREND_ID);
+ assert.equal(result.read, READ_1);
+ assert.deepEqual(result.posts, { onPage: 4, added: 4 });
+ assert.deepEqual(result.topic, { id: "kettle-festival", title: "Kettle Festival", created: true });
+ assert.equal(
+ result.sentence,
+ `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival).`,
+ );
+ // A clean request was noted; no alert.
+ assert.deepEqual(notes, [{ url: FIXTURE_TREND_URL, channel: "trending" }]);
+ const posts = await readAllPosts(root(paths));
+ assert.deepEqual(posts.map((p) => p.id).sort(), [
+ "1900000000000001001",
+ "1900000000000001002",
+ "1900000000000001004",
+ "1900000000000001005",
+ ]);
+ assert.ok(posts.every((p) => p.channelSlug === "trending" && p.platform === "twitter"));
+ const listing = await listXTrending(root(paths));
+ assert.equal(listing.topics[0].posts, 4);
+ assert.deepEqual(listing.posts.map((p) => [p.id, p.author, p.media.kinds.join("+")]), [
+ ["1900000000000001001", "teapot_news", "image"],
+ ["1900000000000001002", "saucer_fan", ""],
+ ["1900000000000001004", "spout_clips", "video"],
+ ["1900000000000001005", "lid_watch", "gif"],
+ ]);
+ // The read's record: operation names and sizes, never a body.
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.equal(record?.outcome, "read");
+ assert.equal(record?.stop, "idle");
+ assert.deepEqual(record?.operations.map((o) => o.op), ["ExampleTrendPage", FIXTURE_TIMELINE_OP, "HomeTimeline"]);
+ const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8");
+ assert.ok(!recordText.includes("kettle festival opens"), "read.json carries no post text");
+ assert.ok(!recordText.includes("teapot_news"), "read.json carries no handle");
+ assert.deepEqual(readdirSync(path.join(root(paths), "trending", "reads", READ_1)).sort(), ["page.png", "read.json", "responses.jsonl"]);
+});
+
+test("a re-read adds the new posts, keeps the old ones, and appends the read with its time", async () => {
+ const paths = corpus("reread");
+ const first = fixtureTrendingResponses();
+ await run(paths, { load: first.load, scrolls: [] });
+ const again = await run(
+ paths,
+ { load: [first.scrolls[0][0]], scrolls: [] },
+ {},
+ { readId: READ_2, at: "2026-11-17T12:00:00.000Z" },
+ );
+ assert.deepEqual(again.result.posts, { onPage: 2, added: 1 });
+ assert.equal(again.result.topic?.created, false);
+ const listing = await listXTrending(root(paths));
+ assert.equal(listing.total, 4);
+ assert.deepEqual(listing.topics[0].sources, [
+ { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" },
+ ]);
+ const twice = listing.posts.find((p) => p.id === "1900000000000001004");
+ assert.deepEqual(twice?.reads.map((r) => r.read), [READ_1, READ_2]);
+ assert.deepEqual(listing.reads, [READ_2, READ_1]);
+});
+
+test("a probe saves the capture and its summary, writes no post, and a reparse writes them without a read", async () => {
+ const paths = corpus("probe");
+ const { result, notes } = await run(paths, fixtureTrendingResponses(), { probe: true });
+ assert.equal(result.ok, true);
+ assert.equal(result.outcome, "probe");
+ assert.equal(result.mode, "probe");
+ assert.deepEqual(result.posts, { onPage: 4, added: 0 });
+ assert.match(result.sentence, /^Probe saved \(trending\/reads\/tr-01JA0000000000000000000000\/\): 4 answers — /);
+ assert.match(result.sentence, /The parser finds 4 posts in it\. No post was written/);
+ assert.deepEqual(notes, []);
+ assert.equal((await readAllPosts(root(paths))).length, 0);
+ assert.deepEqual((await listXTrending(root(paths))).topics, []);
+ assert.equal(existsSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl")), true);
+
+ const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, topic: "Kettles" });
+ assert.ok(planned.ok && planned.plan.mode === "reparse");
+ const reparsed = await reparseXTrendingRead({ plan: planned.plan as never, now: () => Date.parse("2026-11-18T09:00:00.000Z") });
+ assert.equal(reparsed.ok, true);
+ assert.equal(reparsed.mode, "reparse");
+ assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 });
+ assert.match(reparsed.sentence, /X was asked nothing\.$/);
+ assert.equal((await readAllPosts(root(paths))).length, 4);
+ const listing = await listXTrending(root(paths));
+ // The read keeps the time it was made, not the time it was parsed.
+ assert.equal(listing.topics[0].sources[0].lastReadAt, "2026-11-17T10:00:00.000Z");
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.equal(record?.outcome, "read");
+ assert.equal(record?.reparsedAt, "2026-11-18T09:00:00.000Z");
+ // A second reparse adds nothing.
+ const twice = await reparseXTrendingRead({ plan: planned.plan as never });
+ assert.deepEqual(twice.posts, { onPage: 4, added: 0 });
+});
+
+test("a first real read whose answers the parser does not know ends \"read saved, nothing recognised\": no failure, no alert", async () => {
+ const paths = corpus("unknown");
+ const { result, notes } = await run(paths, {
+ load: [{ url: "https://x.com/i/api/graphql/q1/UnknownTrendShape", status: 200, body: { data: { story: { headline: "invented" } } } }],
+ scrolls: [[], []],
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.outcome, "nothing-recognised");
+ assert.equal(result.error, undefined);
+ assert.match(result.sentence, /^Read saved, nothing recognised: 1 answer \(UnknownTrendShape ×1 \(\d+ bytes\)\) held no post the parser knows\./);
+ assert.match(result.sentence, /The capture is kept \(trending\/reads\//);
+ assert.deepEqual(notes, []);
+ assert.equal(existsSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl")), true);
+ assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "nothing-recognised");
+});
+
+test("a login wall fails with its sentence, writes no post and raises the X alert", async () => {
+ const paths = corpus("walled");
+ const { result, notes } = await run(paths, {
+ href: "https://x.com/i/flow/login",
+ load: [{ url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 200, body: fixtureTimelineBody([{ id: "1900000000000009001", handle: "login_page_promo", text: "Shown on the login page." }]) }],
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "login-wall");
+ assert.match(result.sentence, /^X asked to log in instead of showing the trending page/);
+ assert.match(result.sentence, /No post was written; the capture is kept/);
+ assert.equal(result.error, result.sentence);
+ assert.equal(notes.length, 1);
+ assert.equal(notes[0].kind, "auth-failure");
+ assert.ok(typeof notes[0].challengeLine === "string");
+ assert.equal((await readAllPosts(root(paths))).length, 0);
+});
+
+test("a 429 fails with its sentence, keeps what was read, and raises no alert", async () => {
+ const paths = corpus("limited");
+ const f = fixtureTrendingResponses();
+ const { result, notes } = await run(paths, {
+ load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }],
+ scrolls: f.scrolls,
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "rate-limit");
+ assert.equal(result.scrolls, 0);
+ assert.match(result.sentence, /^X answered 429 \(rate limit\)/);
+ assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./);
+ assert.match(result.sentence, /nothing retries by itself/);
+ assert.deepEqual(notes, []);
+ assert.equal((await readAllPosts(root(paths))).length, 3);
+});
+
+test("a page X no longer has, and a page that did not load, each fail with a sentence", async () => {
+ const paths = corpus("gone");
+ const gone = await run(paths, {
+ load: [{ url: "https://x.com/i/api/graphql/q/ExampleTrendPage", status: 404, body: { errors: [{ message: "invented" }] } }],
+ scrolls: [[], []],
+ });
+ assert.equal(gone.result.ok, false);
+ assert.equal(gone.result.outcome, "gone");
+ assert.match(gone.result.sentence, /^X no longer has this trending page/);
+ assert.deepEqual(gone.notes, []);
+ const broken = await run(paths, { gotoError: "net::ERR_TIMED_OUT\nmore", load: [] }, {}, { readId: READ_2 });
+ assert.equal(broken.result.ok, false);
+ assert.equal(broken.result.outcome, "error");
+ assert.match(broken.result.sentence, /^The trending page could not be loaded: net::ERR_TIMED_OUT\./);
+ assert.deepEqual(broken.notes, []);
+});
+
+test("a Connect or Refresh in flight refuses the read at its start: no browser opens", async () => {
+ const paths = corpus("busy");
+ const { result } = await run(paths, fixtureTrendingResponses(), {}, { profileBusy: () => "X's connect is already running." });
+ assert.equal(result.ok, false);
+ assert.equal(result.sentence, "X's connect is already running.");
+ assert.equal(existsSync(path.join(root(paths), "trending")), false);
+});
diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts
@@ -0,0 +1,472 @@
+// READ ONE X TRENDING PAGE INTO A LIBRARY (lane x-trending, slice 1) — the
+// editor's `read-x-trending`, ONE job on X's queue (`platform:twitter`) per
+// page: the network guard's fresh-jar rule, X alert and X's job gap apply to
+// it as to every X job (jobs/networkGuard.ts), and it serialises with every
+// capture, fetch and X run.
+//
+// - the page is opened in the connected X profile's browser and what the
+// page itself fetched is saved raw (social/xTrendingRead.ts);
+// - the posts are then parsed FROM THE SAVED FILE (social/xTrendingParse.ts)
+// and written as the library's posts (lib/posts-server.ts writePosts:
+// month shards, deduped by id), and the read is recorded against a topic
+// (lib/xTrending/store.ts). A re-read adds posts and never drops one;
+// - nothing else is fetched: no media, no thread, no screenshot of a post.
+// Archiving a post is a separate step (slice 2).
+//
+// `probe` saves the capture and its summary and writes no post — the first
+// real read, from which the parser learns the page's shape. A normal read is
+// safe to be that first read too: a capture with no post the parser knows
+// ends "read saved, nothing recognised", capture kept, NOT a failure and no
+// X alert. `reparse` parses a saved capture again, offline (its own kind,
+// `reparse-x-trending`: no request, so no jar is asked of it).
+//
+// EVERY FAILURE IS ONE SENTENCE AND NOTHING RETRIES: a login wall (which
+// raises the X alert, stopping every X job), a 429 (pacing, never cookies:
+// no alert), a page X no longer has, a page that did not load. What was read
+// before the failure is kept.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { writePosts } from "../lib/posts-server";
+import { noteXServiceOutcome } from "../lib/serviceCookies-server";
+import {
+ isXTrendingChannel,
+ NOT_A_TRENDING_URL,
+ NOT_AN_X_TRENDING_LIBRARY,
+ parseXTrendingUrl,
+ xTrendingLimits,
+ type XTrendingLimits,
+ type XTrendingRef,
+} from "../lib/xTrending/config";
+import {
+ isXTrendingReadId,
+ readXTrendingReadRecord,
+ recordXTrendingRead,
+ topicTitleProblem,
+ TRENDING_DIRNAME,
+ TRENDING_READS_DIRNAME,
+ TRENDING_RESPONSES_FILENAME,
+ trendingReadDir,
+ writeXTrendingReadRecord,
+ type XTrendingReadOperation,
+ type XTrendingReadOutcome,
+ type XTrendingReadRecord,
+} from "../lib/xTrending/store";
+import { ulid } from "../jobs/ulid";
+import { readXSessionStatus } from "../social/xSessionBroker";
+import { xRequestPauseMs } from "../social/xGalleryDlFetcher";
+import type { ChromiumLike } from "../social/playwrightRuntime";
+import { parseTrendingCapture, readCaptureLines } from "../social/xTrendingParse";
+import {
+ openXTrendingPage,
+ readXTrendingPage,
+ type TrendingPageRead,
+ type TrendingPageSession,
+} from "../social/xTrendingRead";
+import { readChannelConfig } from "./channels";
+
+export const READ_X_TRENDING_KIND = "read-x-trending";
+export const REPARSE_X_TRENDING_KIND = "reparse-x-trending";
+// X's platform queue: one browser on the profile at a time, X's gap between jobs.
+export const X_TRENDING_QUEUE = "platform:twitter";
+export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending ";
+
+// The job kinds that open the connected X profile in a browser while they
+// run on X's queue: a Connect or a Refresh (which open the same profile) is
+// refused while one of them is running (editor/app/lib/cookieRefreshGuard.ts).
+export const X_PROFILE_BROWSER_JOB_KINDS: readonly string[] = [READ_X_TRENDING_KIND, "capture-posts"];
+
+export const NO_X_PROFILE_FOR_TRENDING =
+ "Reading a trending page needs the connected X profile (the browser that stays logged in): " +
+ "connect an X account on /cookies, then read it again.";
+
+export type ReadXTrendingAsk = {
+ slug: string;
+ // A trending page to read…
+ url?: string;
+ // …or a saved read's id, to parse its capture again (offline).
+ reparse?: string;
+ // The topic the posts go into: an existing topic's id or name, or a new
+ // one's name. Absent: the topic this page was read into before, else a new
+ // one named for the page.
+ topic?: string;
+ scrolls?: unknown;
+ posts?: unknown;
+ probe?: boolean;
+ headed?: boolean;
+};
+
+export type ReadXTrendingPlan =
+ | {
+ mode: "read";
+ slug: string;
+ channelRoot: string;
+ ref: XTrendingRef;
+ limits: XTrendingLimits;
+ topic?: string;
+ probe: boolean;
+ headed: boolean;
+ }
+ | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string };
+
+// Everything checked before a job exists: the plan, or the refusal's sentence.
+export async function planReadXTrending(
+ paths: Paths,
+ ask: ReadXTrendingAsk,
+ deps: { hasProfile?: () => Promise<boolean> } = {},
+): Promise<{ ok: true; plan: ReadXTrendingPlan } | { ok: false; error: string }> {
+ const fail = (error: string) => ({ ok: false as const, error });
+ const config = await readChannelConfig(paths, ask.slug);
+ if (!config) return fail(`No such channel: ${ask.slug}`);
+ if (!isXTrendingChannel(config)) return fail(NOT_AN_X_TRENDING_LIBRARY(ask.slug));
+ const channelRoot = path.join(paths.channelsDir, ask.slug);
+ const hasUrl = ask.url !== undefined && ask.url !== "";
+ const hasReparse = ask.reparse !== undefined && ask.reparse !== "";
+ if (hasUrl === hasReparse) {
+ return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`);
+ }
+ if (ask.topic !== undefined) {
+ const problem = topicTitleProblem(ask.topic);
+ if (problem) return fail(problem);
+ }
+ const topic = ask.topic?.trim();
+ if (hasReparse) {
+ if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined) {
+ return fail(`"probe", "headed", "scrolls" and "posts" apply to a read of a page, not to "reparse" (which asks X nothing).`);
+ }
+ if (!isXTrendingReadId(ask.reparse)) return fail(`"${String(ask.reparse)}" is not a trending read id (tr-…)`);
+ const record = await readXTrendingReadRecord(channelRoot, ask.reparse);
+ if (!record) return fail(`${ask.slug} holds no saved read ${ask.reparse} (pnpm ops get trending ${ask.slug} lists them).`);
+ return { ok: true, plan: { mode: "reparse", slug: ask.slug, channelRoot, record, ...(topic ? { topic } : {}) } };
+ }
+ const ref = parseXTrendingUrl(ask.url);
+ if (!ref) return fail(NOT_A_TRENDING_URL);
+ const limits = xTrendingLimits(config.xTrending, { scrolls: ask.scrolls, posts: ask.posts });
+ if (!limits.ok) return fail(limits.error);
+ const hasProfile = deps.hasProfile ?? (async () => (await readXSessionStatus(paths)).hasProfile);
+ if (!(await hasProfile())) return fail(NO_X_PROFILE_FOR_TRENDING);
+ return {
+ ok: true,
+ plan: {
+ mode: "read",
+ slug: ask.slug,
+ channelRoot,
+ ref,
+ limits: limits.limits,
+ ...(topic ? { topic } : {}),
+ probe: ask.probe === true,
+ headed: ask.headed === true,
+ },
+ };
+}
+
+export type ReadXTrendingResult = {
+ ok: boolean;
+ slug: string;
+ mode: "read" | "probe" | "reparse";
+ url: string;
+ trendId: string;
+ // The read's id: `channels/<slug>/trending/reads/<read>/`.
+ read: string;
+ outcome: XTrendingReadOutcome;
+ stop?: string;
+ scrolls?: number;
+ responses: number;
+ // Operation names and sizes — never a body.
+ operations: XTrendingReadOperation[];
+ posts: { onPage: number; added: number };
+ topic?: { id: string; title: string; created?: boolean };
+ // What happened, as one sentence (the refusal, when `ok` is false).
+ sentence: string;
+ error?: string;
+};
+
+function opsText(ops: ReadonlyArray<XTrendingReadOperation>): string {
+ if (ops.length === 0) return "no GraphQL answer";
+ return ops
+ .map((o) => `${o.op} ×${o.responses} (${o.bytes} bytes${o.tweets ? `, ${o.tweets} post${o.tweets === 1 ? "" : "s"}` : ""})`)
+ .join(", ");
+}
+
+const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
+
+// Where a read's capture is, as a caller reads it (relative to the channel).
+function captureAt(readId: string): string {
+ return `${TRENDING_DIRNAME}/${TRENDING_READS_DIRNAME}/${readId}/`;
+}
+
+type Ingested = {
+ operations: XTrendingReadOperation[];
+ responses: number;
+ onPage: number;
+ added: number;
+ topic?: { id: string; title: string; created: boolean };
+};
+
+// The saved capture → the library: its posts written, the read recorded.
+// `write: false` (a probe) parses and counts and writes nothing.
+async function ingestCapture(o: {
+ channelRoot: string;
+ slug: string;
+ readId: string;
+ at: string;
+ ref: XTrendingRef;
+ topic?: string;
+ write: boolean;
+}): Promise<Ingested> {
+ const file = path.join(trendingReadDir(o.channelRoot, o.readId), TRENDING_RESPONSES_FILENAME);
+ const lines = await readCaptureLines(file).catch(() => []);
+ const parsed = parseTrendingCapture(lines, o.slug);
+ const base = { operations: parsed.operations, responses: parsed.responses, onPage: parsed.posts.length };
+ if (!o.write || parsed.posts.length === 0) return { ...base, added: 0 };
+ const written = await writePosts(o.channelRoot, parsed.posts);
+ const recorded = await recordXTrendingRead(o.channelRoot, {
+ readId: o.readId,
+ at: o.at,
+ ref: o.ref,
+ ...(o.topic ? { topic: o.topic } : {}),
+ postIds: parsed.posts.map((p) => p.id),
+ added: written.written,
+ media: parsed.media,
+ });
+ return { ...base, added: written.written, topic: recorded.topic };
+}
+
+export type ReadXTrendingDeps = {
+ // The page (default: the connected profile, xTrendingRead.ts openXTrendingPage).
+ openPage?: () => Promise<TrendingPageSession>;
+ // The e2e suite's fake browser, handed to the default opener.
+ chromium?: ChromiumLike;
+ pauseMs?: () => number;
+ pause?: (ms: number, signal: AbortSignal) => Promise<void>;
+ now?: () => number;
+ readId?: string;
+ // Why the profile cannot be opened now (a Connect or Refresh in flight), or null.
+ profileBusy?: () => string | null;
+ noteOutcome?: typeof noteXServiceOutcome;
+};
+
+export async function runXTrendingRead(o: {
+ paths: Paths;
+ plan: Extract<ReadXTrendingPlan, { mode: "read" }>;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ deps?: ReadXTrendingDeps;
+}): Promise<ReadXTrendingResult> {
+ const { plan, paths } = o;
+ const deps = o.deps ?? {};
+ const log = o.onLog ?? (() => {});
+ const now = deps.now ?? Date.now;
+ const signal = o.signal ?? new AbortController().signal;
+ const note = deps.noteOutcome ?? noteXServiceOutcome;
+ const readId = deps.readId ?? `tr-${ulid(now())}`;
+ const base = {
+ slug: plan.slug,
+ mode: plan.probe ? ("probe" as const) : ("read" as const),
+ url: plan.ref.url,
+ trendId: plan.ref.trendId,
+ read: readId,
+ };
+ const none = { responses: 0, operations: [], posts: { onPage: 0, added: 0 } };
+
+ // A Connect or a Refresh holds the profile: asked again here, at the start.
+ const busy = deps.profileBusy?.() ?? null;
+ if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy };
+
+ const startedAt = new Date(now()).toISOString();
+ log(
+ `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` +
+ `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")})` +
+ (plan.probe ? " — a probe: the capture is saved, no post is written." : "."),
+ );
+ const dir = trendingReadDir(plan.channelRoot, readId);
+ const page: TrendingPageRead = await readXTrendingPage({
+ url: plan.ref.url,
+ dir,
+ openPage:
+ deps.openPage ??
+ (() =>
+ openXTrendingPage(paths, {
+ headed: plan.headed,
+ onLog: log,
+ ...(deps.chromium ? { chromium: deps.chromium } : {}),
+ })),
+ limits: plan.limits,
+ pauseMs: deps.pauseMs ?? (() => xRequestPauseMs()),
+ ...(deps.pause ? { pause: deps.pause } : {}),
+ signal,
+ onLog: log,
+ now,
+ });
+
+ // What was read is kept whatever stopped it — except behind a login wall,
+ // where the page shown was not the trending page.
+ const walled = page.stop === "login-wall";
+ const ingested = await ingestCapture({
+ channelRoot: plan.channelRoot,
+ slug: plan.slug,
+ readId,
+ at: startedAt,
+ ref: plan.ref,
+ ...(plan.topic ? { topic: plan.topic } : {}),
+ write: !plan.probe && !walled,
+ });
+ const kept = captureAt(readId);
+ const gone = ingested.onPage === 0 && (page.statuses["404"] ?? 0) > 0;
+ const readSoFar = ingested.added > 0 || ingested.onPage > 0
+ ? ` ${plural(ingested.onPage, "post")} read before it ${plan.probe ? "are in the capture" : `were kept (${ingested.added} new)`}.`
+ : "";
+
+ let outcome: XTrendingReadOutcome;
+ let sentence: string;
+ if (walled) {
+ outcome = "login-wall";
+ sentence =
+ "X asked to log in instead of showing the trending page: the connected profile's session has ended. " +
+ `Connect X account (or Refresh cookies) on /cookies, then read it again. No post was written; the capture is kept (${kept}).`;
+ await note(paths, {
+ challengeLine: "X showed its login page to a read of a trending page (read-x-trending)",
+ kind: "auth-failure",
+ url: plan.ref.url,
+ channel: plan.slug,
+ });
+ } else if (page.stop === "rate-limit") {
+ outcome = "rate-limit";
+ sentence =
+ "X answered 429 (rate limit) to the page's own request: the read stopped at once and asked nothing more." +
+ readSoFar +
+ ` Read it again later; nothing retries by itself. The capture is kept (${kept}).`;
+ } else if (page.stop === "error") {
+ outcome = "error";
+ sentence = `The trending page could not be loaded: ${page.error ?? "unknown error"}.` + readSoFar + ` The capture is kept (${kept}).`;
+ } else if (gone) {
+ outcome = "gone";
+ sentence = `X no longer has this trending page (its request was answered 404): trending pages expire. The capture is kept (${kept}).`;
+ } else if (plan.probe) {
+ outcome = "probe";
+ sentence =
+ `Probe saved (${kept}): ${plural(page.responses, "answer")} — ${opsText(ingested.operations)}. ` +
+ `The parser finds ${plural(ingested.onPage, "post")} in it. No post was written` +
+ (ingested.onPage > 0 ? `; read-x-trending {"reparse": "${readId}"} writes them without asking X again.` : ".");
+ } else if (ingested.onPage === 0) {
+ outcome = "nothing-recognised";
+ sentence =
+ `Read saved, nothing recognised: ${plural(page.responses, "answer")} (${opsText(ingested.operations)}) held no post the parser knows. ` +
+ `The capture is kept (${kept}) for the parser to be taught from; read-x-trending {"reparse": "${readId}"} parses it again without asking X.`;
+ } else {
+ outcome = "read";
+ sentence =
+ `Read ${plan.ref.url}: ${plural(ingested.onPage, "post")} on the page, ${ingested.added} new, ` +
+ `in topic "${ingested.topic?.title}" (${ingested.topic?.id})` +
+ (page.stop === "cancelled" ? "; the read was stopped early." : ".");
+ // A clean request: a raised X alert it would clear is cleared.
+ const cleared = await note(paths, { url: plan.ref.url, channel: plan.slug });
+ if (cleared) log(cleared);
+ }
+ const ok = outcome === "read" || outcome === "probe" || outcome === "nothing-recognised";
+ const record: XTrendingReadRecord = {
+ version: 1,
+ id: readId,
+ trendId: plan.ref.trendId,
+ url: plan.ref.url,
+ startedAt,
+ endedAt: new Date(now()).toISOString(),
+ probe: plan.probe,
+ headed: plan.headed,
+ limits: plan.limits,
+ scrolls: page.scrolls,
+ stop: page.stop,
+ outcome,
+ responses: page.responses,
+ saved: page.saved,
+ bytes: page.bytes,
+ statuses: page.statuses,
+ operations: ingested.operations,
+ posts: { onPage: ingested.onPage, added: ingested.added },
+ ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}),
+ shot: page.shot,
+ sentence,
+ };
+ await writeXTrendingReadRecord(plan.channelRoot, record);
+ log(sentence);
+ return {
+ ...base,
+ ok,
+ outcome,
+ stop: page.stop,
+ scrolls: page.scrolls,
+ responses: page.responses,
+ operations: ingested.operations,
+ posts: { onPage: ingested.onPage, added: ingested.added },
+ ...(ingested.topic ? { topic: ingested.topic } : {}),
+ sentence,
+ ...(ok ? {} : { error: sentence }),
+ };
+}
+
+// A saved capture parsed again, offline: its posts written (those the library
+// lacks), the read recorded against its topic. Nothing is asked of X.
+export async function reparseXTrendingRead(o: {
+ plan: Extract<ReadXTrendingPlan, { mode: "reparse" }>;
+ onLog?: (line: string) => void;
+ now?: () => number;
+}): Promise<ReadXTrendingResult> {
+ const { plan } = o;
+ const log = o.onLog ?? (() => {});
+ const record = plan.record;
+ const ref: XTrendingRef = { trendId: record.trendId, url: record.url };
+ const walled = record.outcome === "login-wall";
+ const ingested = await ingestCapture({
+ channelRoot: plan.channelRoot,
+ slug: plan.slug,
+ readId: record.id,
+ at: record.startedAt,
+ ref,
+ ...(plan.topic ? { topic: plan.topic } : {}),
+ write: !walled,
+ });
+ const kept = captureAt(record.id);
+ let outcome: XTrendingReadOutcome;
+ let sentence: string;
+ if (walled) {
+ outcome = "login-wall";
+ sentence = `Read ${record.id} met X's login page, not the trending page: there is nothing in its capture to parse (${kept}).`;
+ } else if (ingested.onPage === 0) {
+ outcome = "nothing-recognised";
+ sentence =
+ `Parsed ${record.id} again, nothing recognised: ${plural(ingested.responses, "answer")} (${opsText(ingested.operations)}) ` +
+ `held no post the parser knows. The capture is kept (${kept}).`;
+ } else {
+ outcome = "read";
+ sentence =
+ `Parsed ${record.id} again (${record.url}): ${plural(ingested.onPage, "post")} in the capture, ${ingested.added} new, ` +
+ `in topic "${ingested.topic?.title}" (${ingested.topic?.id}). X was asked nothing.`;
+ }
+ const ok = outcome !== "login-wall";
+ if (ok) {
+ await writeXTrendingReadRecord(plan.channelRoot, {
+ ...record,
+ outcome: outcome === "read" ? "read" : record.outcome,
+ operations: ingested.operations,
+ posts: { onPage: ingested.onPage, added: record.posts.added + ingested.added },
+ ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}),
+ reparsedAt: new Date((o.now ?? Date.now)()).toISOString(),
+ });
+ }
+ log(sentence);
+ return {
+ ok,
+ slug: plan.slug,
+ mode: "reparse",
+ url: record.url,
+ trendId: record.trendId,
+ read: record.id,
+ outcome,
+ responses: ingested.responses,
+ operations: ingested.operations,
+ posts: { onPage: ingested.onPage, added: ingested.added },
+ ...(ingested.topic ? { topic: ingested.topic } : {}),
+ sentence,
+ ...(ok ? {} : { error: sentence }),
+ };
+}
diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts
@@ -43,6 +43,7 @@ import { isValidChannelSlug, listChannelConfigs, readChannelConfig } from "./cha
import { isSocialChannel } from "../lib/channelConfig";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { isXSearchChannel } from "../lib/xSearch/config";
+import { isXTrendingChannel } from "../lib/xTrending/config";
import { readPostFetchState, countPosts } from "../lib/posts-server";
import {
effectiveTier,
@@ -318,7 +319,9 @@ export function isXPostsChannel(config: ConfigLike | null | undefined): boolean
!!config &&
isSocialChannel(config) &&
config.platform === "twitter" &&
- !isWaybackPagesChannel(config as Parameters<typeof isWaybackPagesChannel>[0])
+ !isWaybackPagesChannel(config as Parameters<typeof isWaybackPagesChannel>[0]) &&
+ // A trending library has nothing an X run can fetch.
+ !isXTrendingChannel(config as Parameters<typeof isXTrendingChannel>[0])
);
}
diff --git a/common/controller/xTrendingGuards.test.ts b/common/controller/xTrendingGuards.test.ts
@@ -0,0 +1,63 @@
+// What an X trending library is kept out of (lane x-trending): the post
+// fetch, the X run, and the job kinds' declarations.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingGuards.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { getJobKind, isDrainableKind, isIngestKind, jobKindLabel, kindIsNetwork } from "../jobs/jobKinds";
+import { fetchPosts } from "./fetchPosts";
+import { isXPostsChannel } from "./xRun";
+import { READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND, X_PROFILE_BROWSER_JOB_KINDS } from "./readXTrending";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-guards-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+const LIBRARY = { handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} } as const;
+
+test("fetch-posts refuses a library with a sentence, before any fetcher is asked", async () => {
+ const channelsDir = path.join(TMP, "channels");
+ mkdirSync(path.join(channelsDir, "trending"), { recursive: true });
+ writeFileSync(path.join(channelsDir, "trending", "config.json"), JSON.stringify(LIBRARY));
+ const res = await fetchPosts({
+ paths: { transcriptsDir: TMP, channelsDir } as unknown as Paths,
+ slug: "trending",
+ settings: {} as never,
+ signal: new AbortController().signal,
+ });
+ assert.equal(res.ok, false);
+ assert.equal(
+ res.error,
+ "trending is an X trending library: it has no timeline to fetch. Read a trending page into it (pnpm ops read-x-trending).",
+ );
+});
+
+test("the X run never lists a library among the X posts channels", () => {
+ assert.equal(isXPostsChannel(LIBRARY as never), false);
+ assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), true);
+});
+
+test("read-x-trending: a network, drainable kind on X's queue that nothing replays or resumes; reparse asks nothing", () => {
+ const read = getJobKind(READ_X_TRENDING_KIND);
+ assert.ok(read, "registered");
+ assert.equal(jobKindLabel(READ_X_TRENDING_KIND), "Read X trending page");
+ assert.equal(read.queueKeyStrategy, "platform");
+ assert.equal(kindIsNetwork(READ_X_TRENDING_KIND), true);
+ assert.equal(isDrainableKind(READ_X_TRENDING_KIND), true);
+ assert.equal(read.replayable, false);
+ assert.equal(read.resumeOnBoot, undefined);
+ assert.equal(read.startedByPerson, true);
+ assert.equal(isIngestKind(READ_X_TRENDING_KIND), true);
+ const reparse = getJobKind(REPARSE_X_TRENDING_KIND);
+ assert.ok(reparse, "registered");
+ assert.equal(reparse.queueKeyStrategy, "platform");
+ assert.equal(kindIsNetwork(REPARSE_X_TRENDING_KIND), false);
+ assert.equal(reparse.replayable, false);
+ assert.equal(isIngestKind(REPARSE_X_TRENDING_KIND), true);
+ // The kinds that hold the connected profile's browser while they run.
+ assert.deepEqual([...X_PROFILE_BROWSER_JOB_KINDS], ["read-x-trending", "capture-posts"]);
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,36 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
network: true,
startedByPerson: true,
},
+ // ONE X TRENDING PAGE read into a trending library (lane x-trending,
+ // controller/readXTrending.ts): the page opened in the connected X profile's
+ // browser, what the page itself fetched saved raw, its posts parsed from the
+ // saved file. One page is one job on X's queue (`platform:twitter`), so the
+ // fresh-jar rule, the X alert and X's job gap apply and no other browser is
+ // on the profile beside it. Network; drainable (it stops between scrolls and
+ // keeps what it read); NOT replayable and not resumed on boot — a read is a
+ // request to X, and nothing repeats one unasked; started only by a person
+ // (or an agent's ask), never by a boot.
+ "read-x-trending": {
+ kind: "read-x-trending",
+ label: "Read X trending page",
+ drainable: true,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ network: true,
+ startedByPerson: true,
+ },
+ // A saved trending-page capture parsed again (`read-x-trending {"reparse"}`):
+ // offline, no request — but on X's queue, so it never writes the library's
+ // posts beside a read writing the same shards. Not drainable (one parse and
+ // one write); not replayable.
+ "reparse-x-trending": {
+ kind: "reparse-x-trending",
+ label: "Reparse X trending read",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ network: false,
+ },
// Forum thread pages the operator saved from a browser, imported into a
// forum-thread channel (controller/importForumPages.ts). Offline — nothing is
// fetched — but on the PLATFORM queue so it never writes the channel's posts
@@ -1645,6 +1675,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([
// Fetch-posts over several X channels (it carries no channelSlug: each
// channel's report regeneration is its per-channel trace).
"x-run",
+ // A trending page's posts into its library, read or parsed again.
+ "read-x-trending",
+ "reparse-x-trending",
"import-forum-pages",
"import-post",
// A page capture's records (release 37), and their re-derivation.
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -13,6 +13,7 @@ import {
import { socialLinksForSave } from "./socialLinks";
import { isRemoteOnlyChannel, parseChannelConfig } from "./channelConfig";
import { isXSearchChannel } from "./xSearch/config";
+import { isXTrendingChannel, X_TRENDING_NOT_ON_A_SITE } from "./xTrending/config";
import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
import {
isListedSite,
@@ -267,6 +268,24 @@ export function xSearchChannelOnSite(
return null;
}
+// The first member of `site` (or of its cited scope) that is an X trending
+// library (lane x-trending), by its config.json — or null. A library is
+// PRIVATE: this is the first of the three things that keep it off every site
+// (the others: buildIndex skips it; the form paths refuse it before a write).
+export function xTrendingChannelOnSite(
+ site: Pick<Site, "channels" | "citedChannels">,
+ paths: Paths,
+): string | null {
+ if (!paths.channelsDir) return 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 && isXTrendingChannel(parseChannelConfig(raw.value))) return slug;
+ }
+ return null;
+}
+
export async function writeSite(
site: Site,
paths: Paths = getPaths(),
@@ -297,6 +316,10 @@ export async function writeSite(
// 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));
+ // Nor an X trending library (lane x-trending): private until a person
+ // publishes posts out of it, which is another channel's business.
+ const trending = xTrendingChannelOnSite(site, paths);
+ if (trending) throw new Error(X_TRENDING_NOT_ON_A_SITE(trending));
// Nor a remote-only channel (demo epic D1): it has no corpus to publish.
const remoteOnly = remoteOnlyChannelOnSite(site, paths);
if (remoteOnly) throw new Error(REMOTE_ONLY_NOT_ON_A_SITE(remoteOnly));
diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts
@@ -61,6 +61,9 @@ export const X_TRENDING_NOT_ON_A_SITE = (slug: string) =>
export const X_TRENDING_HAS_NO_URL =
"An X trending library has no URL: its pages are read one at a time (pnpm ops read-x-trending, or Read a trending page on its channel page).";
+export const X_TRENDING_NOT_FETCHED = (slug: string) =>
+ `${slug} is an X trending library: it has no timeline to fetch. Read a trending page into it (pnpm ops read-x-trending).`;
+
export const NOT_AN_X_TRENDING_LIBRARY = (slug: string) =>
`${slug} is not an X trending library (create one with platform "x-trending").`;
diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts
@@ -275,6 +275,79 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead
return { topic, ...counts };
}
+// ── one read's record ──────────────────────────────────────────────────────
+
+// What read.json says of the capture: operation NAMES and SIZES, never a body.
+export type XTrendingReadOperation = {
+ op: string;
+ responses: number;
+ bytes: number;
+ statuses: number[];
+ tweets: number;
+};
+
+// How a read ended.
+// read posts were written
+// probe the capture was saved and summarised; no post written
+// nothing-recognised the capture held no post the parser knows (kept)
+// login-wall | rate-limit | gone | error the read failed, said in `sentence`
+export type XTrendingReadOutcome =
+ | "read"
+ | "probe"
+ | "nothing-recognised"
+ | "login-wall"
+ | "rate-limit"
+ | "gone"
+ | "error";
+
+export type XTrendingReadRecord = {
+ version: 1;
+ id: string;
+ trendId: string;
+ url: string;
+ startedAt: string;
+ endedAt: string;
+ probe: boolean;
+ headed: boolean;
+ limits: { scrolls: number; posts: number };
+ scrolls: number;
+ // Why the scrolling stopped (xTrendingRead.ts TrendingReadStop).
+ stop: string;
+ outcome: XTrendingReadOutcome;
+ responses: number;
+ saved: number;
+ bytes: number;
+ statuses: Record<string, number>;
+ operations: XTrendingReadOperation[];
+ // Posts the parser finds in the capture, and how many the library lacked.
+ posts: { onPage: number; added: number };
+ topic?: { id: string; title: string };
+ shot: boolean;
+ sentence: string;
+ // When the capture was last parsed again (`reparse`).
+ reparsedAt?: string;
+};
+
+function readRecordPath(channelRoot: string, readId: string): string {
+ return path.join(trendingReadDir(channelRoot, readId), TRENDING_READ_FILENAME);
+}
+
+export async function writeXTrendingReadRecord(channelRoot: string, record: XTrendingReadRecord): Promise<void> {
+ await writeJsonAtomic(readRecordPath(channelRoot, record.id), record, { mkdir: true });
+}
+
+export async function readXTrendingReadRecord(
+ channelRoot: string,
+ readId: string,
+): Promise<XTrendingReadRecord | null> {
+ if (!isXTrendingReadId(readId)) return null;
+ const read = await readJsonFile(readRecordPath(channelRoot, readId));
+ if (!read.ok) return null;
+ const r = read.value as Partial<XTrendingReadRecord> | null;
+ if (!r || r.version !== 1 || r.id !== readId || !str(r.trendId) || !str(r.url) || !str(r.startedAt)) return null;
+ return r as XTrendingReadRecord;
+}
+
// ── the listing ────────────────────────────────────────────────────────────
export type XTrendingTopicRow = {
diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts
@@ -16,19 +16,91 @@
// this process's transcriptsDir (a slot's test data), and unless that file
// exists (a spec writes it). The file holds SYNTHETIC cookies only:
// { "delayMs"?: number, "closeAfterMs"?: number, "fail"?: string,
-// "cookies": [{ name, value, domain, path?, expires? }] }
+// "cookies": [{ name, value, domain, path?, expires? }],
+// "trending"?: { href?, load: [{url, status, body?, text?}], scrolls: [[…], …] } }
+//
+// A TRENDING PAGE (lane x-trending): with `trending` in the file, the fake's
+// page answers a read of x.com/i/trending/<id> (xTrendingRead.ts) from it —
+// `load` are the answers the page "fetches" when it is opened, `scrolls[n]`
+// the ones its n-th scroll to the bottom brings, `href` where the page ended
+// up (X's login page, for a session that has ended). Invented answers only
+// (__fixtures__/xTrendingCapture.ts builds a set).
import { readFileSync, realpathSync } from "node:fs";
import path from "node:path";
import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime";
+export type FakeTrendingResponse = { url: string; status: number; body?: unknown; text?: string };
+
+export type FakeTrendingPage = {
+ // Where the page is once loaded (default: the URL asked for).
+ href?: string;
+ // goto throws this (a page that does not load).
+ gotoError?: string;
+ load: FakeTrendingResponse[];
+ scrolls?: FakeTrendingResponse[][];
+};
+
type FixtureFile = {
delayMs?: number;
closeAfterMs?: number;
fail?: string;
cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>;
+ trending?: FakeTrendingPage;
};
+// The smallest PNG there is (1×1, transparent): the fake page's "screenshot".
+const ONE_PIXEL_PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
+ "base64",
+);
+
+// A PAGE THAT PLAYS A TRENDING PAGE BACK: no browser, no request. `source` is
+// read at each step, so a spec can change the file between reads. Without a
+// trending fixture it is the inert page Refresh and Connect always had.
+export function fakeTrendingPage(
+ source: () => { delayMs?: number; trending?: FakeTrendingPage },
+ wait: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
+): PageLike {
+ const handlers: Array<(res: unknown) => void> = [];
+ let asked = "";
+ let scrolled = 0;
+ const emit = (responses: FakeTrendingResponse[] | undefined) => {
+ for (const r of responses ?? []) {
+ const res = {
+ url: () => r.url,
+ status: () => r.status,
+ text: async () => r.text ?? JSON.stringify(r.body ?? null),
+ };
+ for (const h of handlers) h(res);
+ }
+ };
+ return {
+ goto: async (url: string) => {
+ const f = source();
+ if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000));
+ asked = url;
+ scrolled = 0;
+ if (f.trending?.gotoError) throw new Error(f.trending.gotoError);
+ emit(f.trending?.load);
+ return null;
+ },
+ waitForSelector: async () => null,
+ waitForTimeout: wait,
+ evaluate: async (fn: string) => {
+ const t = source().trending;
+ if (!t) return null;
+ if (fn === "location.href") return t.href ?? asked;
+ if (fn.includes("scrollTo")) emit(t.scrolls?.[scrolled++]);
+ return null;
+ },
+ on: (event: string, cb: (arg: never) => void) => {
+ if (event === "response") handlers.push(cb as (res: unknown) => void);
+ },
+ screenshot: async () => new Uint8Array(ONE_PIXEL_PNG),
+ } as PageLike;
+}
+
export function fakeXProfileCookiesFile(
transcriptsDir: string,
env: Readonly<Record<string, string | undefined>> = process.env,
@@ -63,17 +135,7 @@ export function fakeXProfileChromium(
const file = fakeXProfileCookiesFile(transcriptsDir, env);
if (!file) return null;
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
- const page = {
- goto: async () => {
- const f = readFixture(file);
- if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000));
- return null;
- },
- waitForSelector: async () => null,
- waitForTimeout: wait,
- evaluate: async () => null,
- on: () => {},
- } as unknown as PageLike;
+ const page = fakeTrendingPage(() => readFixture(file), wait);
const context: BrowserContextLike = {
newPage: async () => page,
pages: () => [page],
diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts
@@ -0,0 +1,213 @@
+// The trending page reader over a page that plays invented answers back
+// (fakeXProfileBrowser.ts fakeTrendingPage): no browser, no request, no wait.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xTrendingRead.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fakeTrendingPage, type FakeTrendingPage } from "./fakeXProfileBrowser";
+import { isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead";
+import { readCaptureLines } from "./xTrendingParse";
+import {
+ FIXTURE_TIMELINE_OP,
+ FIXTURE_TREND_URL,
+ fixtureTimelineBody,
+ fixtureTrendingResponses,
+} from "./__fixtures__/xTrendingCapture";
+import type { BrowserContextLike, ChromiumLike } from "./playwrightRuntime";
+import type { Paths } from "../lib/paths";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-read-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+let dirs = 0;
+async function read(
+ trending: FakeTrendingPage,
+ over: { scrolls?: number; posts?: number; signal?: AbortSignal } = {},
+): Promise<{ result: TrendingPageRead; dir: string; closed: number; pauses: number[]; log: string[] }> {
+ const dir = path.join(TMP, `read-${++dirs}`);
+ const pauses: number[] = [];
+ const log: string[] = [];
+ let closed = 0;
+ const page = fakeTrendingPage(() => ({ trending }));
+ const result = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir,
+ openPage: async () => ({ page, close: async () => void closed++ }),
+ limits: { scrolls: over.scrolls ?? 8, posts: over.posts ?? 60 },
+ pauseMs: () => 7_000,
+ pause: async (ms) => void pauses.push(ms),
+ signal: over.signal ?? new AbortController().signal,
+ onLog: (l) => log.push(l),
+ now: () => Date.parse("2026-11-17T10:00:00.000Z"),
+ });
+ return { result, dir, closed, pauses, log };
+}
+
+const timelineUrl = (n: number) => `https://x.com/i/api/graphql/q${n}/${FIXTURE_TIMELINE_OP}`;
+const tweet = (n: number) => ({ id: `19000000000000020${String(n).padStart(2, "0")}`, handle: `author_${n}`, text: `Post ${n}.` });
+
+test("a read keeps every GraphQL answer raw and a screenshot, and stops after two scrolls with nothing new", async () => {
+ const { result, dir, closed, pauses } = await read(fixtureTrendingResponses());
+ assert.deepEqual(result, {
+ stop: "idle",
+ scrolls: 3,
+ responses: 4,
+ saved: 4,
+ bytes: result.bytes,
+ statuses: { "200": 4 },
+ tweets: 4,
+ shot: true,
+ });
+ assert.ok(result.bytes > 0);
+ assert.equal(closed, 1);
+ // One wait after the load, one after each scroll: never two contacts in a row.
+ assert.deepEqual(pauses, [7_000, 7_000, 7_000, 7_000]);
+ const lines = await readCaptureLines(path.join(dir, "responses.jsonl"));
+ assert.deepEqual(lines.map((l) => [l.n, l.op, l.status]), [
+ [1, "ExampleTrendPage", 200],
+ [2, FIXTURE_TIMELINE_OP, 200],
+ [3, "HomeTimeline", 200],
+ [4, FIXTURE_TIMELINE_OP, 200],
+ ]);
+ assert.ok(lines.every((l) => l.body !== undefined && l.at === "2026-11-17T10:00:00.000Z"));
+ // The answer that is not GraphQL was never kept.
+ assert.ok(!readFileSync(path.join(dir, "responses.jsonl"), "utf8").includes("example.json"));
+ assert.equal(readFileSync(path.join(dir, "page.png")).subarray(1, 4).toString(), "PNG");
+});
+
+test("the scroll cap and the post cap each stop a read", async () => {
+ const pages = (count: number) => ({
+ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }],
+ scrolls: Array.from({ length: count }, (_, i) => [
+ { url: timelineUrl(i + 1), status: 200, body: fixtureTimelineBody([tweet(i + 1)]) },
+ ]),
+ });
+ const capped = await read(pages(10), { scrolls: 3 });
+ assert.equal(capped.result.stop, "scroll-cap");
+ assert.equal(capped.result.scrolls, 3);
+ assert.equal(capped.result.tweets, 4);
+ const full = await read(pages(10), { posts: 2 });
+ assert.equal(full.result.stop, "post-cap");
+ assert.equal(full.result.scrolls, 1);
+ assert.equal(full.result.tweets, 2);
+});
+
+test("a 429 stops the read at once: no scroll follows it", async () => {
+ const first = await read({
+ load: [
+ { url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) },
+ { url: timelineUrl(1), status: 429, text: "Rate limit exceeded" },
+ ],
+ scrolls: [[{ url: timelineUrl(2), status: 200, body: fixtureTimelineBody([tweet(2)]) }]],
+ });
+ assert.equal(first.result.stop, "rate-limit");
+ assert.equal(first.result.scrolls, 0);
+ assert.deepEqual(first.result.statuses, { "200": 1, "429": 1 });
+ assert.equal(first.result.tweets, 1);
+ assert.deepEqual(first.pauses, [7_000]);
+ // On a scroll: that scroll is the last.
+ const later = await read({
+ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }],
+ scrolls: [[{ url: timelineUrl(1), status: 429, text: "" }], [{ url: timelineUrl(2), status: 200, body: {} }]],
+ });
+ assert.equal(later.result.stop, "rate-limit");
+ assert.equal(later.result.scrolls, 1);
+});
+
+test("X's login page, or a 401, is a login wall: nothing is scrolled", async () => {
+ const walled = await read({ href: "https://x.com/i/flow/login?redirect_after_login=%2Fi%2Ftrending%2F1", load: [], scrolls: [[]] });
+ assert.equal(walled.result.stop, "login-wall");
+ assert.equal(walled.result.scrolls, 0);
+ const refused = await read({ load: [{ url: timelineUrl(0), status: 401, body: { errors: [{ code: 32 }] } }] });
+ assert.equal(refused.result.stop, "login-wall");
+ assert.equal(isXLoginHref("https://x.com/login"), true);
+ assert.equal(isXLoginHref("https://x.com/account/access"), true);
+ assert.equal(isXLoginHref("https://x.com/i/trending/1"), false);
+ assert.equal(isXLoginHref("https://x.com/login_help_desk/status/1"), false);
+ assert.equal(isXLoginHref(null), false);
+});
+
+test("a page that does not load is an error with its first line; a cancelled read stops before it scrolls", async () => {
+ const broken = await read({ gotoError: "net::ERR_NAME_NOT_RESOLVED at https://x.com/i/trending/1\n call log…", load: [] });
+ assert.equal(broken.result.stop, "error");
+ assert.equal(broken.result.error, "net::ERR_NAME_NOT_RESOLVED at https://x.com/i/trending/1");
+ assert.equal(broken.closed, 1);
+ assert.equal(existsSync(path.join(broken.dir, "responses.jsonl")), true);
+ const ac = new AbortController();
+ ac.abort();
+ const cancelled = await read(fixtureTrendingResponses(), { signal: ac.signal });
+ assert.equal(cancelled.result.stop, "cancelled");
+ assert.equal(cancelled.result.scrolls, 0);
+});
+
+test("an answer that is not JSON is counted and not kept", async () => {
+ const { result, dir } = await read({ load: [{ url: timelineUrl(0), status: 200, text: "<html>not json</html>" }] });
+ assert.equal(result.responses, 1);
+ assert.equal(result.saved, 0);
+ const [line] = await readCaptureLines(path.join(dir, "responses.jsonl"));
+ assert.equal(line.skipped, "not-json");
+ assert.equal(line.body, undefined);
+});
+
+// --- which browser opens ---------------------------------------------------
+
+function stubChromium(extra: Partial<ChromiumLike> = {}) {
+ const launches: Array<{ dir: string; opts: Record<string, unknown> }> = [];
+ const page = fakeTrendingPage(() => ({}));
+ const context: BrowserContextLike = {
+ newPage: async () => page,
+ pages: () => [],
+ cookies: async () => [],
+ addCookies: async () => {},
+ close: async () => {},
+ on: () => {},
+ };
+ const chromium: ChromiumLike = {
+ launch: async () => {
+ throw new Error("not used");
+ },
+ launchPersistentContext: async (dir, opts) => {
+ launches.push({ dir, opts });
+ return context;
+ },
+ ...extra,
+ };
+ return { chromium, launches };
+}
+
+const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths;
+
+test("a read opens the connected profile headless; \"headed\" opens it in a window, through the display search", async () => {
+ const quiet = stubChromium();
+ await openXTrendingPage(paths("headless"), { chromium: quiet.chromium });
+ assert.equal(quiet.launches.length, 1);
+ assert.equal(quiet.launches[0].dir, path.join(TMP, "headless", ".x-session", "profile"));
+ assert.equal(quiet.launches[0].opts.headless, true);
+
+ const window = stubChromium({ opensNoWindow: true });
+ const log: string[] = [];
+ await openXTrendingPage(paths("headed"), { headed: true, chromium: window.chromium, env: { PATH: "" }, onLog: (l) => log.push(l) });
+ assert.equal(window.launches.length, 1);
+ assert.equal(window.launches[0].dir, path.join(TMP, "headed", ".x-session", "profile"));
+ assert.equal(window.launches[0].opts.headless, false);
+
+ // No desktop: the Connects' refusal, before any browser starts.
+ const none = stubChromium();
+ await assert.rejects(
+ openXTrendingPage(paths("nodesk"), {
+ headed: true,
+ chromium: none.chromium,
+ env: { PATH: "" },
+ display: {
+ run: async () => ({ stdout: "", exitCode: 1 }),
+ fs: { readdir: () => [], isSocket: () => false, ownedByMe: () => false },
+ },
+ }),
+ /no desktop session/,
+ );
+ assert.equal(none.launches.length, 0);
+});
diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts
@@ -0,0 +1,296 @@
+// ONE READ OF ONE X TRENDING PAGE (lane x-trending, slice 1), through the
+// connected X profile's browser — the profile capture-posts shoots with
+// (xSessionBroker.ts launchXProfile), headless unless the read asks for a
+// window (headedDisplay.ts launchHeadedContext).
+//
+// gallery-dl has no extractor for x.com/i/trending/<id> (1.32.9: no pattern,
+// no endpoint), so the page is opened as a person would open it and what the
+// PAGE ITSELF fetches is kept: every GraphQL JSON answer
+// (x.com/i/api/graphql/<id>/<Operation>) is written raw, one per line, to
+// `responses.jsonl`, with a screenshot of the loaded page beside it. Nothing
+// here asks X for anything the page did not ask: no request is built, no
+// query id is known, no header is read or stored — ONLY response bodies.
+//
+// WHAT ONE READ COSTS: one navigation, the page's own first requests, and at
+// most one more page of its timeline per scroll. A scroll moves to the bottom
+// of what has loaded (that is what makes the page ask for more), then waits
+// the X request gap (4–10 s, xGalleryDlFetcher.ts xRequestPauseMs). It stops
+// at the scroll cap, at the post cap, after two scrolls in a row that brought
+// no new post, and AT ONCE on a 429, a 401 or a login page. It never retries.
+//
+// The caller (controller/readXTrending.ts) is one editor job on X's queue;
+// this module knows nothing of queues, alerts or the store.
+
+import { appendFile, mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { X_TRENDING_IDLE_SCROLLS, type XTrendingLimits } from "../lib/xTrending/config";
+import {
+ TRENDING_PAGE_SHOT_FILENAME,
+ TRENDING_RESPONSES_FILENAME,
+} from "../lib/xTrending/store";
+import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime";
+import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay";
+import { findXBrowser } from "./xBrowser";
+import { launchXProfile, xProfileDir } from "./xSessionBroker";
+import { xIdOf } from "./xNormalize";
+import {
+ collectTimelineTweets,
+ graphqlOpOf,
+ X_TRENDING_IGNORED_OPS,
+ type TrendingCaptureLine,
+} from "./xTrendingParse";
+
+// One answer is kept up to this size, a read's answers up to this in all:
+// past either, the answer is counted (its operation and size) and not kept.
+export const TRENDING_RESPONSE_MAX_BYTES = 8 * 1024 * 1024;
+export const TRENDING_READ_MAX_BYTES = 64 * 1024 * 1024;
+
+// Why a read stopped scrolling.
+// idle two scrolls in a row brought no new post: the page's end
+// scroll-cap the read's scroll cap
+// post-cap the read's post cap
+// cancelled the job was cancelled or drained
+// rate-limit the page's own request was answered 429
+// login-wall X showed its login page, or answered 401
+// error the page did not load
+export type TrendingReadStop =
+ | "idle"
+ | "scroll-cap"
+ | "post-cap"
+ | "cancelled"
+ | "rate-limit"
+ | "login-wall"
+ | "error";
+
+export type TrendingPageRead = {
+ stop: TrendingReadStop;
+ scrolls: number;
+ // GraphQL answers seen, and how many of them were kept whole.
+ responses: number;
+ saved: number;
+ bytes: number;
+ // Answers by HTTP status ("200": 4, "404": 1).
+ statuses: Record<string, number>;
+ // Distinct posts the walk found while reading (the stop conditions' count).
+ tweets: number;
+ // page.png was written.
+ shot: boolean;
+ error?: string;
+};
+
+export type TrendingPageSession = { page: PageLike; close: () => Promise<void> };
+
+type ResponseLike = { url: () => string; status: () => number; text: () => Promise<string> };
+
+const LOGIN_HREF = /\/i\/flow\/login|\/login(?:[/?#]|$)|\/account\/access/;
+
+export function isXLoginHref(href: unknown): boolean {
+ if (typeof href !== "string") return false;
+ try {
+ return LOGIN_HREF.test(new URL(href).pathname);
+ } catch {
+ return false;
+ }
+}
+
+function firstLine(err: unknown): string {
+ return ((err as Error)?.message ?? String(err)).split("\n")[0];
+}
+
+// An abortable wait: resolves early when the signal fires.
+export function abortablePause(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted || ms <= 0) return resolve();
+ const done = () => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ resolve();
+ };
+ const timer = setTimeout(done, ms);
+ signal.addEventListener("abort", done);
+ });
+}
+
+const SCROLL_TO_BOTTOM = "window.scrollTo(0, document.documentElement.scrollHeight)";
+
+export async function readXTrendingPage(o: {
+ url: string;
+ // The read's directory (`trending/reads/<readId>`), made here.
+ dir: string;
+ openPage: () => Promise<TrendingPageSession>;
+ limits: XTrendingLimits;
+ pauseMs: () => number;
+ pause?: (ms: number, signal: AbortSignal) => Promise<void>;
+ signal: AbortSignal;
+ onLog?: (line: string) => void;
+ now?: () => number;
+}): Promise<TrendingPageRead> {
+ const log = o.onLog ?? (() => {});
+ const pause = o.pause ?? abortablePause;
+ const now = o.now ?? Date.now;
+ await mkdir(o.dir, { recursive: true });
+ const file = path.join(o.dir, TRENDING_RESPONSES_FILENAME);
+ await writeFile(file, "");
+
+ const out: TrendingPageRead = {
+ stop: "idle",
+ scrolls: 0,
+ responses: 0,
+ saved: 0,
+ bytes: 0,
+ statuses: {},
+ tweets: 0,
+ shot: false,
+ };
+ const seen = new Set<string>();
+ let rateLimited = false;
+ let unauthorized = false;
+ let n = 0;
+ let writes: Promise<void> = Promise.resolve();
+ const pending = new Set<Promise<void>>();
+
+ const keep = (line: TrendingCaptureLine) => {
+ writes = writes.then(() => appendFile(file, JSON.stringify(line) + "\n")).catch(() => {});
+ };
+
+ const onResponse = (res: ResponseLike) => {
+ let url: string;
+ let status: number;
+ try {
+ url = res.url();
+ status = res.status();
+ } catch {
+ return;
+ }
+ const op = graphqlOpOf(url);
+ if (!op) return;
+ out.responses++;
+ out.statuses[String(status)] = (out.statuses[String(status)] ?? 0) + 1;
+ if (status === 429) rateLimited = true;
+ if (status === 401) unauthorized = true;
+ const base = { n: ++n, at: new Date(now()).toISOString(), op, status, url };
+ const task = (async () => {
+ let text: string;
+ try {
+ text = await res.text();
+ } catch {
+ keep({ ...base, bytes: 0, skipped: "unread" });
+ return;
+ }
+ const bytes = Buffer.byteLength(text);
+ if (bytes > TRENDING_RESPONSE_MAX_BYTES) return keep({ ...base, bytes, skipped: "too-large" });
+ if (out.bytes + bytes > TRENDING_READ_MAX_BYTES) return keep({ ...base, bytes, skipped: "over-cap" });
+ let body: unknown;
+ try {
+ body = JSON.parse(text);
+ } catch {
+ return keep({ ...base, bytes, skipped: "not-json" });
+ }
+ out.bytes += bytes;
+ out.saved++;
+ keep({ ...base, bytes, body });
+ if (status >= 200 && status < 300 && !X_TRENDING_IGNORED_OPS.includes(op)) {
+ for (const raw of collectTimelineTweets(body)) {
+ const id = xIdOf(raw);
+ if (id) seen.add(id);
+ }
+ }
+ })();
+ pending.add(task);
+ void task.finally(() => pending.delete(task));
+ };
+
+ // The answers in flight, read to their end (at most 15 s).
+ const settle = async () => {
+ const all = Promise.allSettled([...pending]);
+ await Promise.race([all, new Promise((r) => setTimeout(r, 15_000))]);
+ };
+ const blocked = (): TrendingReadStop | null => (unauthorized ? "login-wall" : rateLimited ? "rate-limit" : null);
+
+ let session: TrendingPageSession | undefined;
+ try {
+ session = await o.openPage();
+ const { page } = session;
+ page.on("response", onResponse as (arg: never) => void);
+ await page.goto(o.url, { waitUntil: "domcontentloaded", timeout: 60_000 });
+ // The page settles: its first requests go out and come back.
+ await pause(o.pauseMs(), o.signal);
+ await settle();
+ const href = await page.evaluate("location.href").catch(() => null);
+ if (isXLoginHref(href)) unauthorized = true;
+ try {
+ const png = await page.screenshot({ type: "png" });
+ await writeFile(path.join(o.dir, TRENDING_PAGE_SHOT_FILENAME), png);
+ out.shot = true;
+ } catch (err) {
+ log(`No screenshot of the page: ${firstLine(err)}`);
+ }
+ log(`The page loaded: ${out.responses} answer(s), ${seen.size} post(s) so far.`);
+
+ let idle = 0;
+ let stop: TrendingReadStop | null = blocked();
+ while (!stop) {
+ if (o.signal.aborted) stop = "cancelled";
+ else if (seen.size >= o.limits.posts) stop = "post-cap";
+ else if (out.scrolls >= o.limits.scrolls) stop = "scroll-cap";
+ if (stop) break;
+ const before = seen.size;
+ await page.evaluate(SCROLL_TO_BOTTOM);
+ out.scrolls++;
+ await pause(o.pauseMs(), o.signal);
+ await settle();
+ stop = blocked();
+ if (stop) break;
+ if (seen.size === before) {
+ if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle";
+ } else {
+ idle = 0;
+ }
+ log(`Scroll ${out.scrolls}: ${seen.size} post(s), ${out.responses} answer(s).`);
+ }
+ out.stop = stop ?? "idle";
+ } catch (err) {
+ out.stop = blocked() ?? (o.signal.aborted ? "cancelled" : "error");
+ out.error = firstLine(err);
+ } finally {
+ await settle();
+ await writes;
+ await session?.close().catch(() => {});
+ }
+ out.tweets = seen.size;
+ return out;
+}
+
+// THE PROFILE'S PAGE. Headless: the bundled build on the connected profile,
+// as a post capture opens it. Headed: a window on the editor's desktop, found
+// at this read as a Connect finds it (refused with its sentence when there is
+// no desktop). `chromium` is injectable (the e2e suite's fake, tests' stubs).
+export async function openXTrendingPage(
+ paths: Paths,
+ o: {
+ headed?: boolean;
+ chromium?: ChromiumLike;
+ onLog?: (line: string) => void;
+ env?: Record<string, string | undefined>;
+ display?: HeadedDisplayLaunchDeps;
+ } = {},
+): Promise<TrendingPageSession> {
+ const log = o.onLog ?? (() => {});
+ let context;
+ if (o.headed) {
+ const chromium = o.chromium ?? (await importPlaywright()).chromium;
+ ({ context } = await launchHeadedContext({
+ chromium,
+ profileDir: xProfileDir(paths),
+ browser: findXBrowser({ env: o.env }),
+ onLog: log,
+ env: o.env,
+ display: o.display,
+ }));
+ } else {
+ context = await launchXProfile(paths, { onLog: log, ...(o.chromium ? { chromium: o.chromium } : {}) });
+ }
+ const page = context.pages()[0] ?? (await context.newPage());
+ return { page, close: () => context.close() };
+}