commit 5a55e58328ee113053867f149be276fe00e1297c
parent ae5c3492b6131d47350d86cac48072d54865041d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 23:27:43 -0500
Merge lane/x-trending: a private library of X trending pages, slice 1 -- a channel of platform "x-trending" holds what a trending page showed: `read-x-trending` opens one page on the connected X profile, saves the page's own answers and a screenshot under channels/<lib>/trending/reads/, lists the topic and its posts (never fetching media, never asking X anything the page did not ask), and can probe or reparse a saved read; a 429 stops the read and leaves X alone for 15 minutes, captures included; a library is refused by every publishing door (sites, articles, reports, umtool's post archive), by its marker; listing through `get trending` and two MCP read tools
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
69 files changed, 6625 insertions(+), 42 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -61,6 +61,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `mirror` | config | 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. See [`mirror`](#mirror). |
| `wayback` | config | 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. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". |
| `xSearch` | config | 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. |
+| `xTrending` | config | An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X's trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor's own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field. |
| `localMedia` | config | Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports. |
#### `downloadFilter`
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -136,7 +136,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
| `archives` | archives connects a published archive as a source: {"connect": "<origin>"} reads <origin>/corpus.json once (its title, totals and channels) and saves it in settings.remoteArchives; "dryRun"? answers the probe and writes nothing; an origin connected already writes nothing. A federation hub, a cited-only site, one with no channels or one that does not answer is refused. {"remove": "<id or origin>"} drops one. Create, research and the MCP offer each connected archive; a sweep over it cites it. | `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'` |
-| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` |
+| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Trending","handling":"transcribe","platform":"x-trending"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
| `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` |
@@ -218,6 +218,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `save-page-now-batch` | save-page-now-batch saves a LIST of pages as ONE resumable job: {"urls": \[...\]} \| {"file": <abs path: a JSON list, {urls}, or a URL a line>} \| {"batch": <id>}, "skipArchived"? (true), "sources"? (\["wayback", "archive.today"\]), "evidence"? (abs path), "dailyCap"? (150 anonymous, at most 200; 5000 with keys), "dryRun"? -> {jobId, batch}. Each URL in turn: looked up (the Wayback CDX, archive.today's timemap, each paced) and archived-already when a copy shows it (a Wayback row that recorded a 200, or an archive.today copy); else saved through Save Page Now's pacer (anonymous without keys), saved or failed with the reason; a site Save Page Now refuses as a site (x.com, 5 Nov: "limitations when it comes to archiving this site") is asked once a run, its other URLs looked up only. archive.today and Ghostarchive are looked up, never asked to save. The state is <transcripts>/.spn-batches/<batch>.json, written after every URL: the same request again, {batch}, a Retry or a restart continues from the first pending URL. The evidence (JSON + CSV: url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt) is rewritten after every URL; default <transcripts>/.spn-batches/<batch>.evidence.json. Progress (done/total, ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode, counts, run, evidence, statePath, etaSeconds, stopped?}. | `pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'`<br>`pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'`<br>`pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'` |
| `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -> {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` |
| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -> {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -> {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` |
+| `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/<number>"}, as one job on X's queue (the fresh-jar rule, the X alert and X's job gap apply; ask get x-session first). The page is opened in the connected X profile's browser, every GraphQL answer the page itself fetched is saved raw with a screenshot (channels/<slug>/trending/reads/<readId>/), and the posts are parsed from the saved file and written as the library's posts. A read lists posts; it archives no media and no thread. "topic": a 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 it). "scrolls": 1-20 moves to the bottom of the page (default: the channel's cap, else 8); "posts": stop once 1-200 are seen (else 60); a read also stops after two scrolls with nothing new, and at once on a 429, a 403 or a login wall. A 429 leaves X alone for 15 minutes (no read is queued or started before the time its sentence names); a page that stops answering ends the read within 6 minutes. Nothing retries. "probe": true saves the capture and its summary and writes no post. "headed": true opens a window on the editor's desktop. {"slug", "reparse": "<readId>"} parses a saved read again OFFLINE (X is asked nothing; a read left with no record takes "url" too). No fresh jar needed. --wait prints the log's @@read-x-trending {ok, mode, read, outcome, stop, responses, operations (names and sizes, never a body), posts: {onPage, added}, topic, sentence}; a capture with no post the parser knows ends ok, "read saved, nothing recognised". Refused before a job: not a library, not a trending page URL, a cap out of range, no connected X profile, X's Connect or Refresh in flight, a stale jar. A library is made with create-channel, "platform": "x-trending" (no "url", no "sites": it is private, never on a site, in no index build; "xTrendingMaxScrolls"?, "xTrendingMaxPosts"? set its caps). | `pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait` |
| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` |
| `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -> {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` |
@@ -261,6 +262,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get x-session [<slug>]
pnpm ops get cookies [fresh]
pnpm ops get x-run [<run id>]
+ pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>]
pnpm ops get cleanup <slug>
pnpm ops get speakers
pnpm ops get lookouts [<id>]
@@ -368,6 +370,17 @@ get cookies [fresh] is the /cookies screen's rows, one per service the
browser's cookie store (names and times only, never a value) instead of
the 5-minute cache. Check again is recheck-service; Refresh cookies and
the Connects are clicks on /cookies.
+get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending
+ library's topics and posts, read from its own files (a library is in no
+ index): topics [{id, title, posts, sources: [{trendId, url, reads,
+ lastReadAt}]}], posts [{id, author, authorName, createdAt, url, text,
+ media: {count, kinds, thumbnail?}, topic, reads: [{read, trendId, at}],
+ judgement?}] (the newest read's first, in page order; --limit 1-500,
+ default 100; total is the count before it) and reads (the saved reads'
+ ids, newest first). thumbnail is a captured post's first picture
+ (trending/posts-media/<id>/<name>, relative to the channel); judgement
+ is {state: keep | drop | undecided, note?, by, at} once a post has one. Never the
+ raw capture, a cookie or a token.
get x-run [<run id>] is the X run as /review's X run console shows it:
the latest run (or the one named) — each channel's status (queued,
running, done with its new posts, deferred, failed), "summary" ("N
diff --git a/OPERATING.md b/OPERATING.md
@@ -211,7 +211,7 @@ pnpm ops dismiss-service --json '{"service":"rumble"}'
Connect archive session (/cookies). A Connect that ends on a cleared page clears the banner too.
- **X** (`"service":"x"`): a Cloudflare challenge, a 401/403 or a login wall in gallery-dl's output — even
on a run that exits 0 — fails the fetch (posts read so far kept) and raises it; one is enough. **While it
- is up, no X job starts**: every fetch, older walk, X search, capture or import on X is refused with its
+ is up, no X job starts**: every fetch, older walk, X search, trending read, capture or import on X is refused with its
sentence, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand (Connect X
account on /cookies and clear it in the window; with the browser login, open x.com in that browser),
press **Refresh cookies**, then **Recheck** — which sends X *no* request: it clears when the login on disk
@@ -619,6 +619,88 @@ pnpm ops x-search-lead --json '{"slug":"zephyr-search","handle":"example","acti
- An X search channel is never put on a site (refused on create, on Configure, and by every site writer); its posts
follow `social.x.visibility` like any X channel's.
+### X trending pages, in a private library
+
+```sh
+pnpm ops get x-session # would an X job start now? (the jar's age, the limit)
+pnpm ops create-channel --json '{"fields":{"name":"Trending","handling":"transcribe","platform":"x-trending"}}'
+pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait
+pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait
+pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait
+pnpm ops get trending trending --topic kettle-festival --limit 50
+```
+
+- **X trending library** in the New channel form's Platform (`"platform": "x-trending"`) makes a private posts
+ channel with no URL (`config.xTrending`, CHANNEL.md). Its records are the posts X's trending pages
+ (`x.com/i/trending/<number>`) showed, from any account, grouped into your topics.
+- **A library is private.** It is never put on a site (refused on create, on Configure and by every site writer),
+ and no index build reads it. So its posts are in no site, hub, `corpus.json`, `llms.txt` or MCP corpus tool, and
+ not in the editor's own search either. The channel page's **Topics**, `get trending` and the MCP's
+ `x_trending_topics` / `x_trending_posts` read the library's own files. A library stays one: Configure can neither
+ make a library nor turn one into an ordinary channel, and no patch changes its platform, kind or URL.
+- **No report, article, draft or video project is offered a library's posts.** The posts are kept in
+ `channels/<slug>/trending/posts/` (a posts channel's format, one directory down), not in `channels/<slug>/posts/`
+ where every other reader of a posts channel looks: reports and drafts, research runs, the availability checks,
+ umtool's post search, Add posts and reels. To all of those a library has no posts. An article or a site report
+ that cites a library by name is refused (`"<slug>" is an X trending library: it is private, and a report cannot
+ cite its posts`), a draft's X link never resolves to a library, and a research run is not shown one.
+- **The raw captures never leave the machine.** `channels/<slug>/trending/reads/.gitignore` ignores everything
+ under it, so the corpus's own git repo never commits a capture. No Archilyzer path copies them anywhere: the
+ media moves (the Storage panel, `/storage`) move `media/` only, the saved-video backup covers the saved-video
+ store, the transcript archives read `data/`, and the source mirror publishes this code repo, not the corpus.
+ Nothing in Archilyzer commits or pushes the corpus repo; a backup you run yourself over `transcripts/` is yours
+ to point away from `trending/reads/`.
+- **One page is one job on X's queue** (`read-x-trending`): the fresh-jar rule, the X alert and X's 5-minute job
+ gap apply as to every X job. The page is opened in the connected X profile's browser (headless; `"headed": true`
+ opens a window on the editor's desktop), and what the page itself fetches is kept: every GraphQL JSON answer, raw,
+ in `channels/<slug>/trending/reads/<readId>/responses.jsonl`, a screenshot (`page.png`) and the read's record
+ (`read.json`: operation names and sizes only). No request is built and no header is stored. That directory is
+ never served or indexed.
+- **What a read costs**: one page load, 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, then waits 4–10 s. It stops at the scroll cap
+ (`"scrolls"`, 1–20, default 8), at the post cap (`"posts"`, 1–200, default 60), after two scrolls that brought
+ nothing new, and at once on a 429, a 403, a 401 or X's login page. Nothing retries.
+- **A read cannot hang.** The page's load has 75 s; a scroll, the address and the screenshot 20 s each; closing
+ the browser 10 s (then it is killed); the whole read 6 minutes. Past any of them the read fails with a sentence,
+ the browser closed and the capture kept. The channel's own caps are
+ `xTrendingMaxScrolls` / `xTrendingMaxPosts` (Configure, or `channel-config`).
+- **A read lists posts**: the post's words, author, date and its media by kind, parsed from the saved file and
+ written as the library's posts. It fetches no media, no thread and no screenshot of a post. A re-read of the same
+ page adds the new posts, keeps the old ones and records the read with its time.
+- **Topics.** `"topic"` is a topic's id or name, or a new one's name: several pages can be read into one topic.
+ Without it the posts go to the topic that page was read into before, else to a new one named for the page. A post
+ already in a topic stays there.
+- **`"probe": true`** saves the capture and a summary (the operations' names and sizes, how many posts the parser
+ finds) and writes no post. `{"reparse": "<readId>"}` parses a saved capture again, offline, as a
+ `reparse-x-trending` job: X is asked nothing, so it needs no fresh jar. `read.json` is written when a read
+ starts and again when it ends, so any capture can be parsed again; one left with its answers and no record
+ takes `"url"` beside `"reparse"` to say which page it was. A read that is still queued or running is not
+ reparsed: ask once it has finished.
+- **How a read ends**, in the job's last line (`@@read-x-trending {…, "sentence"}`):
+ - `Read …: N posts on the page, M new, in topic "…"`.
+ - `Read saved, nothing recognised: …`: the answers held no post the parser knows. Not a failure, no X alert; the
+ capture is kept for the parser.
+ - `X asked to log in instead of showing the trending page …`: fails, no post written, and X's cookie alert goes
+ up (no X job starts until it is cleared).
+ - `X answered 429 (rate limit) …`: fails, the posts read before it kept, no alert. X is then left alone for 15
+ minutes, whatever else went wrong with the read: no trending read is queued or started before the time the
+ sentence names. It is the `twitter` platform cooldown, so for those 15 minutes it also holds an X post capture
+ (which fails at its start with the same sentence), import-post on X, and the download lane's X units. It ends
+ by itself; a clean read does not clear it, and never touches a hold the download lane set for its own reason.
+ - `X answered 403 (forbidden) …`: fails at once, the posts read before it kept. No login alert, unless the page
+ also showed the login wall. The sentence names the operation that was refused, and `read.json`'s `stoppedBy`
+ its name and status (for a 429 and a 401 too).
+ - `The page was read and saved (…), but its posts could not be written: …`: fails; reparse the read.
+ - `X no longer has this trending page …`, `The trending page could not be loaded: …` and `The trending page
+ stopped answering: …`: fail, capture kept.
+- **One browser on the X profile at a time.** While a `read-x-trending` or `capture-posts` job is running on X's
+ queue, X's Connect and Refresh cookies are refused with a sentence naming the job ("Cancel it on /jobs or wait
+ for it to finish"); a job that is only queued blocks nothing. While a Connect or Refresh is running, a trending
+ read is refused (when asked and again when it starts) and an X post capture fails at its start with the same
+ sentence. Which job is X's is decided by its channel's platform, not by the queue it was put on; a capture that
+ takes no screenshot (`"shots": false`, and neither the avatars nor the context alone) opens no browser, so it
+ neither blocks a press nor is blocked by one. Refresh the cookies first, then read.
+
## Transcribe
```sh
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -22,6 +22,7 @@
// see composeCitedSite.
import { writeJsonAtomic } from "../lib/jsonFile-server";
+import { isXTrendingChannel } from "../lib/xTrending/config";
import { isLocalRecord } from "../lib/localMedia";
import path from "node:path";
import { cp, link, mkdir, rm, readdir, access, readFile, writeFile, stat, rename } from "node:fs/promises";
@@ -1120,7 +1121,11 @@ export async function main(
const tombstones = await writePostsTombstones({
postsDir: paths.exportPostsDir,
sharedPostsDir: paths.exportSharedPostsDir,
- slugs: site.channels.map((c) => c.slug).filter((slug) => !memberSet.has(slug)),
+ // Not an X trending library (lane x-trending): no site ever served one, so
+ // there is nothing to replace — and a tombstone would publish its slug.
+ slugs: site.channels
+ .map((c) => c.slug)
+ .filter((slug) => !memberSet.has(slug) && !isXTrendingChannel(configs.get(slug))),
});
// --- tombstones for the channels that left this site's pool (release 24 H1) ---
// Every per-channel tree the site's last bundle served that this compose does
diff --git a/common/bin/xTrendingPrivacy.test.ts b/common/bin/xTrendingPrivacy.test.ts
@@ -0,0 +1,226 @@
+// 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, writeXTrendingPosts, 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: {},
+});
+const libPosts = [post(LIB, "1900000000000006001", HANDLE_MARK, `a trending post ${POST_MARK}`)];
+// Where a library keeps them, AND where an ordinary posts channel would (a
+// hand copy): neither may reach a build.
+await writeXTrendingPosts(libRoot, libPosts);
+await writePosts(libRoot, libPosts);
+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,515 @@
+// 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 { listXTrending, readXTrendingPosts, 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, held: async () => null };
+
+async function run(
+ paths: Paths,
+ trending: FakeTrendingPage,
+ ask: Partial<ReadXTrendingAsk> = {},
+ over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise<string | null>; ingest?: never; openPage?: never } = {},
+): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[]; limited: number; cleaned: number }> {
+ 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[] = [];
+ let limited = 0;
+ const cleaned = 0;
+ const at = Date.parse(over.at ?? "2026-11-17T10:00:00.000Z");
+ const page = fakeTrendingPage(() => ({ trending }));
+ const result = await runXTrendingRead({
+ paths,
+ plan: planned.plan as never,
+ onLog: (l) => log.push(l),
+ deps: {
+ openPage: over.openPage ?? (async () => ({ page, close: async () => {} })),
+ held: over.held ?? (async () => null),
+ noteRateLimit: async () => (limited++, at + 15 * 60_000),
+ ...(over.ingest ? { ingest: over.ingest } : {}),
+ 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, limited, cleaned };
+}
+
+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: { hasProfile: () => Promise<boolean>; held?: () => Promise<string | null> } = 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 })), /holds no saved read/);
+ 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 readXTrendingPosts(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 readXTrendingPosts(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 readXTrendingPosts(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 readXTrendingPosts(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, limited, cleaned } = await run(paths, {
+ load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }],
+ scrolls: f.scrolls,
+ });
+ // X is left alone for 15 minutes, and the sentence says until when.
+ assert.equal(limited, 1);
+ assert.equal(cleaned, 0);
+ assert.match(result.sentence, /No trending read starts before 10:15 UTC \(15 min\); nothing retries by itself\./);
+ 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.deepEqual(notes, []);
+ assert.equal((await readXTrendingPosts(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);
+});
+
+// --- review 1 ---------------------------------------------------------------
+
+test("a slug is checked by the plan itself, before it becomes a path", async () => {
+ const paths = corpus("slug");
+ for (const slug of ["../trending", "a/b", "", ".hidden"]) {
+ const r = await planReadXTrending(paths, { slug, url: FIXTURE_TREND_URL }, withProfile);
+ assert.equal(r.ok, false);
+ assert.match(r.ok ? "" : r.error, /is not a valid channel slug/);
+ }
+});
+
+test("X cooling down after a rate limit refuses a read at enqueue and at its start: no browser opens", async () => {
+ const paths = corpus("held");
+ const sentence = "X answered a rate limit (429) a short while ago: no trending read starts before 10:15 UTC (12 min from now). Ask again then; nothing retries by itself.";
+ const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, { hasProfile: async () => true, held: async () => sentence });
+ assert.deepEqual(planned, { ok: false, error: sentence });
+ // Queued before the rate limit, started after it.
+ let opened = 0;
+ const { result } = await run(paths, fixtureTrendingResponses(), {}, {
+ held: async () => sentence,
+ openPage: (async () => {
+ opened++;
+ throw new Error("must not open");
+ }) as never,
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "rate-limit");
+ assert.equal(result.sentence, sentence);
+ assert.equal(opened, 0);
+ assert.equal(existsSync(path.join(root(paths), "trending")), false);
+});
+
+test("a clean read records no rate limit; the real cooldown is 15 minutes on the twitter platform entry", async () => {
+ const paths = corpus("clean");
+ const { limited } = await run(paths, fixtureTrendingResponses());
+ assert.equal(limited, 0);
+ const { X_RATE_LIMIT_HOLD_MS } = await import("./readXTrending");
+ assert.equal(X_RATE_LIMIT_HOLD_MS, 15 * 60_000);
+});
+
+test("a 403 fails with its own sentence, keeps what was read, and raises no login alert", async () => {
+ const paths = corpus("forbidden");
+ const f = fixtureTrendingResponses();
+ const { result, notes, limited } = await run(paths, {
+ load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 403, body: { errors: [{ code: 200 }] } }],
+ scrolls: f.scrolls,
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "forbidden");
+ assert.equal(result.scrolls, 0);
+ assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExampleTrendTimeline\): the read stopped at once/);
+ assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./);
+ assert.match(result.sentence, /not taken for a lost login and no alert was raised/);
+ assert.deepEqual(notes, []);
+ assert.equal(limited, 0);
+ assert.equal((await readXTrendingPosts(root(paths))).length, 3);
+});
+
+test("a page that stops answering fails with a sentence, the capture kept", async () => {
+ const paths = corpus("hung");
+ const base = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ const page = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(Object.assign(new Error("the page did not answer within 20 s (scrolling)"), { name: "PageDeadlineError" })) : base.evaluate(fn)) };
+ const { PageDeadlineError } = await import("../social/xTrendingRead");
+ const hung = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? Promise.reject(new PageDeadlineError("scrolling", 20_000)) : base.evaluate(fn)) };
+ void page;
+ const { result } = await run(paths, fixtureTrendingResponses(), {}, { openPage: (async () => ({ page: hung, close: async () => {} })) as never });
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "error");
+ assert.equal(result.stop, "deadline");
+ assert.match(result.sentence, /^The trending page stopped answering: the page did not answer within 20 s \(scrolling\)\. The browser was closed\. 3 posts read before it were kept \(3 new\)\./);
+});
+
+test("the record is written when the read starts, and a parse that fails still leaves one: the capture is parsed again offline", async () => {
+ const paths = corpus("ingest");
+ // While the page is being opened, read.json is already there.
+ let early: unknown = null;
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ const failing = await run(paths, fixtureTrendingResponses(), { topic: "Kettles" }, {
+ openPage: (async () => {
+ early = await readXTrendingReadRecord(root(paths), READ_1);
+ return { page, close: async () => {} };
+ }) as never,
+ ingest: (async () => {
+ throw new Error("EACCES: permission denied, open 'posts'\n at somewhere");
+ }) as never,
+ });
+ assert.equal((early as { stop?: string } | null)?.stop, "started");
+ assert.equal((early as { outcome?: string } | null)?.outcome, "error");
+ assert.equal(failing.result.ok, false);
+ assert.equal(failing.result.outcome, "error");
+ assert.match(
+ failing.result.sentence,
+ /^The page was read and saved \(4 answers\), but its posts could not be written: EACCES: permission denied, open 'posts'\. The capture is kept/,
+ );
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.equal(record?.outcome, "error");
+ assert.equal(record?.stop, "idle");
+ assert.equal((await readXTrendingPosts(root(paths))).length, 0);
+ // The offline reparse finds the record and writes the posts.
+ const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, topic: "Kettles" });
+ assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error);
+ const reparsed = await reparseXTrendingRead({ plan: planned.plan as never });
+ assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 });
+ assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read");
+});
+
+test("a read left with its answers and no record is parsed again once the page is named", async () => {
+ const paths = corpus("recordless");
+ await run(paths, fixtureTrendingResponses(), { probe: true });
+ rmSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"));
+ const bare = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 });
+ assert.equal(bare.ok, false);
+ assert.match(bare.ok ? "" : bare.error, /has its answers but no record of which page it read: give "url"/);
+ const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL });
+ assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error);
+ const reparsed = await reparseXTrendingRead({ plan: planned.plan as never });
+ assert.equal(reparsed.ok, true);
+ assert.deepEqual(reparsed.posts, { onPage: 4, added: 4 });
+ assert.equal(reparsed.trendId, FIXTURE_TREND_ID);
+ assert.equal((await readXTrendingReadRecord(root(paths), READ_1))?.outcome, "read");
+ // A read WITH its record takes no url beside reparse.
+ const both = await planReadXTrending(paths, { slug: "trending", reparse: READ_1, url: FIXTURE_TREND_URL });
+ assert.match(both.ok ? "" : both.error, /one of them/);
+});
+
+test("a reparse updates the topic's record of the read: what the capture holds, and what was added in all", async () => {
+ const paths = corpus("recount");
+ await run(paths, fixtureTrendingResponses(), { probe: true });
+ const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 });
+ assert.ok(planned.ok && planned.plan.mode === "reparse");
+ await reparseXTrendingRead({ plan: planned.plan as never });
+ await reparseXTrendingRead({ plan: planned.plan as never });
+ const { readXTrendingTopics } = await import("../lib/xTrending/store");
+ const [topic] = await readXTrendingTopics(root(paths));
+ assert.deepEqual(topic.sources[0].reads, [{ id: READ_1, at: "2026-11-17T10:00:00.000Z", posts: 4, added: 4 }]);
+});
+
+test("the captures are never committed: the reads directory ignores everything under it", async () => {
+ const paths = corpus("gitignore");
+ await run(paths, fixtureTrendingResponses());
+ const ignore = readFileSync(path.join(root(paths), "trending", "reads", ".gitignore"), "utf8");
+ assert.match(ignore, /^\*$/m);
+ // And it is not taken for a read.
+ assert.deepEqual((await listXTrending(root(paths))).reads, [READ_1]);
+});
+
+// --- review 2 ---------------------------------------------------------------
+
+test("N2: a 429 leaves X alone even when the posts then cannot be written", async () => {
+ const paths = corpus("limited-and-broken");
+ const f = fixtureTrendingResponses();
+ const { result, limited } = await run(
+ paths,
+ { load: [f.load[1], { url: `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}`, status: 429, text: "" }], scrolls: f.scrolls },
+ {},
+ { ingest: (async () => { throw new Error("EACCES: permission denied"); }) as never },
+ );
+ assert.equal(limited, 1, "the cooldown was recorded");
+ assert.equal(result.ok, false);
+ assert.equal(result.outcome, "error");
+ assert.match(result.sentence, /its posts could not be written: EACCES: permission denied\./);
+ assert.match(result.sentence, /X also answered 429 \(rate limit\): no trending read starts before 10:15 UTC \(15 min\)\./);
+});
+
+test("read.json names the operation and status that stopped a read", async () => {
+ const paths = corpus("stopped-by");
+ const f = fixtureTrendingResponses();
+ const { result } = await run(paths, {
+ load: [f.load[1], { url: "https://x.com/i/api/graphql/q9/ExamplePeripheralOp?variables=%7B%7D", status: 403, body: { errors: [] } }],
+ scrolls: f.scrolls,
+ });
+ assert.deepEqual(result.stoppedBy, { op: "ExamplePeripheralOp", status: 403 });
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.deepEqual(record?.stoppedBy, { op: "ExamplePeripheralOp", status: 403 });
+ assert.match(result.sentence, /^X answered 403 \(forbidden\) to the page's own request \(ExamplePeripheralOp\)/);
+ // A read nothing stopped names none.
+ const clean = await run(paths, fixtureTrendingResponses(), {}, { readId: READ_2 });
+ assert.equal(clean.result.stoppedBy, undefined);
+ assert.equal((await readXTrendingReadRecord(root(paths), READ_2))?.stoppedBy, undefined);
+});
+
+test("N7: a reparse planned while the read was unfinished parses the record as it is when the job runs", async () => {
+ const paths = corpus("stale-plan");
+ // The plan is made from the record a read writes when it STARTS.
+ let planned: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ await run(paths, fixtureTrendingResponses(), { probe: true }, {
+ openPage: (async () => {
+ planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 });
+ return { page, close: async () => {} };
+ }) as never,
+ });
+ assert.ok(planned && (planned as { ok: boolean }).ok);
+ const plan = (planned as unknown as { plan: { record: { stop: string } } }).plan;
+ assert.equal(plan.record.stop, "started");
+ // The read has finished since. The reparse must not put the stale record back.
+ const reparsed = await reparseXTrendingRead({ plan: plan as never });
+ assert.equal(reparsed.ok, true);
+ const record = await readXTrendingReadRecord(root(paths), READ_1);
+ assert.equal(record?.stop, "idle");
+ assert.equal(record?.scrolls, 3);
+ assert.equal(record?.responses, 4);
+ assert.equal(record?.probe, true);
+ assert.equal(record?.outcome, "read");
+ assert.equal(record?.shot, true);
+});
+
+test("N7: a reparse of a read that is still running is refused; of one that died unfinished, allowed", async () => {
+ const paths = corpus("running");
+ let running: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ let dead: Awaited<ReturnType<typeof planReadXTrending>> | null = null;
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ await run(paths, fixtureTrendingResponses(), {}, {
+ openPage: (async () => {
+ running = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => true });
+ dead = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false });
+ return { page, close: async () => {} };
+ }) as never,
+ });
+ assert.deepEqual(running, {
+ ok: false,
+ error: `Read ${READ_1} is still running: parse it again once it has finished (its job is on /jobs).`,
+ });
+ assert.equal((dead as unknown as { ok: boolean }).ok, true);
+});
diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts
@@ -0,0 +1,657 @@
+// 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 (month shards, deduped by id, under
+// the library's own trending/ — store.ts xTrendingPostsRoot says why not
+// where a posts channel keeps them), 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 — and X is left alone for X_RATE_LIMIT_HOLD_MS, 15 minutes, a
+// cooldown the next read's enqueue and start both refuse on), a 403 (its own
+// sentence, no alert), a page X no longer has, a page that did not load or
+// stopped answering. What was read before the failure is kept.
+//
+// read.json IS ALWAYS THERE (review 1): it is written when the read starts
+// (as a read that did not finish), and again when it ends, whatever the
+// parse did — so a capture can always be parsed again offline.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { stat } from "node:fs/promises";
+import { noteXServiceOutcome } from "../lib/serviceCookies-server";
+import {
+ heldPlatformRefusal,
+ platformCooldownRemainingMs,
+ recordPlatformCooldown,
+} from "../jobs/downloadBackoff";
+import {
+ isXTrendingChannel,
+ NOT_A_TRENDING_URL,
+ NOT_AN_X_TRENDING_LIBRARY,
+ parseXTrendingUrl,
+ xRateLimitHoldSentence,
+ xTrendingLimits,
+ type XTrendingLimits,
+ type XTrendingRef,
+} from "../lib/xTrending/config";
+import {
+ ensureXTrendingReadsDir,
+ isXTrendingReadId,
+ readXTrendingReadRecord,
+ recordXTrendingRead,
+ topicTitleProblem,
+ TRENDING_DIRNAME,
+ TRENDING_READS_DIRNAME,
+ TRENDING_RESPONSES_FILENAME,
+ trendingReadDir,
+ writeXTrendingPosts,
+ 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 { isValidChannelSlug, readChannelConfig } from "./channels";
+
+export {
+ READ_X_TRENDING_KIND,
+ REPARSE_X_TRENDING_KIND,
+ X_PROFILE_BROWSER_JOB_KINDS,
+ X_TRENDING_QUEUE,
+} from "../lib/xTrending/config";
+export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending ";
+
+// How long X is left alone after it answered a read with 429: X's own
+// rate-limit window. Written as the `twitter` platform cooldown
+// (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post
+// already respects), read by this job's enqueue and start.
+export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000;
+const X_PLATFORM = "twitter";
+
+const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16);
+
+// Why no trending read may start now — X is cooling down after a rate limit,
+// or held — or null.
+export async function xTrendingHeld(paths: Paths, now: number = Date.now()): Promise<string | null> {
+ const held = await heldPlatformRefusal(X_PLATFORM, "This trending read", paths, now).catch(() => null);
+ if (held) return held;
+ const ms = await platformCooldownRemainingMs(X_PLATFORM, paths).catch(() => 0);
+ if (ms <= 0) return null;
+ return xRateLimitHoldSentence("trending read", ms, now);
+}
+
+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 };
+
+// A read left with its answers and no record (a crash before any record was
+// written, a library from before review 1): the record a reparse starts from.
+function recordlessRead(readId: string, ref: XTrendingRef, at: string): XTrendingReadRecord {
+ return {
+ version: 1,
+ id: readId,
+ trendId: ref.trendId,
+ url: ref.url,
+ startedAt: at,
+ endedAt: at,
+ probe: false,
+ headed: false,
+ limits: { scrolls: 0, posts: 0 },
+ scrolls: 0,
+ stop: "unknown",
+ outcome: "error",
+ responses: 0,
+ saved: 0,
+ bytes: 0,
+ statuses: {},
+ operations: [],
+ posts: { onPage: 0, added: 0 },
+ shot: false,
+ sentence: "This read left its answers and no record.",
+ };
+}
+
+// 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>;
+ held?: () => Promise<string | null>;
+ // Whether a read-x-trending job of this library is queued or running
+ // (the editor asks its registry): a record still marked "started" then
+ // belongs to a read in flight, not to one that died.
+ readInFlight?: () => Promise<boolean>;
+ } = {},
+): Promise<{ ok: true; plan: ReadXTrendingPlan } | { ok: false; error: string }> {
+ const fail = (error: string) => ({ ok: false as const, error });
+ // The slug becomes a path below: checked here, whoever the caller is.
+ if (!isValidChannelSlug(ask.slug)) {
+ return fail(`"${String(ask.slug)}" is not a valid channel slug (letters, digits, ".", "_", "-"; must start with a letter or digit)`);
+ }
+ 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-…)`);
+ let record = await readXTrendingReadRecord(channelRoot, ask.reparse);
+ if (record && hasUrl) {
+ return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`);
+ }
+ if (!record) {
+ // Its answers without its record: parsed all the same, once the caller
+ // says which page it was (the record is what knew).
+ const capture = path.join(trendingReadDir(channelRoot, ask.reparse), TRENDING_RESPONSES_FILENAME);
+ const saved = await stat(capture).catch(() => null);
+ if (!saved?.isFile()) {
+ return fail(`${ask.slug} holds no saved read ${ask.reparse} (pnpm ops get trending ${ask.slug} lists them).`);
+ }
+ const ref = hasUrl ? parseXTrendingUrl(ask.url) : null;
+ if (!ref) {
+ return fail(
+ `Saved read ${ask.reparse} has its answers but no record of which page it read: ` +
+ `give "url" (that trending page, https://x.com/i/trending/<number>) with "reparse".`,
+ );
+ }
+ record = recordlessRead(ask.reparse, ref, saved.mtime.toISOString());
+ }
+ // A read that has not ended (review 2 N7): its record is the one written
+ // when it started, and its capture is still being written.
+ if (record.stop === "started" && (await deps.readInFlight?.())) {
+ return fail(`Read ${ask.reparse} is still running: parse it again once it has finished (its job is on /jobs).`);
+ }
+ return { ok: true, plan: { mode: "reparse", slug: ask.slug, channelRoot, record, ...(topic ? { topic } : {}) } };
+ }
+ if (hasReparse) return fail(`Give "url" (a trending page to read) or "reparse" (a saved read's id), one of them.`);
+ 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);
+ // X cooling down after a rate limit: refused before a job exists.
+ const held = await (deps.held ?? (() => xTrendingHeld(paths)))();
+ if (held) return fail(held);
+ 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;
+ // The operation and status of the first answer that stopped the read.
+ stoppedBy?: { op: string; status: 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 writeXTrendingPosts(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;
+ // X's cooldown: why no read may start now; a rate limit recorded (answers
+ // when it ends, ms since the epoch). Nothing settles it early: it runs out.
+ held?: () => Promise<string | null>;
+ noteRateLimit?: () => Promise<number>;
+ // For tests: the capture → library step (default: ingestCapture).
+ ingest?: typeof ingestCapture;
+};
+
+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 };
+ // And X's cooldown, asked again here: a read queued before a rate limit
+ // does not navigate X when its turn comes.
+ const held = await (deps.held ?? (() => xTrendingHeld(paths, now())))();
+ if (held) return { ...base, ...none, ok: false, outcome: "rate-limit", sentence: held, error: held };
+
+ const startedAt = new Date(now()).toISOString();
+ // The record exists from the first moment: a read that dies anywhere below
+ // leaves a capture that can still be parsed again.
+ await ensureXTrendingReadsDir(plan.channelRoot);
+ const started: XTrendingReadRecord = {
+ version: 1,
+ id: readId,
+ trendId: plan.ref.trendId,
+ url: plan.ref.url,
+ startedAt,
+ endedAt: startedAt,
+ probe: plan.probe,
+ headed: plan.headed,
+ limits: plan.limits,
+ scrolls: 0,
+ stop: "started",
+ outcome: "error",
+ responses: 0,
+ saved: 0,
+ bytes: 0,
+ statuses: {},
+ operations: [],
+ posts: { onPage: 0, added: 0 },
+ shot: false,
+ sentence: `This read did not finish. Whatever it captured is kept (${captureAt(readId)}); read-x-trending {"reparse": "${readId}"} parses it without asking X.`,
+ };
+ await writeXTrendingReadRecord(plan.channelRoot, started);
+ 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";
+ // The parse may fail (a shape it chokes on, a disk that refuses): the read's
+ // record is written all the same, and the capture is there for a reparse.
+ let ingested: Ingested = { operations: [], responses: page.responses, onPage: 0, added: 0 };
+ let ingestError: string | undefined;
+ try {
+ ingested = await (deps.ingest ?? ingestCapture)({
+ channelRoot: plan.channelRoot,
+ slug: plan.slug,
+ readId,
+ at: startedAt,
+ ref: plan.ref,
+ ...(plan.topic ? { topic: plan.topic } : {}),
+ write: !plan.probe && !walled,
+ });
+ } catch (err) {
+ ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0];
+ }
+ 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)`}.`
+ : "";
+
+ // A 429 LEAVES X ALONE WHATEVER ELSE WENT WRONG (review 2 N2): the cooldown
+ // is recorded before the outcome is decided, so a parse that also failed
+ // cannot send the next read straight back to X.
+ let limitedUntil: number | undefined;
+ if (page.stop === "rate-limit") {
+ limitedUntil = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch(
+ () => now() + X_RATE_LIMIT_HOLD_MS,
+ );
+ }
+ const untilText =
+ limitedUntil === undefined ? "" : `${hhmm(limitedUntil)} UTC (${Math.ceil((limitedUntil - now()) / 60_000)} min)`;
+ const leftAlone = limitedUntil === undefined ? "" : ` No trending read starts before ${untilText}`;
+ const by = page.stoppedBy ? ` (${page.stoppedBy.op})` : "";
+
+ 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 (ingestError !== undefined) {
+ outcome = "error";
+ sentence =
+ `The page was read and saved (${plural(page.responses, "answer")}), but its posts could not be written: ${ingestError}. ` +
+ (limitedUntil === undefined ? "" : `X also answered 429 (rate limit): no trending read starts before ${untilText}. `) +
+ `The capture is kept (${kept}); read-x-trending {"reparse": "${readId}"} parses it again without asking X.`;
+ } else if (page.stop === "rate-limit") {
+ outcome = "rate-limit";
+ sentence =
+ `X answered 429 (rate limit) to the page's own request${by}: the read stopped at once and asked nothing more.` +
+ readSoFar +
+ `${leftAlone}; nothing retries by itself. The capture is kept (${kept}).`;
+ } else if (page.stop === "forbidden") {
+ outcome = "forbidden";
+ sentence =
+ `X answered 403 (forbidden) to the page's own request${by}: the read stopped at once and asked nothing more.` +
+ readSoFar +
+ " The page did not show the login wall, so this is not taken for a lost login and no alert was raised; " +
+ `if it happens again, Check login on /cookies. The capture is kept (${kept}).`;
+ } else if (page.stop === "deadline") {
+ outcome = "error";
+ sentence =
+ `The trending page stopped answering: ${page.error ?? "the read ran past its deadline"}. The browser was closed.` +
+ readSoFar +
+ ` 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);
+ // The platform's backoff is NOT settled here (review 2 N4): that entry is
+ // shared with the download lane's X units, whose hold and pace are theirs
+ // to ease. A cooldown this job set ends at its `until`.
+ }
+ 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,
+ ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}),
+ sentence,
+ };
+ await writeXTrendingReadRecord(plan.channelRoot, record);
+ log(sentence);
+ return {
+ ...base,
+ ok,
+ outcome,
+ stop: page.stop,
+ scrolls: page.scrolls,
+ ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}),
+ 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 ?? (() => {});
+ // THE RECORD AS IT IS NOW (review 2 N7), not as the plan saw it: the plan
+ // may have been made while the read was still running, and a reparse that
+ // wrote the plan's copy back would replace the read's final record with the
+ // one it started with. (The plan's is used only for a read that has none.)
+ const record = (await readXTrendingReadRecord(plan.channelRoot, plan.record.id)) ?? 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/reportDraft.ts b/common/controller/reportDraft.ts
@@ -89,6 +89,7 @@ import {
} from "../lib/report/iterations";
import { diskPostChannelOf } from "../lib/report/convert-server";
import { readAllPosts } from "../lib/posts-server";
+import { isXTrendingChannel } from "../lib/xTrending/config";
import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index";
import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
import { loadDeckChecks, type DeckChecks } from "../lib/report/draft/tasks/deckChecks";
@@ -628,11 +629,13 @@ export type ReportDraftDeps = {
};
// The editor's channels, as a research run lists them.
-async function editorChannelsOf(paths: Paths): Promise<EditorChannel[]> {
+export async function editorChannelsOf(paths: Pick<Paths, "channelsDir">): Promise<EditorChannel[]> {
// A remote-only channel (demo epic D1) is no channel of the editor's own —
// it holds an archive's clip windows — so a research run never lists it, or
// imports into it.
- return (await listChannelConfigs(paths)).filter(({ config }) => !isRemoteOnlyChannel(config)).map(({ slug, config }) => {
+ // Nor is an X trending library (lane x-trending): private, so a research
+ // run never lists it, reads it or imports into it.
+ return (await listChannelConfigs(paths as Paths)).filter(({ config }) => !isRemoteOnlyChannel(config) && !isXTrendingChannel(config)).map(({ slug, config }) => {
const c = config as Record<string, unknown>;
const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined);
const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling"));
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/xTrendingCooldown.test.ts b/common/controller/xTrendingCooldown.test.ts
@@ -0,0 +1,71 @@
+// X's cooldown after a trending read met a rate limit (lane x-trending, review
+// 1 SHOULD 5), on the real state file of a temp corpus: 15 minutes on the
+// `twitter` platform entry, read back by the read's own held check.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingCooldown.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-cooldown-"));
+Object.assign(process.env, { TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), SETTINGS_FILE: path.join(ROOT, "settings.json") });
+writeFileSync(path.join(ROOT, "settings.json"), "{}");
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { platformCooldownRemainingMs, recordPlatformClean, recordPlatformCooldown } = await import("../jobs/downloadBackoff");
+const { X_RATE_LIMIT_HOLD_MS, xTrendingHeld } = await import("./readXTrending");
+
+test("no cooldown: a read may start; after a 429: refused until the minute it names; a clean answer settles it", async () => {
+ const paths = getPaths();
+ assert.equal(await xTrendingHeld(paths), null);
+ const now = Date.now();
+ const until = await recordPlatformCooldown("twitter", X_RATE_LIMIT_HOLD_MS, paths, now);
+ assert.equal(until, now + 15 * 60_000);
+ const left = await platformCooldownRemainingMs("twitter", paths);
+ assert.ok(left > 14 * 60_000 && left <= 15 * 60_000, String(left));
+ const held = await xTrendingHeld(paths, now);
+ assert.match(
+ held ?? "",
+ /^X answered a rate limit \(429\) a short while ago: no trending read starts before \d\d:\d\d UTC \(15 min from now\)\. Ask again then; nothing retries by itself\.$/,
+ );
+ assert.ok(held!.includes(new Date(until).toISOString().slice(11, 16)));
+ // Another platform is not held by it.
+ assert.equal(await platformCooldownRemainingMs("bluesky", paths), 0);
+ // A second, shorter cooldown never brings the end forward.
+ assert.equal(await recordPlatformCooldown("twitter", 60_000, paths, now), until);
+ await recordPlatformClean("twitter", paths);
+ assert.equal(await xTrendingHeld(paths), null);
+});
+
+// Review 2 N4: a clean trending read settles nothing on the platform. The
+// download lane's own backoff and pace for X are its own; the read's cooldown
+// simply runs out.
+test("N4: a clean read leaves the download lane's X backoff exactly as it was", async () => {
+ const { mkdirSync, writeFileSync: write } = await import("node:fs");
+ const { recordDownloadBackoff } = await import("../jobs/downloadBackoff");
+ const { planReadXTrending, runXTrendingRead } = await import("./readXTrending");
+ const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser");
+ const { FIXTURE_TREND_URL, fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture");
+ const paths = getPaths();
+ mkdirSync(path.join(paths.channelsDir, "trending"), { recursive: true });
+ write(path.join(paths.channelsDir, "trending", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }));
+ // The lane met a rate limit on X for its own reason.
+ await recordDownloadBackoff("twitter", paths, "rate_limit");
+ const before = await platformCooldownRemainingMs("twitter", paths);
+ assert.ok(before > 0);
+ const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, { hasProfile: async () => true, held: async () => null });
+ assert.ok(planned.ok && planned.plan.mode === "read");
+ const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() }));
+ const result = await runXTrendingRead({
+ paths,
+ plan: planned.plan as never,
+ deps: { openPage: async () => ({ page, close: async () => {} }), pauseMs: () => 0, pause: async () => {}, held: async () => null, noteOutcome: async () => null },
+ });
+ assert.equal(result.outcome, "read");
+ const after = await platformCooldownRemainingMs("twitter", paths);
+ assert.ok(after > 0 && after <= before, `the lane's cooldown stands (${before} → ${after})`);
+});
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 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), false);
+ 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/downloadBackoff.ts b/common/jobs/downloadBackoff.ts
@@ -116,6 +116,28 @@ export async function recordDownloadBackoff(
});
}
+// A COOLDOWN OF A STATED LENGTH on a platform (lane x-trending, review 1): a
+// reader that met the platform's rate limit itself and knows how long to stay
+// away — an X trending read answered 429 — sets the same `platformBackoff`
+// entry the exponential one above writes, so every reader of it
+// (platformCooldownRemainingMs: import-post, the trending read's own enqueue
+// and start checks) sees one cooldown. `until` only ever moves later; the
+// failure count climbs by one. Returns when it ends (ms since the epoch).
+export async function recordPlatformCooldown(
+ platform: string,
+ ms: number,
+ paths: Paths = getPaths(),
+ now: number = Date.now(),
+): Promise<number> {
+ return mutateDownloadState(paths, (state) => {
+ prunePlatformPacing(state.download, now);
+ const prev = state.download.platformBackoff[platform];
+ const next = mergeBackoffEntry(prev, { until: now + ms, fails: (prev?.fails ?? 0) + 1 });
+ state.download.platformBackoff[platform] = next;
+ return next.until;
+ });
+}
+
// Record a SUBTITLE 429 against one video (release 17, slice RL): the count
// climbs and the batch subtitle fetch leaves it alone for 6 h, or for 7 days
// from the third. The platform's backoff, hold and pace are not touched.
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -681,6 +681,37 @@ 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; not drainable (a read is a minute or
+ // two; a Cancel stops it between scrolls and what it read is kept); 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: false,
+ 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 +1676,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/channelConfig.ts b/common/lib/channelConfig.ts
@@ -2,6 +2,7 @@ import { coerceLocalMediaConfig, type LocalMediaConfig } from "./localMedia";
import { PLATFORM_VALUES, type Platform } from "./platform";
import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config";
import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config";
+import { coerceXTrendingConfig, type XTrendingConfig } from "./xTrending/config";
import {
isDownloadFormatPreset,
isSourceVideoQuality,
@@ -302,6 +303,8 @@ export type ChannelConfig = {
wayback?: WaybackPagesConfig;
// Release 38: an X search channel's query (lib/xSearch/config.ts).
xSearch?: XSearchConfig;
+ // Lane x-trending: an X trending library's marker and caps (lib/xTrending/config.ts).
+ xTrending?: XTrendingConfig;
// External library inputs are not managed media. A config change never moves files.
localMedia?: LocalMediaConfig;
};
@@ -398,6 +401,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
'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. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".',
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.',
+ xTrending:
+ 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.',
localMedia:
"Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.",
};
@@ -618,6 +623,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
mirror: coerceMirrorConfig,
wayback: coerceWaybackPagesConfig,
xSearch: coerceXSearchConfig,
+ xTrending: coerceXTrendingConfig,
localMedia: coerceLocalMediaConfig,
};
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, 48); // 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 49); // lane x-trending: `xTrending`; 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
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
@@ -90,6 +90,7 @@ export const channelConfigObjectSchema = z.object({
mirror: field("mirror"),
wayback: field("wayback"),
xSearch: field("xSearch"),
+ xTrending: field("xTrending"),
localMedia: field("localMedia"),
});
diff --git a/common/lib/postsVisibility.ts b/common/lib/postsVisibility.ts
@@ -33,11 +33,12 @@ import { isPrivateSite, type Site } from "./siteSchema";
import type { XPostsVisibility } from "../social/xCookieSource";
import { isWaybackPagesChannel } from "./waybackPages/config";
import { isXTargetUrl } from "./waybackPages/urls";
+import { isXTrendingChannel } from "./xTrending/config";
// What the rule reads of a config: its kind and platform, and for a Wayback
// pages channel its scope.
type VisibilityConfig = Pick<ChannelConfig, "sourceKind" | "platform"> &
- Partial<Pick<ChannelConfig, "url" | "wayback">>;
+ Partial<Pick<ChannelConfig, "url" | "wayback" | "xTrending">>;
// An X channel: the posts of a social channel whose platform is X — and
// (release 37) a Wayback pages channel whose scope is on X (a target on
@@ -73,6 +74,9 @@ export function postsVisibleTo(
config: VisibilityConfig | null | undefined,
settings: { social?: { x?: { visibility?: unknown } } },
): boolean {
+ // An X trending library (lane x-trending) is private: NO site carries it,
+ // a private one included, whatever the X visibility setting says.
+ if (isXTrendingChannel(config)) return false;
if (!isXPostsChannel(config)) return true;
if (xPostsVisibility(settings) === "public") return true;
return isPrivateSite(site);
diff --git a/common/lib/report/convert-server.ts b/common/lib/report/convert-server.ts
@@ -15,6 +15,7 @@ import { assertChannelTextReadable } from "../channelMedia";
import { resolveVideoDir } from "../videoDir-server.mjs";
import { isSafeChannelSegment, isSafeIdSegment } from "../citations/moments";
import { readAllPosts, readSeenPostIds } from "../posts-server";
+import { isXTrendingLibrary } from "../xTrending/library-server";
import type { Post } from "../posts";
import type { Cue, CuesOf, PostChannelOf } from "./convertShared";
import type { PostOf, PostRecord } from "./convertManifest";
@@ -84,6 +85,9 @@ export function diskPostChannelOf(channelsDir: string): PostChannelOf {
const build = async () => {
const byId = new Map<string, string[]>();
for (const slug of await channelSlugs(channelsDir)) {
+ // Never an X trending library (lane x-trending): a draft's X URL must
+ // not resolve to a private library because only it holds the post.
+ if (await isXTrendingLibrary(channelsDir, slug)) continue;
for (const id of await readSeenPostIds(path.join(channelsDir, slug))) {
byId.set(id, [...(byId.get(id) ?? []), slug]);
}
@@ -104,6 +108,8 @@ export function diskPostOf(channelsDir: string): PostOf {
const channels = new Map<string, Promise<Map<string, Post>>>();
return async (channel, id) => {
if (!isSafeChannelSegment(channel)) return null;
+ // A library's post is no record a report may read.
+ if (await isXTrendingLibrary(channelsDir, channel)) return null;
let p = channels.get(channel);
if (!p) {
p = readAllPosts(path.join(channelsDir, channel)).then(
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.test.ts b/common/lib/xTrending/config.test.ts
@@ -0,0 +1,78 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ coerceXTrendingConfig,
+ isXTrendingChannel,
+ parseXTrendingUrl,
+ xTrendingLimits,
+} from "./config";
+import { parseChannelConfig } from "../channelConfig";
+
+test("a trending page URL is its id; anything else is refused", () => {
+ assert.deepEqual(parseXTrendingUrl("https://x.com/i/trending/1900000000000000001"), {
+ trendId: "1900000000000000001",
+ url: "https://x.com/i/trending/1900000000000000001",
+ });
+ // twitter.com, a trailing slash, a query and a fragment all name the same page.
+ assert.equal(
+ parseXTrendingUrl(" https://twitter.com/i/trending/1900000000000000001/?src=trend_click#top ")?.url,
+ "https://x.com/i/trending/1900000000000000001",
+ );
+ for (const bad of [
+ "",
+ "x.com/i/trending/1",
+ "https://x.com/i/trending/",
+ "https://x.com/i/trending/abc",
+ "https://x.com/i/trending/1/more",
+ "https://x.com/example/status/1",
+ "https://x.com/search?q=1",
+ "https://x.com.example.test/i/trending/1",
+ "ftp://x.com/i/trending/1",
+ null,
+ 42,
+ ]) {
+ assert.equal(parseXTrendingUrl(bad), null, String(bad));
+ }
+});
+
+test("the marker is an object; its caps are kept only in range", () => {
+ assert.deepEqual(coerceXTrendingConfig({}), {});
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 4, maxPosts: 30, other: 1 }), { maxScrolls: 4, maxPosts: 30 });
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 21, maxPosts: 0 }), {});
+ assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 2.5, maxPosts: "9" }), {});
+ for (const bad of [undefined, null, true, "yes", 1, []]) assert.equal(coerceXTrendingConfig(bad), undefined);
+});
+
+test("a library is a channel carrying the marker — the marker alone — and its config survives a parse", () => {
+ const config = parseChannelConfig({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ name: "Trending",
+ xTrending: { maxPosts: 40 },
+ });
+ assert.ok(config);
+ assert.deepEqual(config!.xTrending, { maxPosts: 40 });
+ assert.equal(isXTrendingChannel(config), true);
+ assert.equal(isXTrendingChannel({ sourceKind: "social", platform: "twitter" } as never), false);
+ // THE MARKER ALONE DECIDES: a library whose kind or platform was changed is
+ // still a library (and still private).
+ assert.equal(isXTrendingChannel({ sourceKind: "video", platform: "twitter", xTrending: {} } as never), true);
+ assert.equal(isXTrendingChannel({ sourceKind: "social", platform: "bluesky", xTrending: {} } as never), true);
+ assert.equal(isXTrendingChannel({ xTrending: { maxPosts: 3 } }), true);
+ for (const none of [undefined, null, false, true, "yes", 1, []]) assert.equal(isXTrendingChannel({ xTrending: none }), false);
+ assert.equal(isXTrendingChannel(null), false);
+});
+
+test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; out of range is refused", () => {
+ assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 8, posts: 60 } });
+ assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 60 } });
+ assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }, { scrolls: 20, posts: 200 }), {
+ ok: true,
+ limits: { scrolls: 20, posts: 200 },
+ });
+ assert.deepEqual(xTrendingLimits({}, { scrolls: 21 }), { ok: false, error: '"scrolls" is a whole number, 1–20' });
+ assert.deepEqual(xTrendingLimits({}, { posts: 201 }), { ok: false, error: '"posts" is a whole number, 1–200' });
+ assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–200' });
+ assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–20' });
+});
diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts
@@ -0,0 +1,140 @@
+// AN X TRENDING LIBRARY (lane x-trending, slice 1): a PRIVATE posts channel on
+// platform "twitter", `sourceKind: "social"`, with no `url` — nothing syncs it.
+// Its records are the posts X's trending pages (x.com/i/trending/<id>) showed,
+// from any author, read one page at a time by `read-x-trending`
+// (controller/readXTrending.ts) and grouped into the operator's topics
+// (lib/xTrending/store.ts). `config.xTrending` marks the channel and may hold
+// the caps a read uses when the ask names none.
+//
+// NEVER ON A SITE, IN NO INDEX BUILD: every site writer refuses it
+// (lib/site.ts), and buildIndex skips it, so no staging index, shard,
+// corpus.json, llms.txt or MCP corpus tool carries its posts. The library's
+// own listing reads its files (store.ts), never the index.
+//
+// Client-safe, and a leaf but for ./marker.mjs (itself one): lib/channelConfig.ts
+// composes the coercion below, and the channel form imports the URL helper.
+
+export type XTrendingConfig = {
+ // How many times a read moves to the bottom of the loaded page (each brings
+ // at most one more page of the timeline). Absent: X_TRENDING_DEFAULT_SCROLLS.
+ maxScrolls?: number;
+ // A read stops scrolling once it has seen this many posts. Absent:
+ // X_TRENDING_DEFAULT_POSTS.
+ maxPosts?: number;
+};
+
+// The two job kinds, and X's platform queue they run on: one browser on the
+// profile at a time, X's gap between jobs.
+export const READ_X_TRENDING_KIND = "read-x-trending";
+export const REPARSE_X_TRENDING_KIND = "reparse-x-trending";
+export const X_TRENDING_QUEUE = "platform:twitter";
+
+// 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"];
+
+// X is cooling down after a rate limit: why `what` ("trending read", "X
+// capture") does not start, and until when. One sentence for every job that
+// reads the cooldown.
+export function xRateLimitHoldSentence(what: string, remainingMs: number, now: number): string {
+ const until = new Date(now + remainingMs).toISOString().slice(11, 16);
+ return (
+ `X answered a rate limit (429) a short while ago: no ${what} starts before ${until} UTC ` +
+ `(${Math.ceil(remainingMs / 60_000)} min from now). Ask again then; nothing retries by itself.`
+ );
+}
+
+export const X_TRENDING_DEFAULT_SCROLLS = 8;
+export const X_TRENDING_MAX_SCROLLS = 20;
+export const X_TRENDING_DEFAULT_POSTS = 60;
+export const X_TRENDING_MAX_POSTS = 200;
+// A read ends after this many scrolls in a row that brought no new post.
+export const X_TRENDING_IDLE_SCROLLS = 2;
+
+function capOf(v: unknown, max: number): number | undefined {
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= max ? v : undefined;
+}
+
+// `config.xTrending`: an object (the marker), its caps kept when valid and
+// omitted when not. Anything that is not an object is no library.
+export function coerceXTrendingConfig(v: unknown): XTrendingConfig | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ const out: XTrendingConfig = {};
+ const scrolls = capOf(r.maxScrolls, X_TRENDING_MAX_SCROLLS);
+ const posts = capOf(r.maxPosts, X_TRENDING_MAX_POSTS);
+ if (scrolls !== undefined) out.maxScrolls = scrolls;
+ if (posts !== undefined) out.maxPosts = posts;
+ return out;
+}
+
+// An X trending library: a channel carrying the marker. THE MARKER ALONE
+// DECIDES (review 1) — ./marker.mjs holds the predicate, plain JavaScript so
+// umtool's .mjs readers of the corpus ask the very same question.
+export { isXTrendingChannel } from "./marker.mjs";
+
+export const X_TRENDING_NOT_CITABLE = (slug: string) =>
+ `"${slug}" is an X trending library: it is private, and a report cannot cite its posts. ` +
+ `Publish the posts out of it into a posts channel first.`;
+
+export const X_TRENDING_NOT_ON_A_SITE = (slug: string) =>
+ `${slug} is an X trending library: it is private, and never put on a site.`;
+
+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").`;
+
+export const NOT_A_TRENDING_URL =
+ "not a trending page URL: give X's trending page, https://x.com/i/trending/<number>";
+
+const X_HOST_RE = /^(?:www\.|mobile\.)?(?:x|twitter)\.com$/i;
+
+export type XTrendingRef = {
+ // X's numeric id of the trending page.
+ trendId: string;
+ // The page as it is asked: always x.com, no query, no fragment.
+ url: string;
+};
+
+// An X trending page URL (x.com or twitter.com /i/trending/<digits>), or null.
+// The query string and fragment are dropped: the page is its id.
+export function parseXTrendingUrl(input: unknown): XTrendingRef | null {
+ if (typeof input !== "string" || !input.trim()) return null;
+ let u: URL;
+ try {
+ u = new URL(input.trim());
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (!X_HOST_RE.test(u.hostname)) return null;
+ const m = /^\/i\/trending\/(\d{1,25})\/?$/.exec(u.pathname);
+ if (!m) return null;
+ return { trendId: m[1], url: `https://x.com/i/trending/${m[1]}` };
+}
+
+export type XTrendingLimits = { scrolls: number; posts: number };
+
+// The caps of one read: the ask's, else the channel's, else the defaults.
+// A value outside 1–max is refused with a sentence, never clamped.
+export function xTrendingLimits(
+ config: XTrendingConfig | undefined,
+ ask: { scrolls?: unknown; posts?: unknown } = {},
+): { ok: true; limits: XTrendingLimits } | { ok: false; error: string } {
+ const one = (asked: unknown, stored: number | undefined, dflt: number, max: number, what: string) => {
+ if (asked === undefined || asked === null) return stored ?? dflt;
+ const n = capOf(asked, max);
+ return n === undefined ? `"${what}" is a whole number, 1–${max}` : n;
+ };
+ const scrolls = one(ask.scrolls, config?.maxScrolls, X_TRENDING_DEFAULT_SCROLLS, X_TRENDING_MAX_SCROLLS, "scrolls");
+ if (typeof scrolls === "string") return { ok: false, error: scrolls };
+ const posts = one(ask.posts, config?.maxPosts, X_TRENDING_DEFAULT_POSTS, X_TRENDING_MAX_POSTS, "posts");
+ if (typeof posts === "string") return { ok: false, error: posts };
+ return { ok: true, limits: { scrolls, posts } };
+}
diff --git a/common/lib/xTrending/library-server.ts b/common/lib/xTrending/library-server.ts
@@ -0,0 +1,28 @@
+// "IS THIS CHANNEL AN X TRENDING LIBRARY?", asked of the disk by the doors a
+// library is kept behind (lane x-trending, review 1): the report hosts, the
+// draft's post resolver, a research run's channel list. One small read of the
+// channel's config.json; the MARKER ALONE decides (lib/xTrending/config.ts
+// isXTrendingChannel), so a library whose kind or platform was edited by hand
+// is still one. SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { readJsonFile, readJsonFileSync } from "../jsonFile-server";
+import { isXTrendingChannel } from "./config";
+
+const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+function marked(value: unknown): boolean {
+ return isXTrendingChannel(value && typeof value === "object" ? (value as { xTrending?: unknown }) : null);
+}
+
+export function isXTrendingLibrarySync(channelsDir: string | undefined, slug: string): boolean {
+ if (!channelsDir || !SLUG.test(slug)) return false;
+ const raw = readJsonFileSync(path.join(channelsDir, slug, "config.json"));
+ return raw.ok && marked(raw.value);
+}
+
+export async function isXTrendingLibrary(channelsDir: string | undefined, slug: string): Promise<boolean> {
+ if (!channelsDir || !SLUG.test(slug)) return false;
+ const raw = await readJsonFile(path.join(channelsDir, slug, "config.json"));
+ return raw.ok && marked(raw.value);
+}
diff --git a/common/lib/xTrending/marker.d.mts b/common/lib/xTrending/marker.d.mts
@@ -0,0 +1,3 @@
+// Types for ./marker.mjs (lane x-trending): the library marker's predicate.
+
+export function isXTrendingChannel(config: { xTrending?: unknown } | null | undefined): boolean;
diff --git a/common/lib/xTrending/marker.mjs b/common/lib/xTrending/marker.mjs
@@ -0,0 +1,17 @@
+// THE X TRENDING LIBRARY MARKER, as plain JavaScript (lane x-trending, review
+// 2): the one predicate "is this channel config a library's?", importable by
+// umtool's .mjs readers of the corpus as well as by common's TypeScript
+// (lib/xTrending/config.ts re-exports it). A LEAF: no imports.
+//
+// THE MARKER ALONE DECIDES: `xTrending` is an object. Not the kind, not the
+// platform — a config edit that changed either must not switch a library's
+// privacy off while its posts stay.
+
+/**
+ * @param {{ xTrending?: unknown } | null | undefined} config
+ * @returns {boolean}
+ */
+export function isXTrendingChannel(config) {
+ const m = config?.xTrending;
+ return Boolean(m) && typeof m === "object" && !Array.isArray(m);
+}
diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts
@@ -0,0 +1,288 @@
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ listXTrending,
+ readXTrendingMembership,
+ readXTrendingTopics,
+ recordXTrendingRead,
+ writeXTrendingPosts,
+ topicIdFromTitle,
+ topicTitleProblem,
+ trendingReadDir,
+} from "./store";
+import type { Post } from "../posts";
+
+const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-store-"));
+after(() => rmSync(TMP, { recursive: true, force: true }));
+
+const READ_A = "tr-01JA0000000000000000000000";
+const READ_B = "tr-01JB0000000000000000000000";
+const READ_C = "tr-01JC0000000000000000000000";
+const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" };
+const REF_2 = { trendId: "1900000000000000002", url: "https://x.com/i/trending/1900000000000000002" };
+
+function post(id: string, author: string, text: string): Post {
+ return {
+ id,
+ slug: `lib/${id}`,
+ channelSlug: "lib",
+ author,
+ createdAt: "2026-11-16T12:00:00.000Z",
+ uploadDate: "20261116",
+ text,
+ url: `https://x.com/${author}/status/${id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ };
+}
+
+function root(name: string): string {
+ const dir = path.join(TMP, name);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+test("a read id is checked where it becomes a path", () => {
+ assert.equal(trendingReadDir("/c/lib", READ_A), `/c/lib/trending/reads/${READ_A}`);
+ for (const bad of ["../x", "tr-short", "xr-01JA0000000000000000000000", ""]) {
+ assert.throws(() => trendingReadDir("/c/lib", bad), /not a trending read id/);
+ }
+});
+
+test("a topic id comes from its title; a title is refused when empty or too long", () => {
+ assert.equal(topicIdFromTitle(" Kettle Festival 2026! "), "kettle-festival-2026");
+ assert.equal(topicIdFromTitle("!!!"), "");
+ assert.equal(topicTitleProblem("Kettles"), null);
+ assert.match(topicTitleProblem(" ") ?? "", /topic/);
+ assert.match(topicTitleProblem("x".repeat(121)) ?? "", /at most 120/);
+});
+
+test("the first read of a page makes a topic named for it; a re-read adds posts, keeps old ones, appends the read", async () => {
+ const dir = root("reread");
+ await writeXTrendingPosts(dir, [post("101", "teapot_news", "one"), post("102", "saucer_fan", "two")]);
+ const first = await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ postIds: ["101", "102"],
+ added: 2,
+ media: { "101": { count: 2, kinds: ["image"] } },
+ });
+ assert.deepEqual(first, {
+ topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: true },
+ placed: 2,
+ kept: 0,
+ });
+ await writeXTrendingPosts(dir, [post("103", "lid_watch", "three")]);
+ const second = await recordXTrendingRead(dir, {
+ readId: READ_B,
+ at: "2026-11-17T11:00:00.000Z",
+ ref: REF,
+ postIds: ["103", "101"],
+ added: 1,
+ });
+ assert.deepEqual(second, {
+ topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: false },
+ placed: 1,
+ kept: 1,
+ });
+ const topics = await readXTrendingTopics(dir);
+ assert.equal(topics.length, 1);
+ assert.deepEqual(topics[0].sources, [
+ {
+ trendId: REF.trendId,
+ url: REF.url,
+ reads: [
+ { id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 },
+ { id: READ_B, at: "2026-11-17T11:00:00.000Z", posts: 2, added: 1 },
+ ],
+ },
+ ]);
+ const members = await readXTrendingMembership(dir);
+ assert.deepEqual(Object.keys(members).sort(), ["101", "102", "103"]);
+ assert.deepEqual(members["101"].seen.map((s) => [s.read, s.rank]), [
+ [READ_A, 1],
+ [READ_B, 2],
+ ]);
+ // 102 was not on the page the second time: it stays.
+ assert.deepEqual(members["102"].seen.map((s) => s.read), [READ_A]);
+ // The same read recorded twice changes nothing.
+ await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 0 });
+ assert.equal((await readXTrendingTopics(dir))[0].sources[0].reads.length, 2);
+ assert.equal((await readXTrendingMembership(dir))["101"].seen.length, 2);
+});
+
+test("a named topic is found by id or title, else made; a second page merges into it; a placed post keeps its topic", async () => {
+ const dir = root("named");
+ await writeXTrendingPosts(dir, [post("201", "a", "one"), post("202", "b", "two"), post("203", "c", "three")]);
+ const made = await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ topic: "Kettle Festival",
+ postIds: ["201"],
+ added: 1,
+ });
+ assert.deepEqual(made.topic, { id: "kettle-festival", title: "Kettle Festival", created: true });
+ // Another page, into the same topic by its title in another case.
+ const merged = await recordXTrendingRead(dir, {
+ readId: READ_B,
+ at: "2026-11-17T11:00:00.000Z",
+ ref: REF_2,
+ topic: "kettle festival",
+ postIds: ["202", "201"],
+ added: 1,
+ });
+ assert.deepEqual(merged.topic, { id: "kettle-festival", title: "Kettle Festival", created: false });
+ // A third read into another topic: 201 stays where it was placed.
+ const other = await recordXTrendingRead(dir, {
+ readId: READ_C,
+ at: "2026-11-17T12:00:00.000Z",
+ ref: REF_2,
+ topic: "Saucers",
+ postIds: ["201", "203"],
+ added: 1,
+ });
+ assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1 });
+ const members = await readXTrendingMembership(dir);
+ assert.equal(members["201"].topic, "kettle-festival");
+ assert.equal(members["203"].topic, "saucers");
+ const topics = await readXTrendingTopics(dir);
+ assert.deepEqual(topics.map((t) => [t.id, t.sources.map((s) => s.trendId)]), [
+ ["kettle-festival", [REF.trendId, REF_2.trendId]],
+ ["saucers", [REF_2.trendId]],
+ ]);
+});
+
+test("the listing gives each post's words, author, media, reads and topic — and nothing of the raw capture", async () => {
+ const dir = root("listing");
+ await writeXTrendingPosts(dir, [post("301", "teapot_news", "The kettle festival opens today."), post("302", "saucer_fan", "Second.")]);
+ mkdirSync(trendingReadDir(dir, READ_A), { recursive: true });
+ await recordXTrendingRead(dir, {
+ readId: READ_A,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: REF,
+ topic: "Kettles",
+ postIds: ["301", "302", "999"],
+ added: 2,
+ media: { "301": { count: 2, kinds: ["image"] } },
+ });
+ const all = await listXTrending(dir);
+ assert.deepEqual(all.topics, [
+ {
+ id: "kettles",
+ title: "Kettles",
+ posts: 2,
+ sources: [{ trendId: REF.trendId, url: REF.url, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }],
+ },
+ ]);
+ // 999 is a member with no archived post (a write that never landed): not listed.
+ assert.deepEqual(all.posts, [
+ {
+ id: "301",
+ author: "teapot_news",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/teapot_news/status/301",
+ text: "The kettle festival opens today.",
+ media: { count: 2, kinds: ["image"] },
+ topic: "kettles",
+ reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }],
+ },
+ {
+ id: "302",
+ author: "saucer_fan",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/saucer_fan/status/302",
+ text: "Second.",
+ media: { count: 0, kinds: [] },
+ topic: "kettles",
+ reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }],
+ },
+ ]);
+ assert.equal(all.total, 2);
+ assert.deepEqual(all.reads, [READ_A]);
+ assert.equal((await listXTrending(dir, { limit: 1 })).posts.length, 1);
+ assert.equal((await listXTrending(dir, { limit: 1 })).total, 2);
+ assert.equal((await listXTrending(dir, { topic: "nope" })).posts.length, 0);
+ // The files are plain JSON with a version.
+ assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "topics.json"), "utf8")).version, 1);
+ assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "membership.json"), "utf8")).version, 1);
+});
+
+test("an empty library lists nothing", async () => {
+ assert.deepEqual(await listXTrending(root("empty")), { topics: [], posts: [], total: 0, reads: [] });
+});
+
+test("a row carries its first captured picture and its judgement, once there are any", async () => {
+ const dir = root("captured");
+ await writeXTrendingPosts(dir, [post("401", "a", "one"), post("402", "b", "two"), post("403", "c", "three")]);
+ await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["401", "402", "403"], added: 3 });
+ // 401: a capture with an attached image and a shot; 402: a shot alone; 403: none.
+ // A library's media lives under trending/ (review 2 N9), never in the
+ // channel's own posts-media/, which is planted here to prove it is not read.
+ for (const [id, files] of [["401", ["shot.png", "401_2.jpg", "401_1.jpg", "capture.json", "shot-thread.png"]], ["402", ["shot.png", "capture.json", "402_1.mp4"]]] as const) {
+ mkdirSync(path.join(dir, "trending", "posts-media", id), { recursive: true });
+ for (const f of files) writeFileSync(path.join(dir, "trending", "posts-media", id, f), "x");
+ }
+ mkdirSync(path.join(dir, "posts-media", "403"), { recursive: true });
+ writeFileSync(path.join(dir, "posts-media", "403", "shot.png"), "x");
+ mkdirSync(path.join(dir, "posts-media", "402"), { recursive: true });
+ writeFileSync(path.join(dir, "posts-media", "402", "402_9.jpg"), "x");
+ writeFileSync(
+ path.join(dir, "trending", "judgements.json"),
+ JSON.stringify({
+ version: 1,
+ posts: {
+ "401": { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" },
+ "402": { state: "maybe", by: "agent", at: "2026-11-17T11:00:00.000Z" },
+ "403": { state: "drop", by: "nobody", at: "2026-11-17T11:00:00.000Z" },
+ },
+ }),
+ );
+ const { posts } = await listXTrending(dir);
+ const by = Object.fromEntries(posts.map((p) => [p.id, p]));
+ assert.equal(by["401"].media.thumbnail, "trending/posts-media/401/401_1.jpg");
+ assert.deepEqual(by["401"].judgement, { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" });
+ assert.equal(by["402"].media.thumbnail, "trending/posts-media/402/shot.png");
+ // An ill-shaped judgement is no judgement.
+ assert.equal(by["402"].judgement, undefined);
+ assert.equal(by["403"].media.thumbnail, undefined);
+ assert.equal(by["403"].judgement, undefined);
+});
+
+// Review 2 N9: nothing of the lane reads or writes channels/<lib>/posts-media.
+test("no module of the lane reaches the channel's own posts-media: a library's media is under trending/", async () => {
+ const { readFileSync: read } = await import("node:fs");
+ const repo = path.resolve(import.meta.dirname, "..", "..", "..");
+ const lane = [
+ "common/lib/xTrending/config.ts",
+ "common/lib/xTrending/marker.mjs",
+ "common/lib/xTrending/library-server.ts",
+ "common/lib/xTrending/store.ts",
+ "common/social/xTrendingParse.ts",
+ "common/social/xTrendingRead.ts",
+ "common/controller/readXTrending.ts",
+ "editor/app/channels/[slug]/xTrendingActions.ts",
+ "editor/app/channels/[slug]/components/XTrendingPanel.tsx",
+ "editor/app/api/ops/read-x-trending/route.ts",
+ "editor/app/api/ops/trending/route.ts",
+ "mcp/src/xTrending.ts",
+ ];
+ for (const rel of lane) {
+ const code = read(path.join(repo, rel), "utf8")
+ .split("\n")
+ .filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l))
+ .join("\n");
+ assert.ok(!/postsMediaDir\(|postCaptureDir\(|social\/postCapture"/.test(code), `${rel} uses the posts channel's media layout`);
+ // The only posts-media path the lane builds is the store's, under trending/.
+ const mentions = code.match(/posts-media|POSTS_MEDIA/g) ?? [];
+ if (rel !== "common/lib/xTrending/store.ts") assert.deepEqual(mentions, [], `${rel} names posts-media`);
+ }
+ const { xTrendingPostsMediaDir } = await import("./store");
+ assert.equal(xTrendingPostsMediaDir("/c/lib"), "/c/lib/trending/posts-media");
+});
diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts
@@ -0,0 +1,605 @@
+// AN X TRENDING LIBRARY'S OWN FILES (lane x-trending, slice 1):
+//
+// channels/<lib>/trending/posts/<YYYY-MM>.jsonl its posts (a posts
+// channels/<lib>/trending/posts-archive channel's format, kept
+// HERE: see xTrendingPostsRoot)
+// channels/<lib>/trending/topics.json the operator's topics, each with
+// the trending pages read into it
+// and every read's id and time
+// channels/<lib>/trending/membership.json post id → its topic, the reads
+// that showed it, its media by kind
+// channels/<lib>/trending/reads/<readId>/ one read of one page, raw:
+// responses.jsonl every GraphQL JSON answer the page fetched
+// page.png the page as it stood when it had loaded
+// read.json the read's record: operation NAMES and SIZES only
+//
+// THE RAW CAPTURE IS PRIVATE AND STAYS HERE: it can hold other accounts' data
+// and fields bound to the reading session. No route serves `reads/`, nothing
+// indexes it, and the listing below never returns it. A post is parsed from
+// the saved file only (social/xTrendingParse.ts).
+//
+// THIS MODULE IS THE ONE WRITER of topics.json and membership.json; every
+// write goes through the file's lock (withJsonFileLock) and is atomic. A
+// re-read of a page adds posts and appends a read; it never drops a post, and
+// never moves one out of the topic it is in.
+//
+// The listing reads these files and the posts shards — never the index (the
+// library is in no index build). It is a plain module over the corpus on
+// disk, with no editor-only import, so umtool's Posts library page (slice 3)
+// reads a library exactly as the editor does.
+//
+// channels/<lib>/trending/judgements.json RESERVED for slice 3: post id →
+// {state: "keep" | "drop" | "undecided", note?, by: "agent" |
+// "operator", at}. Written by ONE writer, the editor's `judge-trending`
+// ({slug, by, set: [{id, state, note?, topic?}]}), not built yet; the
+// listing already reads it, so a row carries its judgement once one
+// exists.
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { mkdir, readFile, readdir } from "node:fs/promises";
+import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server";
+import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server";
+import type { Post } from "../posts";
+import type { XTrendingRef } from "./config";
+
+export const TRENDING_DIRNAME = "trending";
+export const TRENDING_READS_DIRNAME = "reads";
+export const TRENDING_RESPONSES_FILENAME = "responses.jsonl";
+export const TRENDING_PAGE_SHOT_FILENAME = "page.png";
+export const TRENDING_READ_FILENAME = "read.json";
+
+export function trendingDir(channelRoot: string): string {
+ return path.join(channelRoot, TRENDING_DIRNAME);
+}
+
+// WHERE A LIBRARY'S POSTS LIVE (review 1): `channels/<lib>/trending/posts/`
+// and `trending/posts-archive` — a posts channel's own shard and archive
+// format, one directory down. NOT `channels/<lib>/posts/`: every reader of a
+// posts channel (reports and drafts, research, umtool's post search and reels,
+// the index, the availability checks) looks there, and a library must be
+// offered to none of them until someone publishes posts out of it on purpose.
+// So to all of those a library is a channel with no posts, by construction;
+// the library's own readers and writers below are the only way in.
+export function xTrendingPostsRoot(channelRoot: string): string {
+ return trendingDir(channelRoot);
+}
+
+export function readXTrendingPosts(channelRoot: string): Promise<Post[]> {
+ return readAllPosts(xTrendingPostsRoot(channelRoot));
+}
+
+export function readXTrendingPostIds(channelRoot: string): Promise<Set<string>> {
+ return readSeenPostIds(xTrendingPostsRoot(channelRoot));
+}
+
+// Month shards, deduped by id against the library's archive, as writePosts does.
+export function writeXTrendingPosts(channelRoot: string, posts: ReadonlyArray<Post>): Promise<WritePostsResult> {
+ return writePosts(xTrendingPostsRoot(channelRoot), posts);
+}
+
+const READ_ID = /^tr-[0-9A-Z]{26}$/;
+
+export function isXTrendingReadId(id: unknown): id is string {
+ return typeof id === "string" && READ_ID.test(id);
+}
+
+// THE CAPTURES ARE NEVER COMMITTED (review 1). The corpus is its own git
+// repo, and a capture holds other people's data and fields bound to the
+// reading session: `trending/reads/.gitignore` ignores everything under it
+// (itself included), written whenever the reads directory is made.
+export const TRENDING_READS_GITIGNORE = "# Raw captures of X pages: private, never committed.\n*\n";
+
+export async function ensureXTrendingReadsDir(channelRoot: string): Promise<string> {
+ const dir = path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME);
+ await mkdir(dir, { recursive: true });
+ const ignore = path.join(dir, ".gitignore");
+ const have = await readFile(ignore, "utf8").catch(() => null);
+ if (have !== TRENDING_READS_GITIGNORE) await writeFileAtomic(ignore, TRENDING_READS_GITIGNORE);
+ return dir;
+}
+
+// One read's directory. The id is checked here, where it becomes a path.
+export function trendingReadDir(channelRoot: string, readId: string): string {
+ if (!isXTrendingReadId(readId)) throw new Error(`"${readId}" is not a trending read id`);
+ return path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME, readId);
+}
+
+function topicsPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "topics.json");
+}
+
+function membershipPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "membership.json");
+}
+
+export type XTrendingMediaKind = "image" | "video" | "gif";
+export type XTrendingMedia = { count: number; kinds: XTrendingMediaKind[] };
+
+function judgementsPath(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), "judgements.json");
+}
+
+export type XTrendingJudgementState = "keep" | "drop" | "undecided";
+export const X_TRENDING_JUDGEMENT_STATES: readonly XTrendingJudgementState[] = ["keep", "drop", "undecided"];
+
+// A post's judgement (slice 3 writes it; this slice only reads it).
+export type XTrendingJudgement = {
+ state: XTrendingJudgementState;
+ note?: string;
+ by: "agent" | "operator";
+ at: string;
+};
+
+// judgements.json, or {} while there is none. Ill-shaped entries are dropped.
+export async function readXTrendingJudgements(channelRoot: string): Promise<Record<string, XTrendingJudgement>> {
+ const read = await readJsonFile(judgementsPath(channelRoot));
+ const posts = read.ok ? (read.value as { posts?: unknown } | null)?.posts : null;
+ if (!posts || typeof posts !== "object" || Array.isArray(posts)) return {};
+ const out: Record<string, XTrendingJudgement> = {};
+ for (const [id, j] of Object.entries(posts as Record<string, Partial<XTrendingJudgement> | null>)) {
+ if (!/^\d+$/.test(id) || !j || typeof j !== "object") continue;
+ if (!X_TRENDING_JUDGEMENT_STATES.includes(j.state as XTrendingJudgementState)) continue;
+ if ((j.by !== "agent" && j.by !== "operator") || typeof j.at !== "string" || !j.at) continue;
+ out[id] = {
+ state: j.state as XTrendingJudgementState,
+ ...(typeof j.note === "string" && j.note ? { note: j.note } : {}),
+ by: j.by,
+ at: j.at,
+ };
+ }
+ return out;
+}
+
+const IMAGE_FILE = /\.(?:jpe?g|png|webp|gif)$/i;
+
+// WHERE A LIBRARY'S CAPTURED MEDIA LIVES (review 2 N9): under trending/, as
+// its posts do — `channels/<lib>/trending/posts-media/<id>/` — never in the
+// channel's own `posts-media/`, which umtool and the report media read for an
+// ordinary posts channel. Slice 2 writes it; this slice only looks.
+const LIBRARY_MEDIA_DIRNAME = "posts-media";
+const LIBRARY_SHOT_FILENAME = "shot.png";
+
+export function xTrendingPostsMediaDir(channelRoot: string): string {
+ return path.join(trendingDir(channelRoot), LIBRARY_MEDIA_DIRNAME);
+}
+
+// A captured post's first picture, as a path relative to the channel
+// (`trending/posts-media/<id>/<name>`): its first attached image, else its
+// screenshot. Undefined while the post has no capture (archiving is slice 2).
+export async function firstCapturedThumbnail(channelRoot: string, id: string): Promise<string | undefined> {
+ if (!/^\d+$/.test(id)) return undefined;
+ let names: string[];
+ try {
+ names = (await readdir(path.join(xTrendingPostsMediaDir(channelRoot), id))).sort();
+ } catch {
+ return undefined;
+ }
+ const media = names.find((n) => IMAGE_FILE.test(n) && !n.startsWith("shot") && !n.startsWith("article"));
+ const pick = media ?? (names.includes(LIBRARY_SHOT_FILENAME) ? LIBRARY_SHOT_FILENAME : undefined);
+ return pick ? `${TRENDING_DIRNAME}/${LIBRARY_MEDIA_DIRNAME}/${id}/${pick}` : undefined;
+}
+
+export type XTrendingSourceRead = {
+ // The read's id (`reads/<id>/`), when it ran, the posts it showed and how
+ // many of them were new to the library.
+ id: string;
+ at: string;
+ posts: number;
+ added: number;
+};
+
+// One trending page read into a topic. `title` and `summary` are X's own
+// words for the page, filled once the parser knows where the page keeps them.
+export type XTrendingSource = {
+ trendId: string;
+ url: string;
+ title?: string;
+ summary?: string;
+ reads: XTrendingSourceRead[];
+};
+
+export type XTrendingTopic = {
+ id: string;
+ // The operator's name for it (X's title is the source's).
+ title: string;
+ createdAt: string;
+ sources: XTrendingSource[];
+};
+
+export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number };
+
+export type XTrendingMember = {
+ topic: string;
+ seen: XTrendingSeen[];
+ media?: XTrendingMedia;
+};
+
+type TopicsFile = { version: 1; topics: XTrendingTopic[] };
+type MembershipFile = { version: 1; posts: Record<string, XTrendingMember> };
+
+const str = (v: unknown): v is string => typeof v === "string" && v !== "";
+
+function parseTopics(raw: unknown): XTrendingTopic[] {
+ const list = (raw as { topics?: unknown } | null)?.topics;
+ if (!Array.isArray(list)) return [];
+ const out: XTrendingTopic[] = [];
+ for (const t of list) {
+ if (!t || typeof t !== "object" || !str(t.id) || !str(t.title)) continue;
+ const sources: XTrendingSource[] = [];
+ for (const s of Array.isArray(t.sources) ? t.sources : []) {
+ if (!s || typeof s !== "object" || !str(s.trendId) || !str(s.url)) continue;
+ const reads: XTrendingSourceRead[] = [];
+ for (const r of Array.isArray(s.reads) ? s.reads : []) {
+ if (!r || typeof r !== "object" || !isXTrendingReadId(r.id) || !str(r.at)) continue;
+ reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0 });
+ }
+ sources.push({
+ trendId: s.trendId,
+ url: s.url,
+ ...(str(s.title) ? { title: s.title } : {}),
+ ...(str(s.summary) ? { summary: s.summary } : {}),
+ reads,
+ });
+ }
+ out.push({ id: t.id, title: t.title, createdAt: str(t.createdAt) ? t.createdAt : "", sources });
+ }
+ return out;
+}
+
+const MEDIA_KINDS: readonly XTrendingMediaKind[] = ["image", "video", "gif"];
+
+function parseMembership(raw: unknown): Record<string, XTrendingMember> {
+ const posts = (raw as { posts?: unknown } | null)?.posts;
+ if (!posts || typeof posts !== "object" || Array.isArray(posts)) return {};
+ const out: Record<string, XTrendingMember> = {};
+ for (const [id, m] of Object.entries(posts as Record<string, Partial<XTrendingMember> | null>)) {
+ if (!/^\d+$/.test(id) || !m || typeof m !== "object" || !str(m.topic)) continue;
+ const seen: XTrendingSeen[] = [];
+ for (const s of Array.isArray(m.seen) ? m.seen : []) {
+ if (!s || typeof s !== "object" || !isXTrendingReadId(s.read) || !str(s.trendId) || !str(s.at)) continue;
+ seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0 });
+ }
+ const media =
+ m.media && typeof m.media === "object" && Number(m.media.count) > 0
+ ? {
+ count: Number(m.media.count),
+ kinds: (Array.isArray(m.media.kinds) ? m.media.kinds : []).filter((k): k is XTrendingMediaKind =>
+ MEDIA_KINDS.includes(k as XTrendingMediaKind),
+ ),
+ }
+ : undefined;
+ out[id] = { topic: m.topic, seen, ...(media ? { media } : {}) };
+ }
+ return out;
+}
+
+export async function readXTrendingTopics(channelRoot: string): Promise<XTrendingTopic[]> {
+ const read = await readJsonFile(topicsPath(channelRoot));
+ return read.ok ? parseTopics(read.value) : [];
+}
+
+export async function readXTrendingMembership(channelRoot: string): Promise<Record<string, XTrendingMember>> {
+ const read = await readJsonFile(membershipPath(channelRoot));
+ return read.ok ? parseMembership(read.value) : {};
+}
+
+// A topic id from a title: lower-case words joined by "-", at most 48
+// characters; "" when the title has no letter or digit.
+export function topicIdFromTitle(title: string): string {
+ return title
+ .normalize("NFKD")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 48)
+ .replace(/-+$/, "");
+}
+
+export const X_TRENDING_TOPIC_TITLE_MAX = 120;
+
+// Why this cannot be a topic's name, or null.
+export function topicTitleProblem(title: unknown): string | null {
+ if (typeof title !== "string" || !title.trim()) return `"topic" is a topic's id or a name for a new one`;
+ if (title.trim().length > X_TRENDING_TOPIC_TITLE_MAX) {
+ return `A topic's name is at most ${X_TRENDING_TOPIC_TITLE_MAX} characters`;
+ }
+ return null;
+}
+
+export type RecordReadInput = {
+ readId: string;
+ at: string;
+ ref: XTrendingRef;
+ // The topic asked for: an existing topic's id or title, or a new one's
+ // title. Absent: the topic this page was read into before, else a new one
+ // named for the page.
+ topic?: string;
+ // The page's posts, first shown first.
+ postIds: ReadonlyArray<string>;
+ // How many of them the library did not hold before this read.
+ added: number;
+ media?: Readonly<Record<string, XTrendingMedia>>;
+};
+
+export type RecordReadResult = {
+ topic: { id: string; title: string; created: boolean };
+ // Posts this read placed in the topic (new to the library's membership).
+ placed: number;
+ // Posts the library already had, left in the topic they were in.
+ kept: number;
+};
+
+// One read, recorded: its topic found or made, the page added to the topic's
+// sources, the read appended, and every post it showed given a place (a post
+// already placed keeps its topic and gains the read).
+export async function recordXTrendingRead(channelRoot: string, input: RecordReadInput): Promise<RecordReadResult> {
+ if (!isXTrendingReadId(input.readId)) throw new Error(`"${input.readId}" is not a trending read id`);
+ const topic = await withJsonFileLock(topicsPath(channelRoot), async () => {
+ const topics = await readXTrendingTopics(channelRoot);
+ const asked = input.topic?.trim();
+ let found: XTrendingTopic | undefined;
+ if (asked) {
+ found =
+ topics.find((t) => t.id === asked) ??
+ topics.find((t) => t.title.toLowerCase() === asked.toLowerCase());
+ } else {
+ found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId));
+ }
+ let created = false;
+ if (!found) {
+ const title = asked || `Trending ${input.ref.trendId}`;
+ const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`;
+ let id = base;
+ for (let n = 2; topics.some((t) => t.id === id); n++) id = `${base}-${n}`;
+ found = { id, title, createdAt: input.at, sources: [] };
+ topics.push(found);
+ created = true;
+ }
+ let source = found.sources.find((s) => s.trendId === input.ref.trendId);
+ if (!source) {
+ source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] };
+ found.sources.push(source);
+ }
+ const read = source.reads.find((r) => r.id === input.readId);
+ if (!read) {
+ source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added });
+ } else {
+ // The same read recorded again (a reparse): what the capture is now
+ // read to hold, and whatever this pass added on top of the last.
+ read.posts = input.postIds.length;
+ read.added += input.added;
+ }
+ await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true });
+ return { id: found.id, title: found.title, created };
+ });
+ const counts = await withJsonFileLock(membershipPath(channelRoot), async () => {
+ const posts = await readXTrendingMembership(channelRoot);
+ let placed = 0;
+ let kept = 0;
+ input.postIds.forEach((id, i) => {
+ const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1 };
+ const have = posts[id];
+ if (have) {
+ kept++;
+ if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen);
+ if (!have.media && input.media?.[id]) have.media = input.media[id];
+ } else {
+ placed++;
+ posts[id] = { topic: topic.id, seen: [seen], ...(input.media?.[id] ? { media: input.media[id] } : {}) };
+ }
+ });
+ await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true });
+ return { placed, kept };
+ });
+ 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 | forbidden | gone | error
+// the read failed, said in `sentence` ("error" is also
+// what a read that never finished is left as)
+export type XTrendingReadOutcome =
+ | "read"
+ | "probe"
+ | "nothing-recognised"
+ | "login-wall"
+ | "rate-limit"
+ | "forbidden"
+ | "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;
+ // The operation and HTTP status of the first answer that stopped it (a
+ // 429, a 403 or a 401), when one did.
+ stoppedBy?: { op: string; status: number };
+ 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 ensureXTrendingReadsDir(channelRoot);
+ 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 = {
+ id: string;
+ title: string;
+ posts: number;
+ sources: Array<{
+ trendId: string;
+ url: string;
+ title?: string;
+ summary?: string;
+ reads: number;
+ lastReadAt: string | null;
+ }>;
+};
+
+// One post of the library, as the listing gives it — everything a list view
+// needs: what it says, who said it and when, what media it carries (and the
+// first picture's path once the post is captured), which reads showed it, its
+// topic, and its judgement once it has one. Never the raw capture.
+export type XTrendingPostRow = {
+ id: string;
+ author: string;
+ authorName?: string;
+ createdAt: string;
+ url: string;
+ text: string;
+ media: XTrendingMedia & { thumbnail?: string };
+ topic: string;
+ reads: Array<{ read: string; trendId: string; at: string }>;
+ judgement?: XTrendingJudgement;
+};
+
+export type XTrendingListing = {
+ topics: XTrendingTopicRow[];
+ posts: XTrendingPostRow[];
+ // Posts matching the ask, before `limit`.
+ total: number;
+ // Reads on disk (probes included), newest first.
+ reads: string[];
+};
+
+export const X_TRENDING_LIST_DEFAULT = 100;
+export const X_TRENDING_LIST_MAX = 500;
+
+export async function listXTrendingReadIds(channelRoot: string): Promise<string[]> {
+ try {
+ const names = await readdir(path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME));
+ return names.filter(isXTrendingReadId).sort().reverse();
+ } catch {
+ return [];
+ }
+}
+
+const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.at : a), "");
+
+// The library's topics and posts. `topic` narrows the posts to one topic (its
+// id); `limit` caps them (the newest read's first, in page order).
+export async function listXTrending(
+ channelRoot: string,
+ opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post> } = {},
+): Promise<XTrendingListing> {
+ const [topics, membership, reads, judgements] = await Promise.all([
+ readXTrendingTopics(channelRoot),
+ readXTrendingMembership(channelRoot),
+ listXTrendingReadIds(channelRoot),
+ readXTrendingJudgements(channelRoot),
+ ]);
+ const archived = new Map((opts.posts ?? (await readXTrendingPosts(channelRoot))).map((p) => [p.id, p]));
+ const count = new Map<string, number>();
+ for (const [id, m] of Object.entries(membership)) {
+ if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1);
+ }
+ const rows: XTrendingPostRow[] = [];
+ for (const [id, m] of Object.entries(membership)) {
+ if (opts.topic && m.topic !== opts.topic) continue;
+ const post = archived.get(id);
+ if (!post) continue;
+ rows.push({
+ id,
+ author: post.author,
+ ...(post.authorName ? { authorName: post.authorName } : {}),
+ createdAt: post.createdAt,
+ url: post.url,
+ text: post.text,
+ media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] },
+ topic: m.topic,
+ reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })),
+ ...(judgements[id] ? { judgement: judgements[id] } : {}),
+ });
+ }
+ const rank = (id: string) => {
+ const m = membership[id];
+ const at = lastSeen(m);
+ return m.seen.find((s) => s.at === at)?.rank ?? 0;
+ };
+ rows.sort((a, b) => {
+ const [la, lb] = [lastSeen(membership[a.id]), lastSeen(membership[b.id])];
+ if (la !== lb) return la < lb ? 1 : -1;
+ return rank(a.id) - rank(b.id) || (a.id < b.id ? -1 : 1);
+ });
+ const limit = Math.min(Math.max(1, opts.limit ?? X_TRENDING_LIST_DEFAULT), X_TRENDING_LIST_MAX);
+ return {
+ topics: topics.map((t) => ({
+ id: t.id,
+ title: t.title,
+ posts: count.get(t.id) ?? 0,
+ sources: t.sources.map((s) => ({
+ trendId: s.trendId,
+ url: s.url,
+ ...(s.title ? { title: s.title } : {}),
+ ...(s.summary ? { summary: s.summary } : {}),
+ reads: s.reads.length,
+ lastReadAt: s.reads.reduce<string | null>((a, r) => (a === null || r.at > a ? r.at : a), null),
+ })),
+ })),
+ // The thumbnail is looked up for the rows returned only (one readdir each).
+ posts: await Promise.all(
+ rows.slice(0, limit).map(async (row) => {
+ const thumbnail = await firstCapturedThumbnail(channelRoot, row.id);
+ return thumbnail ? { ...row, media: { ...row.media, thumbnail } } : row;
+ }),
+ ),
+ total: rows.length,
+ reads,
+ };
+}
diff --git a/common/package.json b/common/package.json
@@ -40,6 +40,7 @@
"./lib/clips/segments.mjs": "./lib/clips/segments.mjs",
"./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs",
"./lib/atomicFile.mjs": "./lib/atomicFile.mjs",
+ "./lib/xTrending/marker.mjs": "./lib/xTrending/marker.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/platformSeek.mjs": "./lib/platformSeek.mjs",
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -80,6 +80,7 @@ import { type Site } from "../lib/site";
import { storeReportDir } from "../lib/report/store";
import { getSettings } from "../lib/settings";
import { postsVisibleTo } from "../lib/postsVisibility";
+import { isXTrendingChannel, X_TRENDING_NOT_CITABLE } from "../lib/xTrending/config";
import { assertChannelTextReadable } from "../lib/channelMedia";
import type { ChannelConfig } from "../lib/channelConfig";
import { readChannelConfig } from "../controller/channels";
@@ -631,6 +632,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
continue;
}
if (c.kind === "post") {
+ // Never a post of an X trending library (lane x-trending): private,
+ // whatever the host and the visibility rule would allow.
+ if (isXTrendingChannel(await configOf(c.channel))) {
+ problems.push({ kind: "not-visible", citation: ref, report: report.id, message: X_TRENDING_NOT_CITABLE(c.channel) });
+ refusedChannel.add(c.channel);
+ continue;
+ }
if (!postsVisibleTo(host, await configOf(c.channel), settings)) {
problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} may not carry posts of "${c.channel}" (the post visibility rule)` });
continue;
diff --git a/common/publish/reportHost.ts b/common/publish/reportHost.ts
@@ -24,6 +24,8 @@
// articles' corpus check (a channel directory exists).
import { existsSync, statSync } from "node:fs";
+import { X_TRENDING_NOT_CITABLE } from "../lib/xTrending/config";
+import { isXTrendingLibrarySync } from "../lib/xTrending/library-server";
import path from "node:path";
import type { Paths } from "../lib/paths";
import { PROJECT_NAME, PROJECT_URL } from "../lib/project";
@@ -69,8 +71,18 @@ export type ReportHost = ReportStore & {
};
// A site's pages.
-export function siteReportHost(paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir">, site: Site): ReportHost {
+export function siteReportHost(
+ paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir"> & Partial<Pick<Paths, "channelsDir">>,
+ site: Site,
+): ReportHost {
const citable = siteCitableChannelSlugs(site);
+ // An X trending library is never citable (lane x-trending): the site writer
+ // refuses one as a member, and a site.json written by hand is caught here.
+ const library = new Map<string, boolean>();
+ const isLibrary = (slug: string) => {
+ if (!library.has(slug)) library.set(slug, isXTrendingLibrarySync(paths.channelsDir, slug));
+ return library.get(slug) === true;
+ };
const cited = isCitedSite(site);
return {
...siteReportStore(paths, site.siteId),
@@ -81,7 +93,8 @@ export function siteReportHost(paths: Pick<Paths, "sitesDir" | "exportSitesIndex
audience: isPrivateSite(site) ? "private" : "public",
published: site.pages ?? [],
listedBy: (id) => `the site lists report "${id}"`,
- citableProblem: (slug) => (citable.has(slug) ? null : notInSiteMessage(slug)),
+ citableProblem: (slug) =>
+ isLibrary(slug) ? X_TRENDING_NOT_CITABLE(slug) : citable.has(slug) ? null : notInSiteMessage(slug),
// No corpus page to link a moment to: a cited site publishes none, and a
// cited-only channel (`citedChannels`) is not in the site's corpus.
corpusBase: (slug) => (cited || isCitedOnlyChannel(site, slug) ? null : ""),
@@ -115,6 +128,7 @@ export async function articlesReportHost(
): Promise<ReportHost> {
const audience = opts.audience ?? "private";
const isChannel = new Map<string, boolean>();
+ const library = new Map<string, boolean>();
return {
...articleReportStore(paths),
base: ARTICLES_REPORTS_BASE,
@@ -124,6 +138,10 @@ export async function articlesReportHost(
published: opts.published ?? (await publishedArticleIds(audience, paths)),
listedBy: (id) => `reports/index.json lists article "${id}"`,
citableProblem: (slug) => {
+ // The whole corpus is citable — but never an X trending library, which
+ // is private (lane x-trending).
+ if (!library.has(slug)) library.set(slug, isXTrendingLibrarySync(paths.channelsDir, slug));
+ if (library.get(slug)) return X_TRENDING_NOT_CITABLE(slug);
if (!isChannel.has(slug)) {
let dir = false;
try {
diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts
@@ -59,6 +59,7 @@ import {
} from "../lib/report/store";
import { siteReportHost, type ReportHost } from "./reportHost";
import { postsVisibleTo } from "../lib/postsVisibility";
+import { isXTrendingChannel, X_TRENDING_NOT_CITABLE } from "../lib/xTrending/config";
import { inspectChannelMedia } from "../lib/channelMedia";
import type { ChannelConfig } from "../lib/channelConfig";
import { readChannelConfig } from "../controller/channels";
@@ -321,6 +322,10 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
}
const config = await configOf(slug);
if (m.kind === "post") {
+ if (isXTrendingChannel(config)) {
+ fail(m, "not-visible", X_TRENDING_NOT_CITABLE(slug));
+ continue;
+ }
if (!postsVisibleTo(host, config, settings)) {
fail(m, "not-visible", `this site may not carry posts of "${slug}" (the post visibility rule)`);
continue;
@@ -569,6 +574,10 @@ export async function missingEvidenceWindows(
continue;
}
const config = await configOf(slug);
+ if (isXTrendingChannel(config)) {
+ unfetchable("not-in-site", X_TRENDING_NOT_CITABLE(slug));
+ continue;
+ }
const localRefusal = localMediaFetchRefusal(slug, config, id);
if (localRefusal) {
unfetchable("local-media", localRefusal);
diff --git a/common/publish/xTrendingReportDoor.test.ts b/common/publish/xTrendingReportDoor.test.ts
@@ -0,0 +1,240 @@
+// THE REPORT DOOR IS SHUT ON AN X TRENDING LIBRARY (lane x-trending, review 1
+// MUST 1). An article may cite any channel of the corpus, and a draft resolves
+// an X URL to whichever channel holds the post — so, before this, a library's
+// post could be composed into the homepage's public dir, even unasked.
+//
+// Pinned here over a temp corpus, with a marker in the library's post, and the
+// post ALSO planted where an ordinary posts channel keeps its posts (so the
+// refusals are tested, not only the fact that a library keeps its posts under
+// trending/, where no ordinary reader looks):
+// - both report hosts refuse a library as citable;
+// - composing an article that cites a library post is refused, and nothing
+// of the post is written;
+// - no site may carry a library's posts by the visibility rule, private
+// sites included;
+// - a draft's X URL never resolves to a library;
+// - a research run is never shown a library.
+//
+// Run with: node_modules/.bin/tsx --test publish/xTrendingReportDoor.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";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-report-door-"));
+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"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { writePosts, readAllPosts } = await import("../lib/posts-server");
+const { setPublished, articleDir } = await import("../lib/report/registry");
+const { articlesReportHost, siteReportHost } = await import("./reportHost");
+const { composeHostReports, ComposeReportsError } = await import("./composeReports");
+const { postsVisibleTo } = await import("../lib/postsVisibility");
+const { diskPostChannelOf, diskPostOf } = await import("../lib/report/convert-server");
+const { editorChannelsOf } = await import("../controller/reportDraft");
+const { writeXTrendingPosts, readXTrendingPosts } = await import("../lib/xTrending/store");
+const { X_TRENDING_NOT_CITABLE } = await import("../lib/xTrending/config");
+
+const paths = getPaths();
+const OUT = path.join(ROOT, "homepage-public");
+const LIB = "trending-lib";
+const ACCOUNT = "kettle-org-x";
+const LIB_ID = "1900000000000006001";
+const SHARED_ID = "1900000000000006002";
+const MARK = "trenddoormarkerq7x";
+const HANDLE = "trenddoorhandlez4k";
+
+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: [],
+});
+
+const LIBRARY_CONFIG = { handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} };
+writeJson(paths.settingsFile, {});
+const libRoot = path.join(paths.channelsDir, LIB);
+writeJson(path.join(libRoot, "config.json"), LIBRARY_CONFIG);
+const libPosts = [post(LIB, LIB_ID, HANDLE, `a trending post ${MARK}`), post(LIB, SHARED_ID, "kettle_org", `shared ${MARK}`)];
+await writeXTrendingPosts(libRoot, libPosts);
+// And where an ordinary posts channel keeps them (a hand copy; an older library).
+await writePosts(libRoot, libPosts);
+const accountRoot = path.join(paths.channelsDir, ACCOUNT);
+writeJson(path.join(accountRoot, "config.json"), {
+ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Kettle Org (X)", url: "https://x.com/kettle_org", socialHandle: "kettle_org",
+});
+await writePosts(accountRoot, [post(ACCOUNT, SHARED_ID, "kettle_org", "the account's own copy")]);
+
+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 out.push({ rel: path.relative(dir, p), text: readFileSync(p).toString("latin1") });
+ }
+ };
+ if (existsSync(dir)) walk(dir);
+ return out;
+}
+
+test("a library keeps its posts under trending/: where a posts channel's readers look, it has none of its own making", async () => {
+ const fresh = path.join(paths.channelsDir, "fresh-lib");
+ writeJson(path.join(fresh, "config.json"), LIBRARY_CONFIG);
+ await writeXTrendingPosts(fresh, [post("fresh-lib", "1900000000000006009", HANDLE, MARK)]);
+ assert.equal((await readXTrendingPosts(fresh)).length, 1);
+ assert.equal((await readAllPosts(fresh)).length, 0);
+ assert.equal(existsSync(path.join(fresh, "posts")), false);
+ assert.equal(existsSync(path.join(fresh, "posts-archive")), false);
+ assert.equal(existsSync(path.join(fresh, "trending", "posts")), true);
+ rmSync(fresh, { recursive: true, force: true });
+});
+
+test("both report hosts refuse a library as citable", async () => {
+ const articles = await articlesReportHost(paths, { audience: "private" });
+ assert.equal(articles.citableProblem(LIB), X_TRENDING_NOT_CITABLE(LIB));
+ assert.equal(articles.citableProblem(ACCOUNT), null);
+ // A site whose site.json, written by hand, names the library.
+ const site = {
+ siteId: "priv", siteTitle: "priv", audience: "private", pages: [],
+ groups: [{ id: "default", name: "All", selectedByDefault: true }], defaultGroupId: "default",
+ channels: [{ slug: ACCOUNT, groupId: "default" }, { slug: LIB, groupId: "default" }],
+ };
+ const host = siteReportHost(paths, site as never);
+ assert.equal(host.citableProblem(LIB), X_TRENDING_NOT_CITABLE(LIB));
+ assert.equal(host.citableProblem(ACCOUNT), null);
+ assert.match(X_TRENDING_NOT_CITABLE(LIB), /is an X trending library: it is private/);
+});
+
+test("no site may carry a library's posts, a private one included, whatever social.x.visibility says", () => {
+ const priv = { audience: "private" as const };
+ assert.equal(postsVisibleTo(priv, LIBRARY_CONFIG as never, {}), false);
+ assert.equal(postsVisibleTo(priv, LIBRARY_CONFIG as never, { social: { x: { visibility: "public" } } }), false);
+ // The marker alone decides: a library whose kind was edited by hand is still one.
+ assert.equal(postsVisibleTo(priv, { ...LIBRARY_CONFIG, sourceKind: "video" } as never, {}), false);
+ assert.equal(postsVisibleTo(priv, { sourceKind: "social", platform: "twitter" } as never, {}), true);
+});
+
+test("composing an article that cites a library post is refused, and nothing of the post is published", async () => {
+ writeJson(path.join(articleDir(paths, "art-lib"), "report.json"), {
+ format: "archilyzer-report",
+ version: 1,
+ id: "art-lib",
+ kind: "sweep",
+ title: "Article citing a library",
+ sections: [{ id: "s1", title: "What was said", body: "It was said: [p01](cite:p01)." }],
+ citations: { p01: { kind: "post", channel: LIB, id: LIB_ID, quote: "a trending post" } },
+ });
+ await setPublished("art-lib", true, {}, paths);
+ for (const audience of ["private", "public"] as const) {
+ const host = await articlesReportHost(paths, { audience, published: ["art-lib"] });
+ await assert.rejects(composeHostReports({ paths, host, publicDir: OUT, settings: {}, log: () => {} }), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError, String(e));
+ assert.deepEqual(
+ e.problems.map((p) => [p.kind, p.citation, p.message]),
+ [["not-in-site", "art-lib#p01", X_TRENDING_NOT_CITABLE(LIB)]],
+ );
+ return true;
+ });
+ }
+ for (const dir of [OUT, paths.exportPublicDir]) {
+ for (const f of filesUnder(dir)) {
+ assert.ok(!f.text.includes(MARK) && !f.text.includes(HANDLE), `${f.rel} holds the library's post`);
+ }
+ }
+});
+
+test("a draft's X URL never resolves to a library, and a library's post is not read as a record", async () => {
+ const channelOf = diskPostChannelOf(paths.channelsDir);
+ // Only the library holds it: unresolved.
+ assert.equal(await channelOf({ platform: "x", id: LIB_ID, handle: HANDLE }), null);
+ // The library and an account channel hold it: the account's, never the library's.
+ assert.equal(await channelOf({ platform: "x", id: SHARED_ID, handle: "kettle_org" }), ACCOUNT);
+ assert.equal(await channelOf({ platform: "x", id: SHARED_ID, handle: "trending" }), ACCOUNT);
+ const postOf = diskPostOf(paths.channelsDir);
+ assert.equal(await postOf(LIB, LIB_ID), null);
+ assert.ok(await postOf(ACCOUNT, SHARED_ID));
+});
+
+test("a research run is never shown a library among the editor's channels", async () => {
+ const channels = await editorChannelsOf(paths);
+ assert.deepEqual(channels.map((c) => c.slug), [ACCOUNT]);
+});
+
+// --- review 2 N8a: the refusals BEHIND the host's ---------------------------
+//
+// A host that lets the library through (a stub: the real hosts refuse it
+// first) reaches the second line in composeReports and the two in
+// reportMedia. Each must refuse by the library's own sentence.
+
+const { prepareReportMedia, missingEvidenceWindows } = await import("./reportMedia");
+
+async function lenientHost(published: string[]) {
+ const host = await articlesReportHost(paths, { audience: "private", published });
+ return { ...host, citableProblem: () => null };
+}
+
+test("N8a: behind a host that lets it through, compose still refuses a library's post by name", async () => {
+ const host = await lenientHost(["art-lib"]);
+ await assert.rejects(composeHostReports({ paths, host, publicDir: OUT, settings: {}, log: () => {} }), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError, String(e));
+ assert.deepEqual(
+ e.problems.map((p) => [p.kind, p.citation, p.message]),
+ [["not-visible", "art-lib#p01", X_TRENDING_NOT_CITABLE(LIB)]],
+ );
+ return true;
+ });
+ for (const f of filesUnder(OUT)) assert.ok(!f.text.includes(MARK) && !f.text.includes(HANDLE), `${f.rel} holds the library's post`);
+});
+
+test("N8a: behind such a host, preparing media refuses a library's post, and no window of a library is planned", async () => {
+ const host = await lenientHost(["art-lib"]);
+ const index = await prepareReportMedia({ paths, host, settings: {} });
+ assert.deepEqual(
+ index.problems.map((p) => [p.kind, p.moment, p.message]),
+ [["not-visible", `${LIB}/${LIB_ID}`, X_TRENDING_NOT_CITABLE(LIB)]],
+ );
+ assert.deepEqual(Object.keys(index.moments), []);
+
+ // A span cited on a library (a config edited by hand could carry videos).
+ writeJson(path.join(articleDir(paths, "art-lib-span"), "report.json"), {
+ format: "archilyzer-report",
+ version: 1,
+ id: "art-lib-span",
+ kind: "sweep",
+ title: "Article citing a span of a library",
+ sections: [{ id: "s1", title: "What was said", body: "It was said: [c01](cite:c01)." }],
+ citations: { c01: { kind: "video", channel: LIB, id: "vid00000001", start: 10, end: 20, quote: "said on a recording" } },
+ });
+ await setPublished("art-lib-span", true, {}, paths);
+ const windows = await missingEvidenceWindows(paths, await lenientHost(["art-lib-span"]), { settings: {} as never });
+ assert.deepEqual(windows.missing, []);
+ assert.deepEqual(
+ windows.unfetchable.map((w) => [w.slug, w.id, w.why, w.message]),
+ [[LIB, "vid00000001", "not-in-site", X_TRENDING_NOT_CITABLE(LIB)]],
+ );
+});
diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts
@@ -0,0 +1,129 @@
+// AN INVENTED TRENDING-PAGE CAPTURE, for tests and the editor's e2e fake
+// browser (fakeXProfileBrowser.ts). Every id, handle, name and word here is
+// made up; the SHAPES are X's public GraphQL tweet-result shapes as this repo
+// already reads them (xPlaywrightFetcher.ts): `{__typename: "Tweet", rest_id,
+// core.user_results.result, legacy}`, a TweetWithVisibilityResults wrapper, a
+// quoted result, a promoted entry. The operation names are invented too — the
+// real ones are learned from the first real read (the probe).
+
+export const FIXTURE_TREND_ID = "1900000000000000001";
+export const FIXTURE_TREND_URL = `https://x.com/i/trending/${FIXTURE_TREND_ID}`;
+export const FIXTURE_TREND_OP = "ExampleTrendPage";
+export const FIXTURE_TIMELINE_OP = "ExampleTrendTimeline";
+
+export type FixtureTweet = {
+ id: string;
+ handle: string;
+ name?: string;
+ text: string;
+ // "Wed Oct 10 20:19:24 +0000 2018", X's legacy form.
+ createdAt?: string;
+ media?: Array<"photo" | "video" | "animated_gif">;
+ quoted?: FixtureTweet;
+ replyTo?: { id: string; handle: string };
+ // Names under user.core (newer answers) instead of user.legacy.
+ namesInCore?: boolean;
+ // Wrapped in a TweetWithVisibilityResults, the inner tweet untagged.
+ wrapped?: boolean;
+ promoted?: boolean;
+};
+
+export function fixtureTweetResult(t: FixtureTweet): Record<string, unknown> {
+ const names = { screen_name: t.handle, name: t.name ?? t.handle };
+ const tweet: Record<string, unknown> = {
+ rest_id: t.id,
+ core: { user_results: { result: { __typename: "User", rest_id: `9${t.id.slice(-6)}`, ...(t.namesInCore ? { core: names, legacy: {} } : { legacy: names }) } } },
+ legacy: {
+ id_str: t.id,
+ conversation_id_str: t.replyTo?.id ?? t.id,
+ created_at: t.createdAt ?? "Mon Nov 16 12:00:00 +0000 2026",
+ full_text: t.text,
+ lang: "en",
+ favorite_count: 12,
+ retweet_count: 3,
+ reply_count: 1,
+ quote_count: 0,
+ entities: { urls: [] },
+ ...(t.media?.length
+ ? {
+ extended_entities: {
+ media: t.media.map((type, i) => ({
+ type,
+ media_key: `3_${t.id}${i}`,
+ media_url_https: `https://pbs.twimg.com/media/Fixture${t.id.slice(-4)}${i}.jpg`,
+ })),
+ },
+ }
+ : {}),
+ ...(t.quoted ? { quoted_status_id_str: t.quoted.id, is_quote_status: true } : {}),
+ ...(t.replyTo ? { in_reply_to_status_id_str: t.replyTo.id, in_reply_to_screen_name: t.replyTo.handle } : {}),
+ },
+ ...(t.quoted ? { quoted_status_result: { result: fixtureTweetResult(t.quoted) } } : {}),
+ };
+ return t.wrapped ? { __typename: "TweetWithVisibilityResults", tweet } : { __typename: "Tweet", ...tweet };
+}
+
+function entry(t: FixtureTweet): Record<string, unknown> {
+ return {
+ entryId: `tweet-${t.id}`,
+ content: {
+ entryType: "TimelineTimelineItem",
+ itemContent: {
+ itemType: "TimelineTweet",
+ tweet_results: { result: fixtureTweetResult(t) },
+ ...(t.promoted ? { promotedMetadata: { advertiser_results: {} } } : {}),
+ },
+ },
+ };
+}
+
+// One timeline answer holding these posts.
+export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unknown> {
+ return {
+ data: {
+ timeline: {
+ instructions: [
+ { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", value: "fixture-cursor" } }] },
+ ],
+ },
+ },
+ };
+}
+
+export const FIXTURE_FIRST_PAGE: FixtureTweet[] = [
+ { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] },
+ {
+ id: "1900000000000001002",
+ handle: "saucer_fan",
+ text: "Quoting the festival post.",
+ wrapped: true,
+ quoted: { id: "1900000000000000900", handle: "kettle_org", text: "Festival programme attached.", media: ["photo"] },
+ },
+ { id: "1900000000000001003", handle: "advert_co", text: "Buy our kettles.", promoted: true },
+ { id: "1900000000000001004", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true },
+];
+
+export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [
+ { id: "1900000000000001004", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true },
+ { id: "1900000000000001005", handle: "lid_watch", text: "A reply about the queue.", replyTo: { id: "1900000000000001001", handle: "teapot_news" }, media: ["animated_gif"] },
+];
+
+const graphqlUrl = (op: string, n: number) =>
+ `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=%7B%22rest_id%22%3A%22${FIXTURE_TREND_ID}%22%7D`;
+
+export type FixtureResponse = { url: string; status: number; body?: unknown; text?: string };
+
+// What the page fetches on load, and after each scroll to the bottom.
+export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: FixtureResponse[][] } {
+ return {
+ load: [
+ { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: { data: { example_trend: { rest_id: FIXTURE_TREND_ID } } } },
+ { url: graphqlUrl(FIXTURE_TIMELINE_OP, 2), status: 200, body: fixtureTimelineBody(FIXTURE_FIRST_PAGE) },
+ // Not GraphQL: never saved.
+ { url: "https://x.com/i/api/1.1/example.json", status: 200, body: { ok: true } },
+ // Another surface's posts: saved, never read as the page's.
+ { url: graphqlUrl("HomeTimeline", 3), status: 200, body: fixtureTimelineBody([{ id: "1900000000000007777", handle: "home_only", text: "Not on the trending page." }]) },
+ ],
+ scrolls: [[{ url: graphqlUrl(FIXTURE_TIMELINE_OP, 4), status: 200, body: fixtureTimelineBody(FIXTURE_SECOND_PAGE) }], [], []],
+ };
+}
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/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts
@@ -0,0 +1,116 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ collectTimelineTweets,
+ graphqlOpOf,
+ mediaSummaryOf,
+ parseTrendingCapture,
+ type TrendingCaptureLine,
+} from "./xTrendingParse";
+import {
+ FIXTURE_FIRST_PAGE,
+ FIXTURE_TIMELINE_OP,
+ FIXTURE_TREND_OP,
+ fixtureTimelineBody,
+ fixtureTrendingResponses,
+} from "./__fixtures__/xTrendingCapture";
+
+function linesOf(responses: Array<{ url: string; status: number; body?: unknown }>): TrendingCaptureLine[] {
+ return responses
+ .filter((r) => graphqlOpOf(r.url))
+ .map((r, i) => ({
+ n: i + 1,
+ at: "2026-11-17T10:00:00.000Z",
+ op: graphqlOpOf(r.url)!,
+ status: r.status,
+ url: r.url,
+ bytes: JSON.stringify(r.body ?? null).length,
+ body: r.body,
+ }));
+}
+
+test("an operation is named by the GraphQL URL's path; nothing else is one", () => {
+ assert.equal(graphqlOpOf("https://x.com/i/api/graphql/abc123/ExampleTrendTimeline?variables=%7B%7D"), "ExampleTrendTimeline");
+ assert.equal(graphqlOpOf("https://api.x.com/i/api/graphql/abc/Op"), "Op");
+ assert.equal(graphqlOpOf("https://x.com/i/api/1.1/example.json"), null);
+ assert.equal(graphqlOpOf("https://x.com.example.test/i/api/graphql/abc/Op"), null);
+ assert.equal(graphqlOpOf("https://example.test/i/api/graphql/abc/Op"), null);
+});
+
+test("the walk lists the page's posts once each, in order: no promoted entry, no quoted post", () => {
+ const tweets = collectTimelineTweets(fixtureTimelineBody(FIXTURE_FIRST_PAGE));
+ assert.deepEqual(
+ tweets.map((t) => t.rest_id),
+ ["1900000000000001001", "1900000000000001002", "1900000000000001004"],
+ );
+ // The quoted post rides on the post quoting it.
+ assert.equal((tweets[1].quoted as { rest_id: string }).rest_id, "1900000000000000900");
+ // Names under user.core are read as names under user.legacy are.
+ assert.deepEqual(tweets[2].user, { name: "spout_clips", nick: "Spout Clips" });
+});
+
+test("media is counted by kind from the answer", () => {
+ const [first, , video] = collectTimelineTweets(fixtureTimelineBody(FIXTURE_FIRST_PAGE));
+ assert.deepEqual(mediaSummaryOf(first), { count: 2, kinds: ["image"] });
+ assert.deepEqual(mediaSummaryOf(video), { count: 1, kinds: ["video"] });
+ assert.equal(mediaSummaryOf({ full_text: "no media" }), undefined);
+ // A type that is a property of every object is no kind.
+ assert.deepEqual(
+ mediaSummaryOf({ extended_entities: { media: [{ type: "constructor" }, { type: "toString" }, { type: "photo" }] } }),
+ { count: 3, kinds: ["image"] },
+ );
+});
+
+test("a capture parses to posts, their media and the operations' names and sizes", () => {
+ const f = fixtureTrendingResponses();
+ const parsed = parseTrendingCapture(linesOf([...f.load, ...f.scrolls.flat()]), "trending");
+ assert.deepEqual(
+ parsed.posts.map((p) => [p.id, p.author, p.channelSlug]),
+ [
+ ["1900000000000001001", "teapot_news", "trending"],
+ ["1900000000000001002", "saucer_fan", "trending"],
+ ["1900000000000001004", "spout_clips", "trending"],
+ ["1900000000000001005", "lid_watch", "trending"],
+ ],
+ );
+ const quoting = parsed.posts[1];
+ assert.equal(quoting.quoted?.id, "1900000000000000900");
+ assert.equal(quoting.quoted?.author, "kettle_org");
+ assert.equal(parsed.posts[3].isReply, true);
+ assert.equal(parsed.posts[3].replyTo?.id, "1900000000000001001");
+ assert.equal(parsed.posts[0].url, "https://x.com/teapot_news/status/1900000000000001001");
+ assert.deepEqual(parsed.media, {
+ "1900000000000001001": { count: 2, kinds: ["image"] },
+ "1900000000000001004": { count: 1, kinds: ["video"] },
+ "1900000000000001005": { count: 1, kinds: ["gif"] },
+ });
+ // Another surface's answer is counted, and its posts are not the page's.
+ assert.deepEqual(
+ parsed.operations.map((o) => [o.op, o.responses, o.tweets]),
+ [
+ [FIXTURE_TREND_OP, 1, 0],
+ [FIXTURE_TIMELINE_OP, 2, 5],
+ ["HomeTimeline", 1, 0],
+ ],
+ );
+ assert.equal(parsed.responses, 4);
+ assert.ok(parsed.posts.every((p) => p.author !== "home_only" && p.author !== "advert_co"));
+});
+
+test("an answer that failed, or whose body was not kept, yields nothing", () => {
+ const body = fixtureTimelineBody(FIXTURE_FIRST_PAGE);
+ const line = (over: Partial<TrendingCaptureLine>): TrendingCaptureLine => ({
+ n: 1,
+ at: "2026-11-17T10:00:00.000Z",
+ op: FIXTURE_TIMELINE_OP,
+ status: 200,
+ url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline",
+ bytes: 10,
+ body,
+ ...over,
+ });
+ assert.equal(parseTrendingCapture([line({ status: 429 })], "t").posts.length, 0);
+ assert.equal(parseTrendingCapture([line({ body: undefined, skipped: "too-large" })], "t").posts.length, 0);
+ assert.equal(parseTrendingCapture([line({})], "t").posts.length, 3);
+ assert.equal(parseTrendingCapture([line({ body: { data: {} } })], "t").posts.length, 0);
+});
diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts
@@ -0,0 +1,212 @@
+// WHAT A SAVED TRENDING-PAGE CAPTURE HOLDS (lane x-trending, slice 1).
+//
+// A read of x.com/i/trending/<id> (xTrendingRead.ts) saves every GraphQL JSON
+// answer the page itself fetched, one per line, in
+// `channels/<lib>/trending/reads/<readId>/responses.jsonl`. This module is the
+// ONLY reader of that file's bodies: the posts are parsed from the SAVED file,
+// never from the live page, so a better parser never costs a second read
+// (`read-x-trending {"reparse": <readId>}` is offline).
+//
+// X's operation names for this page are not known offline (the first real
+// read is the probe), so nothing here matches an operation by name to FIND
+// posts: every answer is walked for tweet results, as the Playwright fallback
+// does (xPlaywrightFetcher.ts collectTweetsFromGraphQL). Unlike that walk,
+// this one stops AT a tweet: the post it quotes or reposts is that post's
+// context, not another post of the page; and it skips promoted entries. A few
+// operations known to belong to other surfaces of the app are ignored by name.
+//
+// Pure but for readCaptureLines (node:fs).
+
+import { readFile } from "node:fs/promises";
+import type { Post } from "../lib/posts";
+import { normalizeXTweets, xIdOf, type XTweetRaw } from "./xNormalize";
+
+// One answer the page fetched, as saved. `body` is absent when the answer was
+// not kept (`skipped` says why): not JSON, too large, or past the read's cap.
+export type TrendingCaptureLine = {
+ n: number;
+ at: string;
+ // The GraphQL operation's name, from the URL's path.
+ op: string;
+ status: number;
+ url: string;
+ bytes: number;
+ body?: unknown;
+ skipped?: "not-json" | "too-large" | "over-cap" | "unread";
+};
+
+const GRAPHQL_RE = /^https:\/\/(?:[a-z0-9-]+\.)?(?:x|twitter)\.com\/i\/api\/graphql\/[^/?#]+\/([A-Za-z0-9_]+)(?:[?#]|$)/;
+
+// The operation a response URL names (x.com/i/api/graphql/<query id>/<Op>),
+// or null for anything that is not one of X's GraphQL answers.
+export function graphqlOpOf(url: string): string | null {
+ return GRAPHQL_RE.exec(url)?.[1] ?? null;
+}
+
+// Operations of OTHER surfaces a logged-in page may fetch beside its own: the
+// home timelines, notifications, the sidebar. Their posts are not the page's.
+export const X_TRENDING_IGNORED_OPS: readonly string[] = [
+ "HomeTimeline",
+ "HomeLatestTimeline",
+ "NotificationsTimeline",
+ "ExploreSidebar",
+ "SidebarUserRecommendations",
+ "PinnedTimelines",
+];
+
+function obj(v: unknown): Record<string, unknown> | undefined {
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined;
+}
+
+// A tweet result: `{rest_id, legacy: {full_text, …}, core}` — tagged
+// `__typename: "Tweet"` or bare (the inside of a TweetWithVisibilityResults).
+function tweetLegacy(rec: Record<string, unknown>): Record<string, unknown> | undefined {
+ const legacy = obj(rec.legacy);
+ if (!legacy || typeof legacy.full_text !== "string") return undefined;
+ if (typeof rec.rest_id !== "string" && typeof legacy.id_str !== "string") return undefined;
+ return legacy;
+}
+
+// A nested result (`quoted_status_result`, `retweeted_status_result`): its
+// tweet, through a visibility wrapper.
+function nestedTweet(v: unknown): XTweetRaw | undefined {
+ const result = obj(obj(v)?.result);
+ if (!result) return undefined;
+ const inner = obj(result.tweet) ?? result;
+ const legacy = tweetLegacy(inner);
+ return legacy ? flatten(inner, legacy, false) : undefined;
+}
+
+// `{rest_id, legacy, core}` as the flat record the shared normalizer reads.
+function flatten(rec: Record<string, unknown>, legacy: Record<string, unknown>, withContext: boolean): XTweetRaw {
+ const out: XTweetRaw = { ...legacy };
+ if (typeof rec.rest_id === "string") out.rest_id = rec.rest_id;
+ if (rec.note_tweet) out.note_tweet = rec.note_tweet;
+ // The author: core.user_results.result, its names under `legacy` or (newer
+ // answers) under `core`.
+ const user = obj(obj(obj(rec.core)?.user_results)?.result);
+ const names = { ...obj(user?.core), ...obj(user?.legacy) } as Record<string, unknown>;
+ if (typeof names.screen_name === "string") {
+ out.user = { name: names.screen_name, ...(typeof names.name === "string" ? { nick: names.name } : {}) };
+ }
+ if (withContext) {
+ const quoted = nestedTweet(rec.quoted_status_result);
+ if (quoted) out.quoted = quoted;
+ const reposted = nestedTweet(legacy.retweeted_status_result ?? rec.retweeted_status_result);
+ if (reposted) out.retweeted_status = reposted;
+ }
+ delete out.retweeted_status_result;
+ return out;
+}
+
+// Every post of the page in one answer, in the order the answer lists them.
+// The walk stops at a tweet (what it quotes or reposts is carried on it) and
+// never enters a promoted entry.
+export function collectTimelineTweets(payload: unknown): XTweetRaw[] {
+ const out: XTweetRaw[] = [];
+ const seen = new Set<unknown>();
+ const visit = (node: unknown): void => {
+ if (!node || typeof node !== "object" || seen.has(node)) return;
+ seen.add(node);
+ if (Array.isArray(node)) {
+ for (const item of node) visit(item);
+ return;
+ }
+ const rec = node as Record<string, unknown>;
+ if (rec.promotedMetadata) return;
+ const legacy = tweetLegacy(rec);
+ if (legacy) {
+ out.push(flatten(rec, legacy, true));
+ return;
+ }
+ for (const value of Object.values(rec)) visit(value);
+ };
+ visit(payload);
+ return out;
+}
+
+export type TrendingMediaKind = "image" | "video" | "gif";
+export type TrendingMediaSummary = { count: number; kinds: TrendingMediaKind[] };
+
+const MEDIA_KIND: Record<string, TrendingMediaKind> = { photo: "image", video: "video", animated_gif: "gif" };
+
+// What media a post carries, by kind — counted from the answer, nothing fetched.
+export function mediaSummaryOf(raw: XTweetRaw): TrendingMediaSummary | undefined {
+ const media = obj(raw.extended_entities)?.media ?? obj(raw.entities)?.media;
+ if (!Array.isArray(media) || media.length === 0) return undefined;
+ const kinds = new Set<TrendingMediaKind>();
+ for (const m of media) {
+ // An own key only: a `type` of "constructor" or "toString" is no kind.
+ const type = String(obj(m)?.type ?? "");
+ if (Object.hasOwn(MEDIA_KIND, type)) kinds.add(MEDIA_KIND[type]);
+ }
+ return { count: media.length, kinds: [...kinds].sort() };
+}
+
+export type TrendingOperation = { op: string; responses: number; bytes: number; statuses: number[]; tweets: number };
+
+export type ParsedTrendingCapture = {
+ // The page's posts, first shown first, each once.
+ posts: Post[];
+ // Post id → its media, for the posts that carry any.
+ media: Record<string, TrendingMediaSummary>;
+ // Operation names and sizes only: what read.json may say of the capture.
+ operations: TrendingOperation[];
+ responses: number;
+ bytes: number;
+};
+
+// The capture, parsed. `channelSlug` is the library's (a Post names its channel).
+export function parseTrendingCapture(
+ lines: ReadonlyArray<TrendingCaptureLine>,
+ channelSlug: string,
+): ParsedTrendingCapture {
+ const raws: XTweetRaw[] = [];
+ const media: Record<string, TrendingMediaSummary> = {};
+ const ops = new Map<string, TrendingOperation>();
+ let bytes = 0;
+ for (const line of lines) {
+ const op = ops.get(line.op) ?? { op: line.op, responses: 0, bytes: 0, statuses: [], tweets: 0 };
+ ops.set(line.op, op);
+ op.responses++;
+ op.bytes += line.bytes;
+ bytes += line.bytes;
+ if (!op.statuses.includes(line.status)) op.statuses.push(line.status);
+ if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue;
+ if (line.status < 200 || line.status >= 300) continue;
+ const found = collectTimelineTweets(line.body);
+ op.tweets += found.length;
+ for (const raw of found) {
+ raws.push(raw);
+ const id = xIdOf(raw);
+ const summary = mediaSummaryOf(raw);
+ if (id && summary && !media[id]) media[id] = summary;
+ }
+ }
+ const posts = normalizeXTweets(raws, channelSlug);
+ const kept: Record<string, TrendingMediaSummary> = {};
+ for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id];
+ return {
+ posts,
+ media: kept,
+ operations: [...ops.values()].sort((a, b) => a.op.localeCompare(b.op)),
+ responses: lines.length,
+ bytes,
+ };
+}
+
+// The saved file's lines; a line that is not JSON (a write cut short) is skipped.
+export async function readCaptureLines(file: string): Promise<TrendingCaptureLine[]> {
+ const text = await readFile(file, "utf8");
+ const out: TrendingCaptureLine[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const rec = JSON.parse(line) as TrendingCaptureLine;
+ if (rec && typeof rec.op === "string" && typeof rec.status === "number") out.push(rec);
+ } catch {
+ /* a torn line */
+ }
+ }
+ return out;
+}
diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts
@@ -0,0 +1,499 @@
+// 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 { bounded, 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, PageLike } 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);
+});
+
+// --- review 1: caps, a 403, a 401 mid-scroll, deadlines, the closed file ------
+
+async function readWith(
+ page: PageLike,
+ over: Partial<Parameters<typeof readXTrendingPage>[0]> & { close?: () => Promise<void>; kill?: () => Promise<void> } = {},
+) {
+ const dir = path.join(TMP, `read-${++dirs}`);
+ const log: string[] = [];
+ const { close, kill, ...rest } = over;
+ const result = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir,
+ openPage: async () => ({ page, close: close ?? (async () => {}), ...(kill ? { kill } : {}) }),
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: new AbortController().signal,
+ onLog: (l) => log.push(l),
+ ...rest,
+ });
+ return { result, dir, log };
+}
+
+test("the byte caps: an answer too large, and answers past the read's cap, are counted and not kept", async () => {
+ const big = fixtureTimelineBody(Array.from({ length: 6 }, (_, i) => tweet(i)));
+ const small = fixtureTimelineBody([tweet(7)]);
+ const smallBytes = Buffer.byteLength(JSON.stringify(small));
+ const page = fakeTrendingPage(() => ({
+ trending: {
+ load: [
+ { url: timelineUrl(0), status: 200, body: big },
+ { url: timelineUrl(1), status: 200, body: small },
+ { url: timelineUrl(2), status: 200, body: small },
+ ],
+ scrolls: [[], []],
+ },
+ }));
+ const { result, dir } = await readWith(page, { maxResponseBytes: smallBytes + 10, maxReadBytes: smallBytes + 10 });
+ assert.equal(result.responses, 3);
+ assert.equal(result.saved, 1);
+ assert.equal(result.bytes, smallBytes);
+ assert.equal(result.tweets, 1);
+ const lines = await readCaptureLines(path.join(dir, "responses.jsonl"));
+ assert.deepEqual(lines.map((l) => [l.n, l.skipped ?? "kept", l.body === undefined]), [
+ [1, "too-large", true],
+ [2, "kept", false],
+ [3, "over-cap", true],
+ ]);
+ assert.ok(lines[0].bytes > smallBytes + 10);
+});
+
+test("a 403 stops the read at once: no scroll follows, and it is not a login wall", async () => {
+ const first = await read({
+ load: [
+ { url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) },
+ { url: timelineUrl(1), status: 403, body: { errors: [{ code: 200 }] } },
+ ],
+ scrolls: [[{ url: timelineUrl(2), status: 200, body: fixtureTimelineBody([tweet(2)]) }]],
+ });
+ assert.equal(first.result.stop, "forbidden");
+ assert.equal(first.result.scrolls, 0);
+ assert.equal(first.result.tweets, 1);
+ // On X's login page a 403 is the login wall's.
+ const walled = await read({ href: "https://x.com/i/flow/login", load: [{ url: timelineUrl(0), status: 403, text: "" }] });
+ assert.equal(walled.result.stop, "login-wall");
+ // And a rate limit beside a 403 is the rate limit.
+ const both = await read({ load: [{ url: timelineUrl(0), status: 403, text: "" }, { url: timelineUrl(1), status: 429, text: "" }] });
+ assert.equal(both.result.stop, "rate-limit");
+});
+
+test("a 401 on a scroll ends the read there, as a login wall", async () => {
+ const { result } = await read({
+ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }],
+ scrolls: [
+ [{ url: timelineUrl(1), status: 200, body: fixtureTimelineBody([tweet(1)]) }],
+ [{ url: timelineUrl(2), status: 401, body: { errors: [{ code: 32 }] } }],
+ [{ url: timelineUrl(3), status: 200, body: fixtureTimelineBody([tweet(3)]) }],
+ ],
+ });
+ assert.equal(result.stop, "login-wall");
+ assert.equal(result.scrolls, 2);
+ assert.equal(result.tweets, 2);
+});
+
+const never = <T>() => new Promise<T>(() => {});
+
+test("a page that stops answering ends the read with a sentence; the browser is closed, and killed when closing hangs too", async () => {
+ // The scroll never answers.
+ const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[]] } }));
+ let closed = 0;
+ const hungScroll = { ...base, evaluate: (fn: string) => (fn.includes("scrollTo") ? never<unknown>() : base.evaluate(fn)) } as PageLike;
+ const scroll = await readWith(hungScroll, { timeouts: { call: 40 }, close: async () => void closed++ });
+ assert.equal(scroll.result.stop, "deadline");
+ assert.equal(scroll.result.error, "the page did not answer within 0 s (scrolling)");
+ assert.equal(scroll.result.tweets, 1);
+ assert.equal(closed, 1);
+ assert.equal((await readCaptureLines(path.join(scroll.dir, "responses.jsonl"))).length, 1);
+
+ // The load never answers.
+ const hungLoad = { ...base, goto: () => never<unknown>() } as PageLike;
+ const load = await readWith(hungLoad, { timeouts: { load: 40 } });
+ assert.equal(load.result.stop, "deadline");
+ assert.match(load.result.error ?? "", /did not answer within 0 s \(loading the page\)/);
+
+ // Closing never answers: the browser is killed, and the read still returns.
+ let killed = 0;
+ const stuck = await readWith(fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })), {
+ timeouts: { close: 40 },
+ close: () => never<void>(),
+ kill: async () => void killed++,
+ });
+ assert.equal(stuck.result.stop, "idle");
+ assert.equal(killed, 1);
+ assert.ok(stuck.log.some((l) => /The browser did not close .*; killing it\./.test(l)));
+});
+
+test("the whole read has a deadline: past it the read stops where it is, what was captured kept", async () => {
+ const pages = {
+ load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }],
+ scrolls: Array.from({ length: 20 }, (_, i) => [{ url: timelineUrl(i + 1), status: 200, body: fixtureTimelineBody([tweet(i + 1)]) }]),
+ };
+ const { result, dir } = await readWith(fakeTrendingPage(() => ({ trending: pages })), {
+ limits: { scrolls: 20, posts: 200 },
+ // Each wait is 30 ms of real time; the read may take 100.
+ pauseMs: () => 30,
+ pause: undefined,
+ timeouts: { read: 100 },
+ });
+ assert.equal(result.stop, "deadline");
+ assert.ok(result.scrolls >= 1 && result.scrolls < 20, String(result.scrolls));
+ assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl"))).length, result.responses);
+});
+
+test("once the read has returned, a late answer is not appended to the capture", async () => {
+ const handlers: Array<(res: unknown) => void> = [];
+ const base = fakeTrendingPage(() => ({ trending: { load: [{ url: timelineUrl(0), status: 200, body: fixtureTimelineBody([tweet(0)]) }], scrolls: [[], []] } }));
+ const page = {
+ ...base,
+ on: (event: string, cb: (arg: never) => void) => {
+ if (event === "response") handlers.push(cb as (res: unknown) => void);
+ base.on(event, cb);
+ },
+ } as PageLike;
+ const { result, dir } = await readWith(page);
+ const before = readFileSync(path.join(dir, "responses.jsonl"), "utf8");
+ for (const h of handlers) {
+ h({ url: () => timelineUrl(9), status: () => 200, text: async () => JSON.stringify(fixtureTimelineBody([tweet(9)])) });
+ }
+ await new Promise((r) => setTimeout(r, 30));
+ assert.equal(readFileSync(path.join(dir, "responses.jsonl"), "utf8"), before);
+ assert.equal(result.responses, 1);
+});
+
+test("an answer whose body cannot be read costs that answer, not the read", async () => {
+ const handlers: Array<(res: unknown) => void> = [];
+ const page = {
+ ...fakeTrendingPage(() => ({ trending: { load: [], scrolls: [[], []] } })),
+ on: (event: string, cb: (arg: never) => void) => void (event === "response" && handlers.push(cb as (res: unknown) => void)),
+ goto: async () => {
+ for (const h of handlers) {
+ h({ url: () => timelineUrl(0), status: () => 200, text: () => Promise.reject(new Error("the body is gone")) });
+ h({ url: () => { throw new Error("no url"); }, status: () => 200, text: async () => "{}" });
+ }
+ return null;
+ },
+ } as PageLike;
+ const { result, dir } = await readWith(page);
+ assert.equal(result.stop, "idle");
+ assert.equal(result.responses, 1);
+ assert.equal((await readCaptureLines(path.join(dir, "responses.jsonl")))[0].skipped, "unread");
+});
+
+// --- 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);
+});
+
+test("a context whose first page cannot be made is closed, not left holding the profile", async () => {
+ for (const headed of [false, true]) {
+ let closed = 0;
+ const context: BrowserContextLike = {
+ newPage: async () => {
+ throw new Error("Target page, context or browser has been closed");
+ },
+ pages: () => [],
+ cookies: async () => [],
+ addCookies: async () => {},
+ close: async () => void closed++,
+ on: () => {},
+ };
+ const chromium: ChromiumLike = {
+ opensNoWindow: true,
+ launch: async () => {
+ throw new Error("not used");
+ },
+ launchPersistentContext: async () => context,
+ };
+ await assert.rejects(
+ openXTrendingPage(paths(`newpage-${headed}`), { headed, chromium, env: { PATH: "" } }),
+ /Target page, context or browser has been closed/,
+ );
+ assert.equal(closed, 1, headed ? "headed" : "headless");
+ }
+});
+
+// --- review 2 ---------------------------------------------------------------
+
+test("N1: a browser that opens after the deadline, or after a cancel, is closed; an aborted read opens none", async () => {
+ // The launch resolves 80 ms in; the read gave it 30.
+ let closed = 0;
+ let opened = 0;
+ const slow = () =>
+ new Promise<{ page: PageLike; close: () => Promise<void> }>((resolve) =>
+ setTimeout(() => {
+ opened++;
+ resolve({ page: fakeTrendingPage(() => ({})), close: async () => void closed++ });
+ }, 80),
+ );
+ const late = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: slow,
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: new AbortController().signal,
+ timeouts: { load: 30 },
+ });
+ assert.equal(late.stop, "deadline");
+ assert.match(late.error ?? "", /opening the browser/);
+ assert.equal(closed, 0, "not open yet when the read returned");
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(opened, 1);
+ assert.equal(closed, 1, "the browser that opened late was closed");
+
+ // Cancelled while it launches.
+ const ac = new AbortController();
+ setTimeout(() => ac.abort(), 20);
+ const cancelled = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: slow,
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: ac.signal,
+ });
+ assert.equal(cancelled.stop, "cancelled");
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(opened, 2);
+ assert.equal(closed, 2);
+
+ // Already cancelled on entry: no browser is asked for at all.
+ const gone = new AbortController();
+ gone.abort();
+ let asked = 0;
+ const never = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: async () => {
+ asked++;
+ return { page: fakeTrendingPage(() => ({})), close: async () => {} };
+ },
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: gone.signal,
+ });
+ assert.equal(never.stop, "cancelled");
+ assert.equal(asked, 0);
+});
+
+test("N3: a call bounded on a signal already aborted leaves no unhandled rejection behind", async () => {
+ const unhandled: unknown[] = [];
+ const onUnhandled = (e: unknown) => void unhandled.push(e);
+ process.on("unhandledRejection", onUnhandled);
+ try {
+ const ac = new AbortController();
+ ac.abort();
+ let reject!: (e: Error) => void;
+ const orphan = new Promise<string>((_, r) => (reject = r));
+ await assert.rejects(bounded("reading its address", orphan, 1_000, ac.signal), /cancelled/);
+ // The context closes later and the orphaned call rejects.
+ reject(new Error("Target closed"));
+ await new Promise((r) => setTimeout(r, 30));
+ assert.deepEqual(unhandled, []);
+ } finally {
+ process.off("unhandledRejection", onUnhandled);
+ }
+});
diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts
@@ -0,0 +1,443 @@
+// 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 403, a 401 or a login page. It never
+// retries.
+//
+// NOTHING HERE WAITS FOREVER (review 1). Every call into the page is raced
+// against a deadline — the load 75 s, a scroll, a look at the address or a
+// screenshot 20 s each, closing the browser 10 s — and against the job's
+// cancel; and the whole read against READ_DEADLINE_MS (6 minutes: twenty
+// scrolls at the longest gap, twice over). A page that stops answering ends
+// the read with a sentence, what was captured kept, and the browser is closed
+// (killed, when closing does not answer) so the profile is free again. Once
+// the read returns, nothing more is appended to responses.jsonl.
+//
+// The caller (controller/readXTrending.ts) is one editor job on X's queue;
+// this module knows nothing of queues, alerts or the store.
+
+// A browser that will not close is killed (`session.kill`): the guard every
+// module that kills a process installs (lib/childKillGuard.test.ts).
+import "../lib/childKillGuard";
+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;
+
+// The deadlines (ms): the page's load, any other call into the page, closing
+// the browser, and one whole read.
+export const PAGE_LOAD_TIMEOUT_MS = 75_000;
+export const PAGE_CALL_TIMEOUT_MS = 20_000;
+export const PAGE_CLOSE_TIMEOUT_MS = 10_000;
+export const READ_DEADLINE_MS = 6 * 60_000;
+
+// 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
+// forbidden the page's own request was answered 403
+// login-wall X showed its login page, or answered 401
+// deadline the page stopped answering, or the read ran past its deadline
+// error the page did not load
+export type TrendingReadStop =
+ | "idle"
+ | "scroll-cap"
+ | "post-cap"
+ | "cancelled"
+ | "rate-limit"
+ | "forbidden"
+ | "login-wall"
+ | "deadline"
+ | "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;
+ // The FIRST answer that stopped the read — a 429, a 403 or a 401 — by its
+ // operation and status, so a read's record says which request it was.
+ stoppedBy?: { op: string; status: number };
+};
+
+// `kill` ends the browser when `close` does not answer (optional: a fake has none).
+export type TrendingPageSession = { page: PageLike; close: () => Promise<void>; kill?: () => Promise<void> };
+
+export class PageDeadlineError extends Error {
+ constructor(what: string, ms: number) {
+ super(`the page did not answer within ${Math.round(ms / 1000)} s (${what})`);
+ this.name = "PageDeadlineError";
+ }
+}
+
+// `p`, or a PageDeadlineError after `ms`, or an abort — whichever is first.
+// The loser is left to settle by itself (its rejection swallowed).
+export function bounded<T>(what: string, p: Promise<T>, ms: number, signal?: AbortSignal): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ let done = false;
+ const finish = (fn: () => void) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ fn();
+ };
+ const onAbort = () => finish(() => reject(new Error("cancelled")));
+ const timer = setTimeout(() => finish(() => reject(new PageDeadlineError(what, ms))), ms);
+ // The handlers go on `p` FIRST (review 2 N3): were the aborted check to
+ // return before them, a call still in flight would reject with nobody
+ // listening when the context closes under it.
+ p.then(
+ (v) => finish(() => resolve(v)),
+ (e) => finish(() => reject(e)),
+ );
+ if (signal?.aborted) return onAbort();
+ signal?.addEventListener("abort", onAbort);
+ });
+}
+
+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;
+ // The byte caps and the deadlines, for tests (defaults: the constants above).
+ maxResponseBytes?: number;
+ maxReadBytes?: number;
+ timeouts?: { load?: number; call?: number; close?: number; read?: number };
+}): Promise<TrendingPageRead> {
+ const log = o.onLog ?? (() => {});
+ const pause = o.pause ?? abortablePause;
+ const now = o.now ?? Date.now;
+ const maxResponse = o.maxResponseBytes ?? TRENDING_RESPONSE_MAX_BYTES;
+ const maxRead = o.maxReadBytes ?? TRENDING_READ_MAX_BYTES;
+ const t = {
+ load: o.timeouts?.load ?? PAGE_LOAD_TIMEOUT_MS,
+ call: o.timeouts?.call ?? PAGE_CALL_TIMEOUT_MS,
+ close: o.timeouts?.close ?? PAGE_CLOSE_TIMEOUT_MS,
+ read: o.timeouts?.read ?? READ_DEADLINE_MS,
+ };
+ // The read's own clock: fired at its deadline, and by the job's cancel.
+ const clock = new AbortController();
+ let pastDeadline = false;
+ const deadline = setTimeout(() => {
+ pastDeadline = true;
+ clock.abort();
+ }, t.read);
+ const onCancel = () => clock.abort();
+ if (o.signal.aborted) clock.abort();
+ else o.signal.addEventListener("abort", onCancel);
+ const signal = clock.signal;
+ 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 forbidden = false;
+ let n = 0;
+ let writes: Promise<void> = Promise.resolve();
+ // Closed when the read returns: an answer that arrives later is not written.
+ let closed = false;
+ const pending = new Set<Promise<void>>();
+
+ const keep = (line: TrendingCaptureLine) => {
+ if (closed) return;
+ // What was queued before the close is still written; nothing is queued after it.
+ writes = writes.then(() => appendFile(file, JSON.stringify(line) + "\n")).catch(() => {});
+ };
+
+ const onResponse = (res: ResponseLike) => {
+ if (closed) return;
+ 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;
+ if (status === 403) forbidden = true;
+ if ((status === 429 || status === 401 || status === 403) && !out.stoppedBy) out.stoppedBy = { op, status };
+ 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 > maxResponse) return keep({ ...base, bytes, skipped: "too-large" });
+ if (out.bytes + bytes > maxRead) 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);
+ }
+ }
+ })().catch(() => {
+ /* a throw while reading one answer costs that answer, never the read */
+ });
+ pending.add(task);
+ void task.finally(() => pending.delete(task)).catch(() => {});
+ };
+
+ // 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))]);
+ };
+ // A login wall first (it is what the other statuses would mean too), then
+ // the rate limit, then a plain refusal.
+ const blocked = (): TrendingReadStop | null =>
+ unauthorized ? "login-wall" : rateLimited ? "rate-limit" : forbidden ? "forbidden" : null;
+
+ let session: TrendingPageSession | undefined;
+ // The launch itself, kept (review 2 N1): when the deadline or a cancel wins
+ // the race below, the browser may still open afterwards, holding the
+ // profile — it is closed the moment it does.
+ let opening: Promise<TrendingPageSession> | undefined;
+ try {
+ // A read cancelled before it began asks for no browser at all.
+ if (signal.aborted) throw new Error("cancelled");
+ opening = o.openPage();
+ session = await bounded("opening the browser", opening, t.load, signal);
+ const { page } = session;
+ page.on("response", onResponse as (arg: never) => void);
+ await bounded("loading the page", page.goto(o.url, { waitUntil: "domcontentloaded", timeout: 60_000 }), t.load, signal);
+ // The page settles: its first requests go out and come back.
+ await pause(o.pauseMs(), signal);
+ await settle();
+ const href = await bounded("reading its address", page.evaluate("location.href"), t.call, signal).catch((err) => {
+ if (err instanceof PageDeadlineError) throw err;
+ return null;
+ });
+ if (isXLoginHref(href)) unauthorized = true;
+ try {
+ const png = await bounded("the screenshot", page.screenshot({ type: "png" }), t.call, signal);
+ await writeFile(path.join(o.dir, TRENDING_PAGE_SHOT_FILENAME), png);
+ out.shot = true;
+ } catch (err) {
+ if (err instanceof PageDeadlineError) throw 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 (signal.aborted) stop = pastDeadline ? "deadline" : "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 bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal);
+ out.scrolls++;
+ await pause(o.pauseMs(), 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) {
+ const hung = err instanceof PageDeadlineError || pastDeadline;
+ out.stop = blocked() ?? (hung ? "deadline" : o.signal.aborted ? "cancelled" : "error");
+ out.error = pastDeadline && !(err instanceof PageDeadlineError)
+ ? `the read ran past its ${Math.round(t.read / 1000)} s deadline`
+ : firstLine(err);
+ } finally {
+ clearTimeout(deadline);
+ o.signal.removeEventListener("abort", onCancel);
+ // The answers already in flight, briefly; then the file is closed.
+ await Promise.race([Promise.allSettled([...pending]), new Promise((r) => setTimeout(r, Math.min(t.call, 15_000)))]);
+ closed = true;
+ await writes;
+ // The browser is closed whatever happened; one that does not answer is
+ // killed, so the profile is never left held by a dead page.
+ if (!session && opening) {
+ void opening
+ .then(async (s) => {
+ log("The browser opened after the read had ended: closing it.");
+ await bounded("closing the browser", s.close(), t.close).catch(() => (s.kill ? s.kill() : undefined));
+ })
+ .catch(() => {});
+ }
+ if (session) {
+ const s = session;
+ await bounded("closing the browser", s.close(), t.close).catch(async (err) => {
+ log(`The browser did not close (${firstLine(err)})${s.kill ? "; killing it." : "."}`);
+ if (s.kill) await bounded("killing the browser", s.kill(), t.close).catch(() => {});
+ });
+ }
+ }
+ if (out.stop === "idle" && pastDeadline) out.stop = "deadline";
+ 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 } : {}) });
+ }
+ // A context that opened holds the profile: it is closed on every way out,
+ // a failed newPage included (review 1).
+ let page: PageLike;
+ try {
+ page = context.pages()[0] ?? (await context.newPage());
+ } catch (err) {
+ await context.close().catch(() => {});
+ throw err;
+ }
+ // The browser behind a persistent context, when the runtime names it: what
+ // `kill` closes if the context itself stops answering.
+ const browser = (context as { browser?: () => { close?: () => Promise<void> } | null }).browser?.() ?? null;
+ return {
+ page,
+ close: () => context.close(),
+ ...(browser?.close ? { kill: () => browser.close!() } : {}),
+ };
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,39 @@
# Changelog
## [Unreleased]
+- **X trending pages can be read into a private library.** A new kind of channel, **X trending library** in the New
+ channel form's Platform (`"platform": "x-trending"`), holds the posts X's trending pages (`x.com/i/trending/…`)
+ show, grouped into your topics. Read one page with **Read a trending page** on the library's channel page, or
+ `pnpm ops read-x-trending --json '{"slug":"…","url":"…","topic":"…"}'`.
+ - A library is private. It is never put on a site, and no index build reads it, so its posts are in no site, hub,
+ `corpus.json`, `llms.txt` or MCP corpus tool. They are not in the editor's own search either: the channel page's
+ Topics, `pnpm ops get trending <slug>` and the MCP's `x_trending_topics` / `x_trending_posts` read the library's
+ own files.
+ - One page is one job on X's queue: the cookie-age rule, the X alert and the 5-minute gap between X jobs apply. The
+ page opens in the connected X profile's browser, and the answers the page itself fetches are saved raw with a
+ screenshot under `channels/<slug>/trending/reads/`. A read scrolls at most 8 times (cap 20) with 4–10 s between,
+ stops at 60 posts (cap 200) or after two scrolls with nothing new, and stops at once on a rate limit or a login
+ page. Nothing retries.
+ - A read lists posts: words, author, date and media by kind. It downloads no media and no thread. Reading the
+ same page again adds the new posts and keeps the old ones.
+ - `"probe": true` saves the capture and a summary and writes no post. `{"reparse": "<readId>"}` parses a saved
+ capture again without asking X.
+ - A capture the parser finds no post in ends "Read saved, nothing recognised", with the capture kept. It is not a
+ failure and raises no alert.
+ - No report, article, draft or video project is offered a library's posts. They are kept in
+ `channels/<slug>/trending/posts/`, not where a posts channel keeps its posts, so every other reader finds a
+ library empty; an article or report that cites a library is refused, and a draft's X link never resolves to one.
+ - A read cannot hang: the load has 75 s, each scroll 20 s, the whole read 6 minutes, and the browser is closed or
+ killed. A 429 leaves X alone for 15 minutes (the sentence says until when), which also holds X post captures,
+ import-post on X and the download lane's X units; a 403 stops the read at once with its own sentence and no
+ login alert. `read.json` names the operation and status that stopped a read.
+ - The raw captures are never committed: `trending/reads/.gitignore` ignores everything under it.
+- **X's Connect and Refresh cookies say when a job is using the profile.** While a trending-page read or a post
+ capture is running on X's queue, a press is refused with a sentence that names the job and says to cancel it on
+ /jobs or wait; a queued job blocks nothing. A trending-page read is refused while a Connect or Refresh is running,
+ and an X post capture that starts during one fails with the same sentence. Before, the second browser failed with
+ Chromium's own error.
+- **Fetch posts on an X trending library is refused with a sentence**, and the X run does not list a library.
- **umtool: a video's reads, found, replaced and re-read in one press, with no agent (the Reads page).**
`/projects/<p>/reads` lists every line a synthetic voice reads: a post's script, the pieces of a thread read, screen
lines and card narration. Each line shows what it SAYS, the take that plays and its state:
diff --git a/editor/app/api/ops/read-x-trending/route.test.ts b/editor/app/api/ops/read-x-trending/route.test.ts
@@ -0,0 +1,207 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/read-x-trending/route.test.ts"
+//
+// An X trending library over ops (lane x-trending), against a temp corpus:
+// every refusal of read-x-trending BEFORE a job exists (so no browser opens
+// and nothing is asked of X — the corpus has no connected profile, which is
+// itself the last refusal), the listing (`GET /api/ops/trending`), and the
+// channel form's refusals: a library on a site, a library with a URL, a
+// library turned into an ordinary channel. A read itself is driven in
+// e2e/x-trending.spec.ts over the fake browser.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-route-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const READ = "tr-01JA0000000000000000000000";
+const TREND = "https://x.com/i/trending/1900000000000000001";
+
+async function channel(slug: string, config: Record<string, unknown>): Promise<string> {
+ const dir = path.join(ROOT, "channels", slug);
+ await mkdir(path.join(dir, "trending", "posts"), { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config }));
+ return dir;
+}
+
+const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} });
+await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" });
+await writeFile(
+ path.join(lib, "trending", "posts", "2026-11.jsonl"),
+ ["1900000000000001001", "1900000000000001002"]
+ .map((id, i) =>
+ JSON.stringify({
+ id,
+ slug: `trending/${id}`,
+ channelSlug: "trending",
+ author: i ? "saucer_fan" : "teapot_news",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ uploadDate: "20261116",
+ text: i ? "Second." : "The kettle festival opens today.",
+ url: `https://x.com/${i ? "saucer_fan" : "teapot_news"}/status/${id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }),
+ )
+ .join("\n") + "\n",
+);
+await writeFile(path.join(lib, "trending", "posts-archive"), "twitter 1900000000000001001\ntwitter 1900000000000001002\n");
+await mkdir(path.join(lib, "trending", "reads", READ), { recursive: true });
+await writeFile(path.join(lib, "trending", "reads", READ, "responses.jsonl"), JSON.stringify({ n: 1, op: "Op", status: 200, bytes: 9, url: "u", at: "x", body: { secret: "rawcapturemarker" } }) + "\n");
+await writeFile(
+ path.join(lib, "trending", "topics.json"),
+ JSON.stringify({
+ version: 1,
+ topics: [
+ {
+ id: "kettles",
+ title: "Kettles",
+ createdAt: "2026-11-17T10:00:00.000Z",
+ sources: [{ trendId: "1900000000000000001", url: TREND, reads: [{ id: READ, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 }] }],
+ },
+ ],
+ }),
+);
+await writeFile(
+ path.join(lib, "trending", "membership.json"),
+ JSON.stringify({
+ version: 1,
+ posts: {
+ "1900000000000001001": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }], media: { count: 2, kinds: ["image"] } },
+ "1900000000000001002": { topic: "kettles", seen: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 2 }] },
+ },
+ }),
+);
+await mkdir(path.join(ROOT, "sites", "demo-site"), { recursive: true });
+await writeFile(path.join(ROOT, "sites", "demo-site", "site.json"), JSON.stringify({ siteId: "demo-site", siteTitle: "Demo", channels: [] }));
+
+const readTrending = (await import("./route")).POST;
+const listing = (await import("../trending/route")).GET;
+const create = (await import("../create-channel/route")).POST;
+const configure = (await import("../channel-config/route")).POST;
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function call(handler: (r: Request) => Promise<Response>, body: Record<string, unknown>) {
+ const res = await handler(
+ new Request("http://localhost/api/ops/x", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> };
+}
+
+async function get(query: string, token = "test-token") {
+ const res = await listing(new Request(`http://localhost/api/ops/trending${query}`, { headers: { authorization: `Bearer ${token}` } }));
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> };
+}
+
+const exists = (p: string) => access(p).then(() => true, () => false);
+
+test("read-x-trending refuses, before any job, with a sentence", async () => {
+ const refused = async (body: Record<string, unknown>) => {
+ const r = await call(readTrending, body);
+ assert.equal(r.status, 400, JSON.stringify(r.json));
+ assert.equal(r.json.ok, false);
+ return String(r.json.error);
+ };
+ assert.match(await refused({ url: TREND }), /"slug" is required/);
+ assert.equal(await refused({ slug: "nope", url: TREND }), "No such channel: nope");
+ assert.match(await refused({ slug: "account-x", url: TREND }), /account-x is not an X trending library/);
+ assert.match(await refused({ slug: "trending" }), /Give "url" .* or "reparse"/);
+ assert.match(await refused({ slug: "trending", url: "https://x.com/example/status/1" }), /not a trending page URL/);
+ assert.match(await refused({ slug: "trending", url: TREND, scrolls: 21 }), /"scrolls" is a whole number, 1–20/);
+ assert.match(await refused({ slug: "trending", url: TREND, posts: 0 }), /"posts" must be a whole number above zero/);
+ assert.match(await refused({ slug: "trending", url: TREND, probe: "yes" }), /"probe" must be a boolean/);
+ assert.match(await refused({ slug: "trending", url: TREND, pages: 3 }), /pages/);
+ assert.match(await refused({ slug: "trending", reparse: "tr-01JZ0000000000000000000000" }), /holds no saved read/);
+ // No connected X profile in this corpus: the read is refused, and no browser was asked for.
+ assert.match(await refused({ slug: "trending", url: TREND }), /needs the connected X profile/);
+ assert.equal(await exists(path.join(ROOT, ".jobs")), false, "no job was made");
+});
+
+test("get trending lists topics and posts — words, author, media, reads, topic — and never the raw capture", async () => {
+ const all = await get("?slug=trending");
+ assert.equal(all.status, 200);
+ assert.deepEqual(all.json.topics, [
+ { id: "kettles", title: "Kettles", posts: 2, sources: [{ trendId: "1900000000000000001", url: TREND, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }] },
+ ]);
+ const posts = all.json.posts as Array<Record<string, unknown>>;
+ assert.deepEqual(posts[0], {
+ id: "1900000000000001001",
+ author: "teapot_news",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/teapot_news/status/1900000000000001001",
+ text: "The kettle festival opens today.",
+ media: { count: 2, kinds: ["image"] },
+ topic: "kettles",
+ reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }],
+ });
+ assert.equal(all.json.total, 2);
+ assert.deepEqual(all.json.reads, [READ]);
+ assert.ok(!JSON.stringify(all.json).includes("rawcapturemarker"));
+ assert.equal(((await get("?slug=trending&limit=1")).json.posts as unknown[]).length, 1);
+ assert.equal(((await get("?slug=trending&topic=kettles")).json.posts as unknown[]).length, 2);
+ // Refusals.
+ assert.match(String((await get("?slug=trending&topic=nope")).json.error), /has no topic "nope" \(its topics: kettles\)/);
+ assert.match(String((await get("?slug=account-x")).json.error), /not an X trending library/);
+ assert.equal((await get("?slug=nope")).status, 404);
+ assert.match(String((await get("?slug=trending&limit=501")).json.error), /1–500/);
+ assert.match(String((await get("?slug=trending&raw=1")).json.error), /unknown parameter "raw"/);
+ assert.match(String((await get("?slug=..%2Fx")).json.error), /not a valid channel slug/);
+ assert.equal((await get("?slug=trending", "wrong")).status, 401);
+});
+
+test("create-channel refuses a library on a site and a library with a URL; nothing is made", async () => {
+ const fields = { name: "Made trending", handling: "transcribe", platform: "x-trending" };
+ const onSite = await call(create, { fields, sites: [{ siteId: "demo-site", groupId: "default" }] });
+ assert.equal(onSite.status, 400);
+ assert.equal(onSite.json.error, "made-trending is an X trending library: it is private, and never put on a site.");
+ const withUrl = await call(create, { fields: { ...fields, url: TREND } });
+ assert.equal(withUrl.status, 400);
+ assert.match(String(withUrl.json.error), /^An X trending library has no URL/);
+ const badCap = await call(create, { fields: { ...fields, xTrendingMaxPosts: 500 } });
+ assert.match(String(badCap.json.error), /post cap is a whole number, 1–200/);
+ assert.equal(await exists(path.join(ROOT, "channels", "made-trending")), false);
+});
+
+test("the marker cannot be switched off: no create or patch changes a library's kind, platform or URL", async () => {
+ const fields = { name: "Video trending", handling: "transcribe", platform: "x-trending" };
+ const video = await call(create, { fields: { ...fields, sourceKind: "video" } });
+ assert.equal(video.status, 400);
+ assert.match(String(video.json.error), /An X trending library is a posts channel: its kind cannot be "video"/);
+ assert.equal(await exists(path.join(ROOT, "channels", "video-trending")), false);
+ const before = await readFile(path.join(lib, "config.json"), "utf8");
+ for (const [patch, sentence] of [
+ [{ sourceKind: "video" }, /its kind cannot be "video"/],
+ [{ url: "https://x.com/example" }, /An X trending library has no URL/],
+ [{ platform: "youtube" }, /is an X trending library and stays one/],
+ [{ platform: "", url: "https://www.youtube.com/@example/videos", sourceKind: "video" }, /is an X trending library and stays one/],
+ ] as const) {
+ const r = await call(configure, { slug: "trending", patch });
+ assert.equal(r.status, 400, JSON.stringify(patch));
+ assert.match(String(r.json.error), sentence, JSON.stringify(patch));
+ }
+ assert.equal(await readFile(path.join(lib, "config.json"), "utf8"), before, "the config is untouched");
+});
+
+test("Configure cannot turn a library into an ordinary channel, an account into a library, or put a library on a site", async () => {
+ const unmade = await call(configure, { slug: "trending", patch: { platform: "twitter", socialHandle: "example" } });
+ assert.equal(unmade.status, 400);
+ assert.match(String(unmade.json.error), /trending is an X trending library and stays one/);
+ const made = await call(configure, { slug: "account-x", patch: { platform: "x-trending", url: "" } });
+ assert.equal(made.status, 400);
+ assert.match(String(made.json.error), /Configure cannot make it one/);
+ const onSite = await call(configure, { slug: "trending", sites: [{ siteId: "demo-site", groupId: "default" }] });
+ assert.equal(onSite.status, 400);
+ assert.equal(onSite.json.error, "trending is an X trending library: it is private, and never put on a site.");
+});
diff --git a/editor/app/api/ops/read-x-trending/route.ts b/editor/app/api/ops/read-x-trending/route.ts
@@ -0,0 +1,65 @@
+import { readXTrendingAction } from "../../../channels/[slug]/xTrendingActions";
+import { jobResponse, ops, optBool, optPositiveInt, optString, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, url, topic?, scrolls?, posts?, probe?, headed? } -> { ok: true, jobId }
+// POST { slug, reparse: "<readId>", topic? } -> { ok: true, jobId }
+//
+// ONE X trending page (https://x.com/i/trending/<number>) read into `slug`,
+// an X trending library (a private posts channel made with platform
+// "x-trending"), as ONE `read-x-trending` job on X's queue: the page is
+// opened in the connected X profile's browser, every GraphQL answer the page
+// itself fetched is saved raw with a screenshot
+// (channels/<slug>/trending/reads/<readId>/), and the posts are parsed from
+// the saved file and written as the library's posts under a topic. A read
+// lists posts; it archives no media and no thread.
+//
+// topic the 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 it.
+// scrolls at most this many moves to the bottom of the page (1–20; the
+// channel's cap, else 8). posts: stop once this many are seen
+// (1–200; else 60). A read also stops after two scrolls that
+// brought nothing new, and at once on a 429 or a login wall.
+// probe save the capture and its summary; write no post.
+// headed open a window on the editor's desktop instead of a headless one.
+// reparse a saved read's id: its capture parsed again, OFFLINE (a
+// `reparse-x-trending` job; X is asked nothing, so no fresh jar).
+//
+// The log ends with `@@read-x-trending {ok, slug, mode, url, trendId, read,
+// outcome, stop?, scrolls?, responses, operations, posts: {onPage, added},
+// topic?, sentence, error?}` — operation NAMES and SIZES, never a body. A
+// capture with no post the parser knows ends ok, "read saved, nothing
+// recognised".
+//
+// Every refusal is the action's own sentence: no such channel, not a
+// library, not a trending page URL, a cap out of range, no connected X
+// profile, a Connect or Refresh of X in flight, a stale cookie jar or a
+// raised X alert (the network guard), a saved read that is not there.
+export async function POST(request: Request) {
+ return ops(
+ request,
+ ["slug", "url", "reparse", "topic", "scrolls", "posts", "probe", "headed"],
+ async (body) => {
+ const url = optString(body, "url");
+ const reparse = optString(body, "reparse");
+ const topic = optString(body, "topic");
+ const scrolls = optPositiveInt(body, "scrolls");
+ const posts = optPositiveInt(body, "posts");
+ const probe = optBool(body, "probe");
+ const headed = optBool(body, "headed");
+ return jobResponse(
+ await readXTrendingAction({
+ slug: reqSlug(body, "slug"),
+ ...(url !== undefined ? { url } : {}),
+ ...(reparse !== undefined ? { reparse } : {}),
+ ...(topic !== undefined ? { topic } : {}),
+ ...(scrolls !== undefined ? { scrolls } : {}),
+ ...(posts !== undefined ? { posts } : {}),
+ ...(probe ? { probe: true } : {}),
+ ...(headed ? { headed: true } : {}),
+ }),
+ );
+ },
+ );
+}
diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts
@@ -0,0 +1,61 @@
+import path from "node:path";
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store";
+import { opsAuth, opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/trending?slug=<library>[&topic=<topicId>][&limit=<n>]
+// -> { ok, slug, name, topics: [{id, title, posts, sources: [{trendId, url,
+// title?, summary?, reads, lastReadAt}]}],
+// posts: [{id, author, authorName?, createdAt, url, text,
+// media: {count, kinds, thumbnail?}, topic,
+// reads: [{read, trendId, at}], judgement?}],
+// total, reads: [<readId>, …] }
+//
+// An X trending library's topics and posts (lane x-trending) — `pnpm ops get
+// trending <slug>` and the MCP's x_trending_topics / x_trending_posts. Read
+// from the library's own files and its posts shards (lib/xTrending/store.ts):
+// a library is in no index build, so nothing here needs one. `topic` narrows
+// the posts to one topic; `limit` (default 100, at most 500) caps them, the
+// newest read's first, in page order; `total` is the count before the cap.
+//
+// Everything a list view needs per post. `media.thumbnail` is the first
+// captured picture's path relative to the channel
+// (`trending/posts-media/<id>/<name>` — a library's media is kept under trending/,
+// and no route serves it yet), present once the post is captured; `judgement` ({state: keep | drop | undecided, note?, by:
+// agent | operator, at}) once it has one (written by `judge-trending`, a later
+// slice). NEVER the raw capture, a cookie or a token.
+export async function GET(request: Request) {
+ const denied = opsAuth(request);
+ if (denied) return denied;
+ const sp = new URL(request.url).searchParams;
+ for (const key of sp.keys()) {
+ if (!["slug", "topic", "limit"].includes(key)) return opsFail(`unknown parameter "${key}" (slug, topic, limit)`);
+ }
+ const slug = sp.get("slug") ?? "";
+ if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ const topic = sp.get("topic") ?? undefined;
+ let limit: number | undefined;
+ if (sp.get("limit") !== null) {
+ limit = Number(sp.get("limit"));
+ if (!Number.isInteger(limit) || limit < 1 || limit > X_TRENDING_LIST_MAX) {
+ return opsFail(`"limit" is a whole number, 1–${X_TRENDING_LIST_MAX}`);
+ }
+ }
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return opsFail(`No such channel: ${slug}`, 404);
+ if (!isXTrendingChannel(config)) return opsFail(NOT_AN_X_TRENDING_LIBRARY(slug));
+ const listing = await listXTrending(path.join(paths.channelsDir, slug), {
+ ...(topic ? { topic } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ if (topic && !listing.topics.some((t) => t.id === topic)) {
+ return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`);
+ }
+ return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing });
+}
diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import {
+ X_TRENDING_MAX_POSTS,
+ X_TRENDING_MAX_SCROLLS,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
+import type { XTrendingListing } from "yt-dlp-transcript-common/lib/xTrending/store";
+import { cancelJobAction } from "../../../jobs/actions";
+import { readXTrendingAction } from "../xTrendingActions";
+
+// An X trending library's page (lane x-trending, slice 1): read a trending
+// page into it (`read-x-trending`, one job on X's queue), parse a saved read
+// again, and the library by topic — each post's author, words, media by kind
+// and when it was read. Listing only: archiving a post and judging it are
+// later slices. Everything here is `pnpm ops read-x-trending` / `get trending`.
+export function XTrendingPanel({
+ slug,
+ listing,
+ limits,
+}: {
+ slug: string;
+ listing: XTrendingListing;
+ limits: { scrolls: number; posts: number };
+}) {
+ const [url, setUrl] = useState("");
+ const [topic, setTopic] = useState("");
+ const [scrolls, setScrolls] = useState("");
+ const [posts, setPosts] = useState("");
+ const [probe, setProbe] = useState(false);
+ const [headed, setHeaded] = useState(false);
+ const [reparse, setReparse] = useState(listing.reads[0] ?? "");
+ const input = "rounded border border-border bg-card px-2 py-1 text-sm";
+ const num = (v: string) => (v.trim() ? Number(v) : undefined);
+ const byTopic = (id: string) => listing.posts.filter((p) => p.topic === id);
+ return (
+ <div className="flex flex-col gap-6">
+ <section aria-label="read a trending page" className="flex flex-col gap-3 rounded-lg border border-border p-3">
+ <h3 className="text-sm font-semibold">Read a trending page</h3>
+ <span data-x-trending-private="" className="text-xs text-muted-foreground">
+ Private: on no site, in no build, not in search.
+ </span>
+ <input
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ aria-label="trending page URL"
+ placeholder="https://x.com/i/trending/…"
+ className={`${input} w-[32rem] max-w-full font-mono`}
+ />
+ <div className="flex flex-wrap items-end gap-3 text-sm">
+ <label className="flex flex-col gap-1">
+ <span className="font-medium">Topic</span>
+ <input
+ value={topic}
+ onChange={(e) => setTopic(e.target.value)}
+ aria-label="topic"
+ list="x-trending-topics"
+ placeholder="its own, or a new name"
+ className={`${input} w-64`}
+ />
+ <datalist id="x-trending-topics">
+ {listing.topics.map((t) => (
+ <option key={t.id} value={t.title} />
+ ))}
+ </datalist>
+ </label>
+ <label className="flex flex-col gap-1">
+ <span className="font-medium">Scrolls</span>
+ <input
+ type="number"
+ min={1}
+ max={X_TRENDING_MAX_SCROLLS}
+ value={scrolls}
+ onChange={(e) => setScrolls(e.target.value)}
+ aria-label="scrolls"
+ placeholder={String(limits.scrolls)}
+ className={`${input} w-20`}
+ />
+ </label>
+ <label className="flex flex-col gap-1">
+ <span className="font-medium">Posts</span>
+ <input
+ type="number"
+ min={1}
+ max={X_TRENDING_MAX_POSTS}
+ value={posts}
+ onChange={(e) => setPosts(e.target.value)}
+ aria-label="posts"
+ placeholder={String(limits.posts)}
+ className={`${input} w-20`}
+ />
+ </label>
+ <label className="flex items-center gap-2" title="Save the page's answers and a summary; write no post">
+ <input type="checkbox" checked={probe} onChange={(e) => setProbe(e.target.checked)} />
+ Probe (save only)
+ </label>
+ <label className="flex items-center gap-2" title="Open a browser window on the editor's machine instead of a headless one">
+ <input type="checkbox" checked={headed} onChange={(e) => setHeaded(e.target.checked)} />
+ In a window
+ </label>
+ </div>
+ <StreamActionLog
+ trigger={() =>
+ readXTrendingAction({
+ slug,
+ url: url.trim(),
+ ...(topic.trim() ? { topic: topic.trim() } : {}),
+ ...(num(scrolls) !== undefined ? { scrolls: num(scrolls) } : {}),
+ ...(num(posts) !== undefined ? { posts: num(posts) } : {}),
+ ...(probe ? { probe: true } : {}),
+ ...(headed ? { headed: true } : {}),
+ })
+ }
+ cancelAction={cancelJobAction}
+ buttonLabel="Read trending page"
+ runningLabel="Reading…"
+ label={`Read a trending page into ${slug}`}
+ disabled={!url.trim()}
+ />
+ {listing.reads.length > 0 && (
+ <div className="flex flex-col gap-2 border-t border-border pt-3">
+ <h4 className="text-sm font-semibold">Parse a saved read again</h4>
+ <select
+ value={reparse}
+ onChange={(e) => setReparse(e.target.value)}
+ aria-label="saved read"
+ className={`${input} w-80 font-mono`}
+ >
+ {listing.reads.map((id) => (
+ <option key={id} value={id}>
+ {id}
+ </option>
+ ))}
+ </select>
+ <StreamActionLog
+ trigger={() =>
+ readXTrendingAction({ slug, reparse, ...(topic.trim() ? { topic: topic.trim() } : {}) })
+ }
+ cancelAction={cancelJobAction}
+ buttonLabel="Parse again (asks X nothing)"
+ runningLabel="Parsing…"
+ label={`Parse a saved read of ${slug} again`}
+ disabled={!reparse}
+ />
+ </div>
+ )}
+ </section>
+ <section aria-label="trending topics" className="flex flex-col gap-4">
+ <h3 className="text-sm font-semibold">
+ Topics <span className="font-normal text-muted-foreground">· {listing.total} posts</span>
+ </h3>
+ {listing.topics.length === 0 && (
+ <span className="text-sm text-muted-foreground">No topic yet.</span>
+ )}
+ {listing.topics.map((t) => (
+ <article key={t.id} data-x-trending-topic={t.id} className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <h4 className="text-sm font-semibold">
+ {t.title} <span className="font-normal text-muted-foreground">· {t.posts} posts</span>
+ </h4>
+ <ul className="flex flex-col gap-0.5 text-xs text-muted-foreground">
+ {t.sources.map((s) => (
+ <li key={s.trendId}>
+ <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline">
+ {s.url}
+ </a>{" "}
+ · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""}
+ </li>
+ ))}
+ </ul>
+ <ol className="flex flex-col divide-y divide-border">
+ {byTopic(t.id).map((p) => (
+ <li key={p.id} data-x-trending-post={p.id} className="flex flex-col gap-1 py-2 text-sm">
+ <span className="text-xs text-muted-foreground">
+ <a href={p.url} target="_blank" rel="noreferrer" className="font-medium text-foreground underline">
+ @{p.author}
+ </a>
+ {p.authorName ? ` (${p.authorName})` : ""} · {p.createdAt.slice(0, 16).replace("T", " ")} UTC
+ {p.media.count > 0
+ ? ` · ${p.media.count} media${p.media.kinds.length ? ` (${p.media.kinds.join(", ")})` : ""}`
+ : ""}
+ {p.reads.length > 1 ? ` · on ${p.reads.length} reads` : ""}
+ </span>
+ <span className="whitespace-pre-wrap">{p.text}</span>
+ </li>
+ ))}
+ </ol>
+ </article>
+ ))}
+ {listing.total > listing.posts.length && (
+ <span className="text-xs text-muted-foreground">
+ {listing.posts.length} of {listing.total} posts shown.
+ </span>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -42,6 +42,9 @@ import { waybackLiveState } from "./waybackLiveState";
import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config";
+import { isXTrendingChannel, xTrendingLimits } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store";
+import { XTrendingPanel } from "./components/XTrendingPanel";
import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk";
import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads";
import { XSearchLeadsPanel } from "./components/XSearchLeadsPanel";
@@ -243,21 +246,34 @@ export default async function ChannelDetailPage({
// An X SEARCH channel (release 38): its query, its walk and its leads.
const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null;
const leads = xSearch ? await readXSearchLeads(paths, slug) : null;
+ // AN X TRENDING LIBRARY (lane x-trending): its topics and posts, read from
+ // its own files (it is in no index), and the caps a read would use.
+ const trending = isXTrendingChannel(config)
+ ? {
+ listing: await listXTrending(channelRoot, { limit: X_TRENDING_LIST_MAX }),
+ limits: (() => {
+ const l = xTrendingLimits(config.xTrending);
+ return l.ok ? l.limits : { scrolls: 8, posts: 60 };
+ })(),
+ }
+ : null;
// A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new and,
// when the full-history walk is part-way, Resume backfill — never a forum
// thread's (its own two walks) or an X search's (one walk).
- const timeline = !forumThread && !xSearch ? timelineWalks(fetchState) : null;
+ const timeline = !forumThread && !xSearch && !trending ? timelineWalks(fetchState) : null;
// ACCOUNT ACTIVITY (lane x-console): posts per day and the long silences,
// from the stored posts — every posts channel but a Wayback pages one
// (its records are captures) and an X search (its posts are many
// accounts' answers to a query, not one account's activity). Streamed
// behind its own Suspense boundary, read through the cached light reader
// (lib/postTimes-server.ts), so the page never waits on the posts.
- const showActivity = !isWaybackPagesChannel(config) && !xSearch && postCount >= 2;
+ const showActivity = !isWaybackPagesChannel(config) && !xSearch && !trending && postCount >= 2;
return (
<div className="flex flex-col gap-6">
<RunningJobsList jobs={socialRunningJobs} hideChannelSlug />
- {wayback ? (
+ {trending ? (
+ <XTrendingPanel slug={slug} listing={trending.listing} limits={trending.limits} />
+ ) : wayback ? (
<>
<WaybackPagesPanel
slug={slug}
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -22,6 +22,7 @@ import {
import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config";
+import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "yt-dlp-transcript-common/lib/xTrending/config";
import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch";
import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts";
import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
@@ -41,6 +42,8 @@ import {
retryOnBlockProblem,
type RetryOnBlock,
} from "yt-dlp-transcript-common/lib/forumWalk";
+import { channelPlatformOf, xCaptureStartRefusal } from "../../lib/cookieRefreshGuard";
+import { platformCooldownRemainingMs } from "yt-dlp-transcript-common/jobs/downloadBackoff";
import { saveSettings } from "../../settings/saveSettings";
import { isUtcDay } from "yt-dlp-transcript-common/social/olderBackfill";
import {
@@ -236,6 +239,8 @@ export async function fetchPostsAction(
// A Wayback pages channel is never fetched: its captures are imported one
// by one (import-page), as chosen — no unattended crawling (release 37).
if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED };
+ // An X trending library has no timeline: its pages are read one at a time.
+ if (isXTrendingChannel(config)) return { ok: false, info: true, error: X_TRENDING_NOT_FETCHED(slug) };
// An X search channel's one walk is its search windows (release 38).
if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL };
if (backfill) {
@@ -406,6 +411,16 @@ export async function capturePostsAction(
},
},
fn: async (onLog, signal, _progress, ctx) => {
+ // AN X CAPTURE'S START (lib/cookieRefreshGuard.ts xCaptureStartRefusal),
+ // decided by the channel's PLATFORM, never by the queue this job was
+ // put on: X cooling down after a rate limit (a trending read's 429)
+ // holds it; and while X's Connect or Refresh holds the profile, a
+ // capture that would open its browser fails with a sentence instead of
+ // with Chromium's profile-lock error.
+ const platform = pages ? null : channelPlatformOf(slug);
+ const cooling = platform === "twitter" ? await platformCooldownRemainingMs("twitter", paths).catch(() => 0) : 0;
+ const held = xCaptureStartRefusal({ platform, shots, avatarsOnly, contextOnly }, cooling);
+ if (held) throw new Error(held);
const result = await capturePosts({
paths,
slug,
diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts
@@ -0,0 +1,88 @@
+"use server";
+
+// READ A TRENDING PAGE INTO AN X TRENDING LIBRARY (lane x-trending, slice 1):
+// the channel page's "Read a trending page" and `pnpm ops read-x-trending`,
+// one body (common/controller/readXTrending.ts).
+//
+// Refused HERE, before a job exists, with the controller's sentences: no such
+// channel, not a library, a URL that is not a trending page, a cap out of
+// range, no connected X profile, a saved read that is not there — and a
+// Connect or Refresh of X in flight, which holds the profile's browser
+// (lib/cookieRefreshGuard.ts). runManagedFunction then asks the network guard
+// (the fresh-jar rule, the X alert) at enqueue and at the job's start, and X's
+// queue spaces it from every other X job.
+//
+// A read is a `read-x-trending` job on X's queue; `reparse` (a saved capture
+// parsed again, nothing asked of X) a `reparse-x-trending` job on the same
+// queue, so neither writes the library's posts beside the other. The log ends
+// with `@@read-x-trending {…}`.
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ planReadXTrending,
+ READ_X_TRENDING_KIND,
+ READ_X_TRENDING_RESULT_MARKER,
+ REPARSE_X_TRENDING_KIND,
+ reparseXTrendingRead,
+ runXTrendingRead,
+ X_TRENDING_QUEUE,
+ type ReadXTrendingAsk,
+} from "yt-dlp-transcript-common/controller/readXTrending";
+import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser";
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { xPressInFlight } from "../../lib/cookieRefreshGuard";
+
+export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<StreamActionResult> {
+ const paths = getPaths();
+ // A read of this library queued or running: a reparse of a record still
+ // marked "started" is then refused (the read has not ended).
+ const readInFlight = async () =>
+ getRegistry()
+ .list()
+ .some((j) => j.kind === READ_X_TRENDING_KIND && j.channelSlug === ask.slug && (j.status === "queued" || j.status === "running"));
+ const planned = await planReadXTrending(paths, ask, { readInFlight });
+ if (!planned.ok) return { ok: false, error: planned.error };
+ const plan = planned.plan;
+ const done = (onLog: (line: string) => void, result: { ok: boolean; error?: string }) => {
+ onLog(`${READ_X_TRENDING_RESULT_MARKER}${JSON.stringify(result)}`);
+ safeRevalidate([`/channels/${plan.slug}`]);
+ if (!result.ok) throw new Error(result.error ?? "The trending page was not read");
+ };
+ if (plan.mode === "reparse") {
+ return runManagedFunction({
+ kind: REPARSE_X_TRENDING_KIND,
+ queueKey: X_TRENDING_QUEUE,
+ paths,
+ channelSlug: plan.slug,
+ fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog })),
+ });
+ }
+ const busy = xPressInFlight();
+ if (busy) return { ok: false, error: busy };
+ // Under the e2e test server only, the fake browser (fakeXProfileBrowser.ts
+ // says how it is gated) and its short waits; everywhere else the real
+ // profile and X's request gap.
+ const chromium = fakeXProfileChromium(paths.transcriptsDir);
+ return runManagedFunction({
+ kind: READ_X_TRENDING_KIND,
+ queueKey: X_TRENDING_QUEUE,
+ paths,
+ channelSlug: plan.slug,
+ fn: async (onLog, signal) =>
+ done(
+ onLog,
+ await runXTrendingRead({
+ paths,
+ plan,
+ onLog,
+ signal,
+ deps: {
+ profileBusy: () => xPressInFlight(),
+ ...(chromium ? { chromium, pauseMs: () => 50 } : {}),
+ },
+ }),
+ ),
+ });
+}
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -42,6 +42,7 @@ import {
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site";
import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config";
+import { X_TRENDING_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/xTrending/config";
import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings";
import {
LANES,
@@ -288,6 +289,10 @@ export async function createChannelFromForm(
if (config.xSearch && requests && requests.length > 0) {
return fail(X_SEARCH_NOT_ON_A_SITE(slug));
}
+ // Nor an X trending library (lane x-trending): private.
+ if (config.xTrending && requests && requests.length > 0) {
+ return fail(X_TRENDING_NOT_ON_A_SITE(slug));
+ }
if (requests) {
siteWrites = planSiteMembershipWrites(paths, slug, requests);
}
@@ -374,12 +379,32 @@ export async function updateChannelAction(
const paths = getPaths();
const existing = await readChannelConfig(paths, slug);
if (!existing) return { error: `Channel "${slug}" not found`, values };
+ // A library is made one when it is created and stays one (lane x-trending).
+ // Asked of the platform choice before the parse, so the refusal is this
+ // sentence and not whatever the other platform's fields would complain of.
+ const libraryProblem = (becomes: boolean) =>
+ Boolean(existing.xTrending) === becomes
+ ? null
+ : existing.xTrending
+ ? `${slug} is an X trending library and stays one: its platform cannot be changed. Delete the channel to be rid of it.`
+ : `${slug} is not an X trending library, and Configure cannot make it one: create a new channel with platform "X trending library".`;
+ const asked = libraryProblem(String(formData.get("platform") ?? "") === "x-trending");
+ if (asked) return { error: asked, values };
let parsed;
try {
parsed = parseChannelForm(formData, { stored: existing });
} catch (e) {
return { error: (e as Error).message, values };
}
+ // And of the parsed config: whatever the fields said, the marker neither
+ // appears nor disappears, and a library stays a posts channel on X, no URL.
+ const parsedProblem =
+ libraryProblem(Boolean(parsed.config.xTrending)) ??
+ (parsed.config.xTrending &&
+ (parsed.config.platform !== "twitter" || parsed.config.sourceKind !== "social" || parsed.config.url)
+ ? libraryProblem(false)
+ : null);
+ if (parsedProblem) return { error: parsedProblem, values };
// A stored value today's checks refuse, saved unchanged: the save stands.
// The form has no place for a warning, so the server log says it.
for (const w of parsed.warnings) console.warn(`Channel ${slug} saved with a warning: ${w}`);
@@ -394,6 +419,9 @@ export async function updateChannelAction(
if (parsed.config.xSearch && requests && requests.length > 0) {
return { error: X_SEARCH_NOT_ON_A_SITE(slug), values };
}
+ if (parsed.config.xTrending && requests && requests.length > 0) {
+ return { error: X_TRENDING_NOT_ON_A_SITE(slug), values };
+ }
if (requests) {
siteWrites = planSiteMembershipWrites(paths, slug, requests);
}
diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx
@@ -45,6 +45,7 @@ import { waybackTargetFromUrl, waybackTargetHost } from "yt-dlp-transcript-commo
import { WaybackTargetsField } from "./WaybackTargetsField";
import { XSearchFields } from "./XSearchFields";
import { isXSearchUrl, xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config";
+import { XTrendingFields } from "./XTrendingFields";
import { MANUAL_DOWNLOADS_TEXT } from "yt-dlp-transcript-common/lib/manualDownloads";
import { SKIP_SHORTS_TEXT } from "yt-dlp-transcript-common/lib/skipShorts";
import { probeChannelUrlAction } from "../actions";
@@ -213,7 +214,7 @@ export function ChannelForm({
c?.handling === "transcribe" ? "transcribe" : "youtube",
);
const [handlingTouched, setHandlingTouched] = useState(false);
- const [platform, setPlatform] = useState<string>(c?.xSearch ? "x-search" : (c?.platform ?? ""));
+ const [platform, setPlatform] = useState<string>(c?.xTrending ? "x-trending" : c?.xSearch ? "x-search" : (c?.platform ?? ""));
const [platformTouched, setPlatformTouched] = useState(false);
// Social sources are ingested into the posts corpus, not the video pipeline,
// so every video-only control below is hidden for them. In edit mode this is
@@ -227,9 +228,12 @@ export function ChannelForm({
: isSocialPlatform(platform as Platform) ||
isSocialPlatform(detectPlatform(url)) ||
isWaybackPagesUrl(url) ||
- platform === "x-search";
+ platform === "x-search" ||
+ platform === "x-trending";
// An X search channel (release 38): a query across accounts, never on a site.
const isXSearch = isEdit ? Boolean(c?.xSearch) : !creatingLocal && platform === "x-search";
+ // An X trending library (lane x-trending): private, no URL, never on a site.
+ const isXTrending = isEdit ? Boolean(c?.xTrending) : !creatingLocal && platform === "x-trending";
// A Wayback pages channel (release 37): captures of pages, no fetcher; its
// scope is its targets.
const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage";
@@ -376,7 +380,11 @@ export function ChannelForm({
)}
</Section>
<Section title="Sites">
- {isXSearch ? (
+ {isXTrending ? (
+ <span data-x-trending-no-site="" className="text-xs text-muted-foreground">
+ An X trending library is private: it is never put on a site.
+ </span>
+ ) : isXSearch ? (
<span data-x-search-no-site="" className="text-xs text-muted-foreground">
An X search channel is never put on a site.
</span>
@@ -456,7 +464,7 @@ export function ChannelForm({
<SeededSelect
state={state}
name="platform"
- initial={c?.xSearch ? "x-search" : (c?.platform ?? "")}
+ initial={c?.xTrending ? "x-trending" : c?.xSearch ? "x-search" : (c?.platform ?? "")}
className="rounded border border-border bg-card px-2 py-1 text-sm"
>
<option value="">Auto (detect from URL)</option>
@@ -469,6 +477,7 @@ export function ChannelForm({
<option value="bitchute">BitChute</option>
<option value="twitter">X / Twitter (posts)</option>
<option value="x-search">X search (posts from any account)</option>
+ <option value="x-trending">X trending library (private)</option>
<option value="bluesky">Bluesky (posts)</option>
<option value="xenforo">Forum thread — XenForo (posts)</option>
<option value="webpage">Archived pages (Wayback Machine, archive.today)</option>
@@ -593,6 +602,7 @@ export function ChannelForm({
<option value="bitchute">BitChute</option>
<option value="twitter">X / Twitter (posts)</option>
<option value="x-search">X search (posts from any account)</option>
+ <option value="x-trending">X trending library (private)</option>
<option value="bluesky">Bluesky (posts)</option>
<option value="xenforo">Forum thread — XenForo (posts)</option>
<option value="webpage">Archived pages (Wayback Machine, archive.today)</option>
@@ -607,7 +617,11 @@ export function ChannelForm({
<legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
On create
</legend>
- {isWaybackPages ? (
+ {isXTrending ? (
+ <span className="text-xs text-muted-foreground">
+ Nothing is fetched on create: read a trending page from the channel page.
+ </span>
+ ) : isWaybackPages ? (
<span className="text-xs text-muted-foreground">
Nothing is fetched on create: import captures from the channel page.
</span>
@@ -688,7 +702,10 @@ export function ChannelForm({
{isSocial && isXSearch && (
<XSearchFields {...(isEdit ? (c?.xSearch ? { initial: c.xSearch } : {}) : { derivedFrom: url })} />
)}
- {isSocial && !isWaybackPages && !isXSearch && (
+ {isSocial && isXTrending && (
+ <XTrendingFields {...(isEdit && c?.xTrending ? { initial: c.xTrending } : {})} />
+ )}
+ {isSocial && !isWaybackPages && !isXSearch && !isXTrending && (
<>
{/* A social source is ingested into the posts corpus, so it carries
its fetcher + handle instead of any of the video controls. */}
diff --git a/editor/app/channels/components/XTrendingFields.tsx b/editor/app/channels/components/XTrendingFields.tsx
@@ -0,0 +1,53 @@
+// An X trending library's fields on the channel form (lane x-trending): the
+// caps a read of a trending page uses when the read names none. Posted as
+// xTrendingMaxScrolls / xTrendingMaxPosts; parseChannelForm refuses a value
+// out of range with a sentence. Blank is the default.
+
+import {
+ X_TRENDING_DEFAULT_POSTS,
+ X_TRENDING_DEFAULT_SCROLLS,
+ X_TRENDING_MAX_POSTS,
+ X_TRENDING_MAX_SCROLLS,
+ type XTrendingConfig,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
+
+export function XTrendingFields({ initial }: { initial?: XTrendingConfig }) {
+ const input = "w-28 rounded border border-border bg-card px-2 py-1 text-sm";
+ return (
+ <fieldset data-x-trending-fields="" className="flex flex-col gap-3 rounded-md border border-border px-3 py-2">
+ <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ X trending library
+ </legend>
+ <input type="hidden" name="sourceKind" value="social" />
+ <span className="text-xs text-muted-foreground">
+ Private. Each trending page is read on the channel page, one job at a time on X's queue.
+ </span>
+ <div className="flex flex-wrap gap-4">
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="font-medium">Scrolls per read</span>
+ <input
+ type="number"
+ name="xTrendingMaxScrolls"
+ min={1}
+ max={X_TRENDING_MAX_SCROLLS}
+ defaultValue={initial?.maxScrolls ?? ""}
+ placeholder={String(X_TRENDING_DEFAULT_SCROLLS)}
+ className={input}
+ />
+ </label>
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="font-medium">Posts per read</span>
+ <input
+ type="number"
+ name="xTrendingMaxPosts"
+ min={1}
+ max={X_TRENDING_MAX_POSTS}
+ defaultValue={initial?.maxPosts ?? ""}
+ placeholder={String(X_TRENDING_DEFAULT_POSTS)}
+ className={input}
+ />
+ </label>
+ </div>
+ </fieldset>
+ );
+}
diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts
@@ -79,6 +79,9 @@ export const CHANNEL_FORM_VALUES = [
"xSearchWindowMonths",
"xSearchLang",
"xSearchExclude",
+ // An X trending library's caps (lane x-trending): whole numbers, "" clears.
+ "xTrendingMaxScrolls",
+ "xTrendingMaxPosts",
] as const;
export type ChannelFormFlag = (typeof CHANNEL_FORM_FLAGS)[number];
@@ -108,7 +111,9 @@ export function channelConfigToFormData(config: ChannelConfig): FormData {
fd.set("name", config.name ?? "");
fd.set("handling", config.handling ?? "transcribe");
put(fd, "url", config.url);
- put(fd, "platform", config.platform);
+ // A trending library is the platform CHOICE "x-trending" on the form (its
+ // stored platform is "twitter"): parseChannelForm keeps it a library by it.
+ put(fd, "platform", config.xTrending ? "x-trending" : config.platform);
put(fd, "sourceKind", config.sourceKind);
put(fd, "postFetcher", config.postFetcher);
put(fd, "socialHandle", config.socialHandle);
@@ -156,6 +161,8 @@ export function channelConfigToFormData(config: ChannelConfig): FormData {
putNum(fd, "xSearchWindowMonths", config.xSearch?.windowMonths);
put(fd, "xSearchLang", config.xSearch?.lang);
if (config.xSearch?.exclude?.length) fd.set("xSearchExclude", JSON.stringify(config.xSearch.exclude));
+ putNum(fd, "xTrendingMaxScrolls", config.xTrending?.maxScrolls);
+ putNum(fd, "xTrendingMaxPosts", config.xTrending?.maxPosts);
// Ticked when the check is on: said so, or the platform's default (an
// Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch
// that does not name it keeps what the channel has.
diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts
@@ -434,3 +434,49 @@ test("a Rumble URL parses to platform rumble, and the create defaults fill what
assert.equal(none.cookiesFromBrowser, undefined);
assert.equal(none.ytdlpExtraArgs, undefined);
});
+
+// --- lane x-trending: the "X trending library" platform choice ---
+
+test("the X trending choice makes a library: X, social, no URL, no handle, no fetcher", () => {
+ const { config } = parseChannelForm(form({ handling: "transcribe", platform: "x-trending" }));
+ assert.equal(config.platform, "twitter");
+ assert.equal(config.sourceKind, "social");
+ assert.equal(config.url, undefined);
+ assert.equal(config.socialHandle, undefined);
+ assert.equal(config.postFetcher, undefined);
+ assert.deepEqual(config.xTrending, {});
+ assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("xTrending"));
+ const capped = parseChannelForm(
+ form({ handling: "transcribe", platform: "x-trending", xTrendingMaxScrolls: "4", xTrendingMaxPosts: "200" }),
+ ).config;
+ assert.deepEqual(capped.xTrending, { maxScrolls: 4, maxPosts: 200 });
+});
+
+test("a library refuses a URL and a cap out of range, in sentences", () => {
+ const refused = (fields: Record<string, string>) => () =>
+ parseChannelForm(form({ handling: "transcribe", platform: "x-trending", ...fields }));
+ assert.throws(refused({ url: "https://x.com/i/trending/1900000000000000001" }), /An X trending library has no URL/);
+ assert.throws(refused({ url: "https://x.com/example_user" }), /An X trending library has no URL/);
+ assert.throws(refused({ xTrendingMaxScrolls: "21" }), /scroll cap is a whole number, 1–20/);
+ assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–200/);
+ assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–200/);
+ // An ordinary X account is not a library.
+ assert.equal(parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config.xTrending, undefined);
+});
+
+test("a stored library round-trips through the Configure form, and a patch sets its caps", () => {
+ const stored = {
+ handling: "transcribe" as const,
+ name: "Trending",
+ sourceKind: "social" as const,
+ platform: "twitter" as const,
+ xTrending: { maxPosts: 40 },
+ };
+ const fd = channelConfigToFormData(stored);
+ assert.equal(fd.get("platform"), "x-trending");
+ assert.deepEqual(parseChannelForm(fd).config.xTrending, { maxPosts: 40 });
+ assert.equal(parseChannelForm(fd).config.platform, "twitter");
+ validateChannelFormPatch({ xTrendingMaxScrolls: 5, xTrendingMaxPosts: "" });
+ applyChannelFormPatch(fd, { xTrendingMaxScrolls: 5, xTrendingMaxPosts: "" });
+ assert.deepEqual(parseChannelForm(fd).config.xTrending, { maxScrolls: 5 });
+});
diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts
@@ -40,6 +40,12 @@ import {
xSearchUrl,
type XSearchConfig,
} from "yt-dlp-transcript-common/lib/xSearch/config";
+import {
+ X_TRENDING_HAS_NO_URL,
+ X_TRENDING_MAX_POSTS,
+ X_TRENDING_MAX_SCROLLS,
+ type XTrendingConfig,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
import { isCookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy";
import {
isDownloadFormatPreset,
@@ -112,6 +118,9 @@ export const CHANNEL_FORM_FIELDS = [
"mirror",
"wayback",
"xSearch",
+ // Lane x-trending: the library's caps. The marker itself is set at creation
+ // and a Configure save can neither add nor remove it (channels/actions.ts).
+ "xTrending",
] as const satisfies ReadonlyArray<keyof ChannelConfig>;
// Maps FormData -> ChannelConfig. Throws on invalid input so the server
@@ -142,8 +151,12 @@ export function parseChannelForm(
(isXSearchUrl(typedUrl) || (platformRaw === "twitter" && stringOrUndef(formData, "xSearchQuery") !== undefined)))
? parseXSearchFields(formData, typedUrl)
: undefined;
+ // AN X TRENDING LIBRARY (lane x-trending): the platform choice "X trending
+ // library". No URL (its pages are read one at a time), no account, no
+ // fetcher; private, never on a site.
+ const xTrending = platformRaw === X_TRENDING_PLATFORM_CHOICE ? parseXTrendingFields(formData, typedUrl) : undefined;
const url = xSearch ? xSearchUrl(xSearch.query) : typedUrl;
- const platform: Platform | undefined = xSearch
+ const platform: Platform | undefined = xSearch || xTrending
? "twitter"
: PLATFORM_VALUES.includes(platformRaw as Platform)
? (platformRaw as Platform)
@@ -157,8 +170,10 @@ export function parseChannelForm(
// explicit "social" wins, otherwise infer from the platform so a social URL
// pasted into the form does the right thing without a hidden field.
const sourceKindRaw = String(formData.get("sourceKind") ?? "").trim();
+ // A library is a posts channel whatever the request says of its kind (and
+ // parseXTrendingFields refused any other kind by name).
const sourceKind: ChannelConfig["sourceKind"] | undefined =
- sourceKindRaw === "social" || (!sourceKindRaw && isSocialPlatform(platform))
+ xTrending || sourceKindRaw === "social" || (!sourceKindRaw && isSocialPlatform(platform))
? "social"
: sourceKindRaw === "video"
? "video"
@@ -166,22 +181,24 @@ export function parseChannelForm(
// A search channel is walked by the one fetcher that can (gallery-dl).
const postFetcher = xSearch
? "x-gallery-dl"
+ : xTrending
+ ? undefined
: sourceKind === "social"
? stringOrUndef(formData, "postFetcher")
: undefined;
const socialHandleRaw =
- sourceKind === "social" && !xSearch ? stringOrUndef(formData, "socialHandle") : undefined;
+ sourceKind === "social" && !xSearch && !xTrending ? stringOrUndef(formData, "socialHandle") : undefined;
// A Wayback pages channel's scope: the form's target rows (one hidden JSON
// field), else one target derived from the URL.
const wayback = platform === "webpage" ? parseWaybackTargets(formData, url) : undefined;
const socialHandle =
socialHandleRaw?.replace(/^@/, "") ||
(wayback ? waybackTargetHost(wayback.targets[0]) : undefined) ||
- (sourceKind === "social" && url && !xSearch
+ (sourceKind === "social" && url && !xSearch && !xTrending
? (handleFromAccountUrl(url) ?? undefined)
: undefined);
// A search channel has no account: its query is what it archives.
- if (sourceKind === "social" && !socialHandle && !xSearch) {
+ if (sourceKind === "social" && !socialHandle && !xSearch && !xTrending) {
throw new Error(
"A social source needs an account handle (could not derive one from the URL)",
);
@@ -529,10 +546,41 @@ export function parseChannelForm(
if (mirrorOf.length > 0) config.mirror = { of: mirrorOf };
if (wayback) config.wayback = wayback;
if (xSearch) config.xSearch = xSearch;
+ if (xTrending) config.xTrending = xTrending;
return { name, slug, config, warnings };
}
+// The platform select's value for an X trending library: not a platform (the
+// channel's platform is "twitter"), a kind of X channel.
+export const X_TRENDING_PLATFORM_CHOICE = "x-trending";
+
+// An X trending library's marker and caps: the form's xTrendingMaxScrolls and
+// xTrendingMaxPosts (blank: the defaults). A URL is refused — the library has
+// none — and a cap out of range is refused, never clamped.
+function parseXTrendingFields(formData: FormData, url: string | undefined): XTrendingConfig {
+ if (url) throw new Error(X_TRENDING_HAS_NO_URL);
+ const kind = stringOrUndef(formData, "sourceKind");
+ if (kind !== undefined && kind !== "social") {
+ throw new Error(`An X trending library is a posts channel: its kind cannot be "${kind}".`);
+ }
+ const cap = (key: string, max: number, what: string): number | undefined => {
+ const raw = stringOrUndef(formData, key);
+ if (raw === undefined) return undefined;
+ const n = Number(raw);
+ if (!Number.isInteger(n) || n < 1 || n > max) {
+ throw new Error(`An X trending library's ${what} is a whole number, 1–${max}`);
+ }
+ return n;
+ };
+ const maxScrolls = cap("xTrendingMaxScrolls", X_TRENDING_MAX_SCROLLS, "scroll cap");
+ const maxPosts = cap("xTrendingMaxPosts", X_TRENDING_MAX_POSTS, "post cap");
+ return {
+ ...(maxScrolls !== undefined ? { maxScrolls } : {}),
+ ...(maxPosts !== undefined ? { maxPosts } : {}),
+ };
+}
+
// The platform select's value for an X search channel: not a platform (the
// channel's platform is "twitter"), a kind of X channel.
export const X_SEARCH_PLATFORM_CHOICE = "x-search";
diff --git a/editor/app/lib/cookieRefreshGuard.test.ts b/editor/app/lib/cookieRefreshGuard.test.ts
@@ -138,3 +138,106 @@ test("a throw before the press (finding the paths) never leaves the service mark
);
assert.equal(runningCookieActions([]).rumble, undefined);
});
+
+// --- lane x-trending: one browser on the X profile at a time ---
+
+test("X's Connect and Refresh are refused while a job holds the profile's browser; nothing else is", async () => {
+ const { xProfileJobRunning } = await import("./cookieRefreshGuard");
+ const at = Date.parse("2026-11-17T10:02:11Z");
+ const reading = () => [{ id: "J1", kind: "read-x-trending", queueKey: "platform:twitter", status: "running", queuedAt: 0, startedAt: at }];
+ const capturing = () => [{ id: "J2", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at }];
+ // The job's PLATFORM decides (review 2 N6), looked up by its channel.
+ const platformOf = (slug: string | undefined) => (slug === "acct-x" ? "twitter" : slug === "acct-bsky" ? "bluesky" : null);
+ let ran = 0;
+ const press = (service: string, action: "connect" | "refresh" | "recheck", jobs: () => never[]) =>
+ withCookieAction(service, action, async () => { ran++; return { ok: true as const }; }, () => ({ ok: true, message: "done" }), { paths, jobs, platformOf });
+ const refused = await press("x", "connect", reading as never);
+ assert.deepEqual(refused, {
+ ok: false,
+ busy: true,
+ error:
+ "X's connect opens the connected profile, and a job is using it: Read X trending page (J1, running since 10:02:11 UTC). " +
+ "Cancel it on /jobs or wait for it to finish, then press again.",
+ });
+ const refresh = await press("x", "refresh", capturing as never);
+ assert.match((refresh as { error: string }).error, /^X's refresh opens the connected profile, and a job is using it: Capture posts \(J2,/);
+ assert.equal(ran, 0);
+ // The refused press left no mark: X is not shown as running.
+ assert.equal(runningCookieActions([]).x, undefined);
+ // A queued read holds nothing yet; a capture on another platform's queue, a
+ // fetch on X's, a recheck of X and another service's press are not held.
+ const idle = [
+ { id: "J3", kind: "read-x-trending", queueKey: "platform:twitter", status: "queued", queuedAt: 0 },
+ { id: "J4", kind: "capture-posts", queueKey: "platform:bluesky", channelSlug: "acct-bsky", status: "running", queuedAt: 0 },
+ { id: "J5", kind: "fetch-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0 },
+ { id: "J6", kind: "read-x-trending", queueKey: "platform:twitter", status: "done", queuedAt: 0 },
+ // A Bluesky capture moved onto X's queue opens no X profile.
+ { id: "J7", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-bsky", status: "running", queuedAt: 0 },
+ // An X capture that takes no shot opens no browser.
+ { id: "J8", kind: "capture-posts", queueKey: "platform:twitter", channelSlug: "acct-x", status: "running", queuedAt: 0, spec: { params: { shots: false } } },
+ ];
+ assert.equal(xProfileJobRunning(idle, platformOf), null);
+ // A queue override does not hide a job that holds the profile (N6).
+ for (const hidden of [
+ { id: "J9", kind: "capture-posts", queueKey: "my-own-queue", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at },
+ { id: "J10", kind: "read-x-trending", queueKey: "elsewhere", status: "running", queuedAt: 0, startedAt: at },
+ { id: "J11", kind: "capture-posts", queueKey: "my-own-queue", channelSlug: "acct-x", status: "running", queuedAt: 0, startedAt: at, spec: { params: { shots: false, avatarsOnly: true } } },
+ ]) {
+ assert.equal(xProfileJobRunning([hidden], platformOf)?.jobId, hidden.id);
+ const r = await press("x", "connect", (() => [hidden]) as never);
+ assert.equal((r as { busy?: boolean }).busy, true, hidden.id);
+ }
+ assert.deepEqual(await press("x", "refresh", (() => idle) as never), { ok: true });
+ assert.deepEqual(await press("x", "recheck", reading as never), { ok: true });
+ assert.deepEqual(await press("rumble", "refresh", reading as never), { ok: true });
+ assert.equal(ran, 3);
+});
+
+test("a trending read is refused while X's Connect or Refresh is in flight, and only then", async () => {
+ const { xPressInFlight } = await import("./cookieRefreshGuard");
+ assert.equal(xPressInFlight(), null);
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const connecting = withCookieAction("x", "connect", async () => { await gate; return { ok: true as const }; }, () => ({ ok: true, message: "Connected." }), { paths, jobs: noJobs });
+ assert.match(
+ xPressInFlight() ?? "",
+ /^X's connect is running \(since \d\d:\d\d:\d\d UTC\) and holds the connected profile: read the trending page once it has finished\.$/,
+ );
+ // The same at an X capture's start (N6: by the job's platform, whatever
+ // its queue; a capture that takes no shot opens no browser).
+ const { xCaptureStartRefusal } = await import("./cookieRefreshGuard");
+ const now = Date.parse("2026-11-17T10:00:00Z");
+ assert.match(
+ xCaptureStartRefusal({ platform: "twitter" }, 0, now) ?? "",
+ /^X's connect is running \(since \d\d:\d\d:\d\d UTC\) and holds the connected profile: capture these posts once it has finished\.$/,
+ );
+ assert.match(xCaptureStartRefusal({ platform: "twitter", shots: false, contextOnly: true }, 0, now) ?? "", /^X's connect is running/);
+ assert.equal(xCaptureStartRefusal({ platform: "twitter", shots: false }, 0, now), null);
+ assert.equal(xCaptureStartRefusal({ platform: "bluesky" }, 0, now), null);
+ assert.equal(xCaptureStartRefusal({ platform: "xenforo" }, 15 * 60_000, now), null);
+ release();
+ await connecting;
+ assert.equal(xPressInFlight(), null);
+ assert.equal(xCaptureStartRefusal({ platform: "twitter" }, 0, now), null);
+ // N5: X cooling down after a rate limit holds an X capture too, shot or no
+ // shot (its media comes from X), and the sentence names the time.
+ assert.equal(
+ xCaptureStartRefusal({ platform: "twitter", shots: false }, 12 * 60_000, now),
+ "X answered a rate limit (429) a short while ago: no X capture starts before 10:12 UTC (12 min from now). Ask again then; nothing retries by itself.",
+ );
+ assert.match(xCaptureStartRefusal({ platform: "twitter" }, 1, now) ?? "", /no X capture starts before 10:00 UTC \(1 min from now\)/);
+ // A Refresh holds it as a Connect does.
+ let done!: () => void;
+ const hold = new Promise<void>((r) => (done = r));
+ const refreshing = withCookieAction("x", "refresh", async () => { await hold; return { ok: true as const }; }, () => ({ ok: true, message: "Cookies refreshed." }), { paths, jobs: noJobs });
+ assert.match(xCaptureStartRefusal({ platform: "twitter" }, 0, now) ?? "", /^X's refresh is running/);
+ done();
+ await refreshing;
+ // A recheck of X opens no profile: a read is not held by it.
+ let free!: () => void;
+ const wait = new Promise<void>((r) => (free = r));
+ const rechecking = withCookieAction("x", "recheck", async () => { await wait; return { ok: true as const }; }, () => ({ ok: true, message: "clean" }), { paths, jobs: noJobs });
+ assert.equal(xPressInFlight(), null);
+ free();
+ await rechecking;
+});
diff --git a/editor/app/lib/cookieRefreshGuard.ts b/editor/app/lib/cookieRefreshGuard.ts
@@ -12,6 +12,18 @@
// (noteServiceCookieAction, `.service-cookies.json` `actions`), which the
// screen shows as "last result".
//
+//
+// THE X PROFILE HAS ONE BROWSER AT A TIME (lane x-trending). X's Connect and
+// Refresh open the connected profile; so do the jobs that read X through it
+// (a trending-page read, a post capture: X_PROFILE_BROWSER_JOB_KINDS), which
+// X's queue already keeps one at a time among themselves. Two browsers on one
+// profile is a launch that fails with Chromium's own error, so each side is
+// refused with a sentence instead: a Connect or Refresh while such a job is
+// RUNNING (`xProfileJobRunning`; a queued one blocks nothing), and such a job
+// while a Connect or Refresh is in flight (`xPressInFlight`: the trending read
+// at enqueue and at its start, a post capture at its start).
+// Nothing else about Connect or Refresh changes.
+//
// The mark lives on globalThis (one per server process, like the registry).
import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
@@ -20,6 +32,14 @@ import { noteServiceCookieAction } from "yt-dlp-transcript-common/lib/serviceCoo
import { serviceLabel, type ServiceCookieActionKind } from "yt-dlp-transcript-common/lib/serviceCookies";
import type { CookieRunning } from "yt-dlp-transcript-common/lib/cookieStatus";
import { RECHECK_JOB_KIND } from "yt-dlp-transcript-common/controller/serviceCookieTimer";
+import path from "node:path";
+import {
+ READ_X_TRENDING_KIND,
+ xRateLimitHoldSentence,
+} from "yt-dlp-transcript-common/lib/xTrending/config";
+import { readJsonFileSync } from "yt-dlp-transcript-common/lib/jsonFile-server";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
+import { jobKindLabel } from "yt-dlp-transcript-common/jobs/jobKinds";
const QUEUE_PREFIX = "service-cookies:";
const KEY = Symbol.for("archilyzer.cookieRefresh.inflight");
@@ -29,7 +49,37 @@ function inflight(): Map<string, CookieRunning> {
return (g[KEY] ??= new Map());
}
-type JobLike = { id: string; kind: string; queueKey: string; status: string; queuedAt?: number; startedAt?: number };
+type JobLike = {
+ id: string;
+ kind: string;
+ queueKey: string;
+ status: string;
+ queuedAt?: number;
+ startedAt?: number;
+ channelSlug?: string;
+ spec?: { params?: Record<string, unknown> };
+};
+
+// The platform a job's channel is on, by its config.json (its `platform`,
+// else its URL's) — or null. What decides whether a capture is X's: the JOB'S
+// PLATFORM, never its queue key, which a caller may override (review 2 N6).
+export type PlatformOf = (channelSlug: string | undefined) => string | null;
+
+export const channelPlatformOf: PlatformOf = (slug) => {
+ if (!slug || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) return null;
+ const raw = readJsonFileSync(path.join(getPaths().channelsDir, slug, "config.json"));
+ if (!raw.ok || !raw.value || typeof raw.value !== "object") return null;
+ const c = raw.value as { platform?: unknown; url?: unknown };
+ if (typeof c.platform === "string" && c.platform) return c.platform;
+ return typeof c.url === "string" ? detectPlatform(c.url) : null;
+};
+
+// Whether a capture opens the X profile's browser: a shot (the default), the
+// avatars alone or the context alone. One that takes no shot only downloads
+// media with the exported jar.
+export function captureOpensBrowser(params: { shots?: unknown; avatarsOnly?: unknown; contextOnly?: unknown } | undefined): boolean {
+ return params?.shots !== false || params?.avatarsOnly === true || params?.contextOnly === true;
+}
// What is running per service now: the presses in flight here, and any
// recheck job queued or running on a service's queue.
@@ -51,6 +101,60 @@ export function runningCookieActions(
return out;
}
+// A job that holds the connected X profile's browser now: RUNNING (a queued
+// one holds nothing yet), and either a trending read, or a post capture of an
+// X channel that opens a browser — whatever queue it was put on.
+export function xProfileJobRunning(
+ jobs: readonly JobLike[] = getRegistry().list(),
+ platformOf: PlatformOf = channelPlatformOf,
+): { kind: string; since: string; jobId: string } | null {
+ for (const j of jobs) {
+ if (j.status !== "running") continue;
+ const holds =
+ j.kind === READ_X_TRENDING_KIND ||
+ (j.kind === "capture-posts" && captureOpensBrowser(j.spec?.params) && platformOf(j.channelSlug) === "twitter");
+ if (!holds) continue;
+ return { kind: j.kind, since: new Date(j.startedAt ?? j.queuedAt ?? Date.now()).toISOString(), jobId: j.id };
+ }
+ return null;
+}
+
+export function xProfileJobSentence(action: string, job: { kind: string; since: string; jobId: string }): string {
+ return (
+ `X's ${action} opens the connected profile, and a job is using it: ${jobKindLabel(job.kind)} ` +
+ `(${job.jobId}, running since ${job.since.slice(11, 19)} UTC). Cancel it on /jobs or wait for it to finish, then press again.`
+ );
+}
+
+// Why a job may not open the X profile now — a Connect or a Refresh of X is
+// in flight — or null. (A recheck opens no profile.)
+export function xPressInFlight(what = "read the trending page"): string | null {
+ const r = inflight().get("x");
+ if (!r || (r.action !== "connect" && r.action !== "refresh")) return null;
+ return (
+ `X's ${r.action} is running (since ${r.since.slice(11, 19)} UTC) and holds the connected profile: ` +
+ `${what} once it has finished.`
+ );
+}
+
+// WHY AN X POST CAPTURE DOES NOT START NOW, or null — asked at the job's
+// start (channels/[slug]/socialActions.ts), by the channel's PLATFORM:
+// - X is cooling down after a rate limit (review 2 N5; `cooldownMs` is
+// platformCooldownRemainingMs("twitter")): any X capture, shot or not —
+// its media comes from X too;
+// - X's Connect or Refresh holds the profile, and this capture would open
+// its browser.
+// A capture of another platform's posts is never held by either.
+export function xCaptureStartRefusal(
+ job: { platform: string | null | undefined; shots?: unknown; avatarsOnly?: unknown; contextOnly?: unknown },
+ cooldownMs: number,
+ now: number = Date.now(),
+): string | null {
+ if (job.platform !== "twitter") return null;
+ if (cooldownMs > 0) return xRateLimitHoldSentence("X capture", cooldownMs, now);
+ return captureOpensBrowser(job) ? xPressInFlight("capture these posts") : null;
+}
+
export function busySentence(service: string, r: CookieRunning): string {
return `${serviceLabel(service)}'s ${r.action} is already running (since ${r.since.slice(11, 19)} UTC) — wait for it to finish.`;
}
@@ -82,10 +186,14 @@ export async function withCookieAction<T>(
action: ServiceCookieActionKind,
fn: () => Promise<T>,
describe: (r: T) => CookieActionOutcome,
- opts: { paths?: Paths; jobs?: () => readonly JobLike[] } = {},
+ opts: { paths?: Paths; jobs?: () => readonly JobLike[]; platformOf?: PlatformOf } = {},
): Promise<T | { ok: false; error: string; busy: true }> {
const running = runningCookieActions(opts.jobs ? opts.jobs() : undefined)[service];
if (running) return { ok: false, error: busySentence(service, running), busy: true };
+ if (service === "x" && (action === "connect" || action === "refresh")) {
+ const job = xProfileJobRunning(opts.jobs ? opts.jobs() : undefined, opts.platformOf);
+ if (job) return { ok: false, error: xProfileJobSentence(action, job), busy: true };
+ }
const map = inflight();
map.set(service, { action, since: new Date().toISOString() });
// Everything after the mark is inside the try: whatever throws, the finally
diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts
@@ -0,0 +1,175 @@
+// AN X TRENDING LIBRARY end to end (lane x-trending, slice 1): the platform
+// choice "X trending library" in the New channel form makes a private library
+// (no URL, the Sites section replaced by "never on a site"); Read a trending
+// page on its channel page runs ONE read-x-trending job on X's queue, which
+// saves the page's answers raw and writes the posts it parses from the saved
+// file; the page then shows the library by topic; `get trending` answers the
+// same; a stale cookie jar refuses a second read before any job.
+//
+// X is NEVER contacted and no browser starts: the test server's fake browser
+// (E2E_FAKE_X_PROFILE_COOKIES_FILE, common/social/fakeXProfileBrowser.ts)
+// plays back the INVENTED trending page of
+// common/social/__fixtures__/xTrendingCapture.ts. The "connected profile" is
+// an empty directory and a cookie jar with a made-up login.
+
+import { test, expect } from "@playwright/test";
+import { mkdir, readFile, readdir, utimes, writeFile } from "node:fs/promises";
+import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings, writeSite } from "./helpers";
+import { baseUrl } from "./baseUrl";
+// By relative path: a runtime import of the package specifier does not resolve
+// under playwright's loader (digest.spec.ts says why).
+import { FIXTURE_TREND_URL, fixtureTrendingResponses } from "../../common/social/__fixtures__/xTrendingCapture";
+
+const TOKEN = "test-worker-token";
+const AUTH = { authorization: `Bearer ${TOKEN}` };
+const SLUG = "trending";
+const t = (p: string) => resolvePath(`${testPaths().transcriptsDir}/${p}`);
+const rel = (p: string) => `${testPaths().transcriptsDir}/${p}`;
+
+type Config = { platform?: string; sourceKind?: string; url?: string; socialHandle?: string; postFetcher?: string; xTrending?: Record<string, number> };
+
+const archiveLines = async (): Promise<number> => {
+ // A library keeps its posts under trending/, not where a posts channel does.
+ const file = rel(`channels/${SLUG}/trending/posts-archive`);
+ return (await pathExists(file)) ? (await readFile(resolvePath(file), "utf8")).split("\n").filter(Boolean).length : 0;
+};
+
+async function seed() {
+ await resetData("empty");
+ // The cookie-age limit is off on the test server unless a spec sets it (e2e/servers.ts).
+ await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } });
+ await writeSite("demo-site", { siteTitle: "Demo" });
+ // A connected X profile whose jar, written now, holds a (made-up) login.
+ await mkdir(t(".x-session/profile"), { recursive: true });
+ await writeFile(
+ t(".x-session/cookies.txt"),
+ "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n",
+ );
+ // The fake browser's page: the invented trending page.
+ await writeFile(
+ t(".fake-x-profile-cookies.json"),
+ JSON.stringify({
+ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }],
+ trending: fixtureTrendingResponses(),
+ }),
+ );
+}
+
+test("an X trending library: the form, one read, the library by topic, the listing, a stale jar", async ({ page, request }) => {
+ test.setTimeout(120_000);
+ await seed();
+ await generateReport(page, "new");
+ await page.goto("/channels/new");
+
+ await page.locator('select[name="platform"]').selectOption("x-trending");
+ await expect(page.locator("[data-x-trending-no-site]")).toHaveText("An X trending library is private: it is never put on a site.");
+ await expect(page.locator("[data-x-trending-fields]")).toBeVisible();
+ await expect(page.locator('input[name="socialHandle"]')).toHaveCount(0);
+ await expect(page.locator('input[name="fetchPostsNow"]')).toHaveCount(0);
+ await page.locator('input[name="name"]').fill("Trending");
+ await page.locator('input[name="slug"]').fill(SLUG);
+ await page.getByRole("button", { name: /create|add channel|save/i }).first().click();
+
+ const configPath = rel(`channels/${SLUG}/config.json`);
+ await expect
+ .poll(async () => ((await pathExists(configPath)) ? await readJson<Config>(configPath) : null), { timeout: 15_000 })
+ .toMatchObject({ platform: "twitter", sourceKind: "social", xTrending: {} });
+ const config = await readJson<Config>(configPath);
+ expect(config.url).toBeUndefined();
+ expect(config.socialHandle).toBeUndefined();
+ expect(config.postFetcher).toBeUndefined();
+
+ // The library's page: nothing yet, and it says it is private.
+ await generateReport(page, SLUG);
+ await page.goto(`/channels/${SLUG}`);
+ await expect(page.locator("[data-x-trending-private]")).toHaveText("Private: on no site, in no build, not in search.");
+ await expect(page.getByLabel("trending topics")).toContainText("No topic yet.");
+ await expect(page.getByRole("button", { name: /fetch posts|sync new/i })).toHaveCount(0);
+
+ // One read, into a named topic.
+ await page.getByLabel("trending page URL").fill(`${FIXTURE_TREND_URL}?src=trend_click`);
+ await page.getByLabel("topic", { exact: true }).fill("Kettle Festival");
+ await page.getByRole("button", { name: "Read trending page" }).click();
+ // Four posts: the promoted entry, the quoted post and another surface's post are not the page's.
+ await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4);
+
+ // What the read left: the raw answers, a screenshot, a record with names and sizes only.
+ const readsDir = t(`channels/${SLUG}/trending/reads`);
+ const reads = async () => (await readdir(readsDir).catch(() => [] as string[])).filter((n) => n.startsWith("tr-"));
+ await expect.poll(async () => (await reads()).length, { timeout: 15_000 }).toBe(1);
+ const [readId] = await reads();
+ // The captures are never committed: the reads directory ignores everything under it.
+ expect(await readFile(`${readsDir}/.gitignore`, "utf8")).toMatch(/^\*$/m);
+ expect(readId).toMatch(/^tr-[0-9A-Z]{26}$/);
+ await expect
+ .poll(async () => (await readdir(`${readsDir}/${readId}`)).sort(), { timeout: 15_000 })
+ .toEqual(["page.png", "read.json", "responses.jsonl"]);
+ const record = await readJson<{ outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; sentence: string }>(
+ rel(`channels/${SLUG}/trending/reads/${readId}/read.json`),
+ );
+ expect(record.outcome).toBe("read");
+ expect(record.stop).toBe("idle");
+ expect(record.scrolls).toBe(3);
+ expect(record.posts).toEqual({ onPage: 4, added: 4 });
+ expect(record.operations.map((o) => o.op)).toEqual(["ExampleTrendPage", "ExampleTrendTimeline", "HomeTimeline"]);
+ expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival).`);
+ const recordText = await readFile(t(`channels/${SLUG}/trending/reads/${readId}/read.json`), "utf8");
+ expect(recordText).not.toContain("teapot_news");
+ expect(recordText).not.toContain("festival opens");
+
+ // The library by topic.
+ await page.reload();
+ const topic = page.locator('[data-x-trending-topic="kettle-festival"]');
+ await expect(topic).toContainText("Kettle Festival · 4 posts");
+ await expect(topic).toContainText(FIXTURE_TREND_URL);
+ await expect(topic.locator("[data-x-trending-post]")).toHaveCount(4);
+ const first = topic.locator('[data-x-trending-post="1900000000000001001"]');
+ await expect(first).toContainText("@teapot_news (Teapot News)");
+ await expect(first).toContainText("2 media (image)");
+ await expect(first).toContainText("The kettle festival opens today.");
+ await expect(topic.locator('[data-x-trending-post="1900000000000001004"]')).toContainText("1 media (video)");
+ await expect(page.getByLabel("saved read")).toHaveValue(readId);
+ await expect(page.locator("body")).not.toContainText("Buy our kettles.");
+ await expect(page.locator("body")).not.toContainText("Not on the trending page.");
+
+ // The same over ops: what an agent reads. Never the raw capture.
+ const listed = await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}&topic=kettle-festival`, { headers: AUTH });
+ expect(listed.status()).toBe(200);
+ const body = (await listed.json()) as {
+ topics: { id: string; title: string; posts: number; sources: { url: string; reads: number }[] }[];
+ posts: { id: string; author: string; text: string; media: { count: number; kinds: string[] }; topic: string; reads: { read: string }[] }[];
+ total: number;
+ reads: string[];
+ };
+ expect(body.topics).toMatchObject([{ id: "kettle-festival", title: "Kettle Festival", posts: 4, sources: [{ url: FIXTURE_TREND_URL, reads: 1 }] }]);
+ expect(body.posts.map((p) => p.id)).toEqual(["1900000000000001001", "1900000000000001002", "1900000000000001004", "1900000000000001005"]);
+ expect(body.posts[3]).toMatchObject({ author: "lid_watch", media: { count: 1, kinds: ["gif"] }, topic: "kettle-festival", reads: [{ read: readId }] });
+ expect(body.total).toBe(4);
+ expect(body.reads).toEqual([readId]);
+ expect(JSON.stringify(body)).not.toContain("fixtureQueryId");
+
+ // On no site, and a site cannot take it.
+ const site = await readJson<{ channels: { slug: string }[] }>(rel("sites/demo-site/site.json"));
+ expect(site.channels).toEqual([]);
+ const onSite = await request.post(`${baseUrl}/api/ops/channel-config`, {
+ headers: AUTH,
+ data: { slug: SLUG, sites: [{ siteId: "demo-site", groupId: "default" }] },
+ });
+ expect(onSite.status()).toBe(400);
+ expect(((await onSite.json()) as { error: string }).error).toBe("trending is an X trending library: it is private, and never put on a site.");
+
+ // A cookie jar past the limit: the next read is refused before any job, with the guard's sentence.
+ const old = new Date(Date.now() - 2 * 60 * 60_000);
+ await utimes(t(".x-session/cookies.txt"), old, old);
+ const stale = await request.post(`${baseUrl}/api/ops/read-x-trending`, {
+ headers: AUTH,
+ data: { slug: SLUG, url: FIXTURE_TREND_URL },
+ });
+ expect(stale.status()).toBe(400);
+ expect(((await stale.json()) as { error: string }).error).toMatch(/^X cookies were last refreshed 2 h ago \(limit 60 min\)/);
+ expect((await reads()).length).toBe(1);
+ expect(await archiveLines()).toBe(4);
+ // Where every other reader of a posts channel looks, the library has nothing.
+ expect(await pathExists(rel(`channels/${SLUG}/posts`))).toBe(false);
+ expect(await pathExists(rel(`channels/${SLUG}/posts-archive`))).toBe(false);
+});
diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts
@@ -50,6 +50,8 @@ const EXPECTED_TOOLS = [
"channel_coverage",
"notes",
"x_search_leads",
+ "x_trending_topics",
+ "x_trending_posts",
"generation_policy",
"generate",
"list_sources",
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -100,6 +100,7 @@ import {
type ToolAnswer,
} from "./archivalTools";
import { X_SEARCH_TOOLS, xSearchLeadsTool } from "./xSearchLeads";
+import { X_TRENDING_TOOLS, xTrendingPostsTool, xTrendingTopicsTool } from "./xTrending";
import {
GENERATION_TOOLS,
generateTool,
@@ -948,6 +949,8 @@ export const TOOLS: Tool[] = [
...(ARCHIVAL_TOOLS as unknown as Tool[]),
// An X search channel's leads, through the editor (release 38 lane S).
...(X_SEARCH_TOOLS as unknown as Tool[]),
+ // An X trending library's topics and posts, through the editor (lane x-trending).
+ ...(X_TRENDING_TOOLS as unknown as Tool[]),
// The Claude Code balance (release 27 S9): generation.ts.
...(GENERATION_TOOLS as unknown as Tool[]),
{
@@ -1350,6 +1353,10 @@ export function createServer(
return fromAnswer(await channelCoverageTool(args, fetchClipDeps));
case "x_search_leads":
return fromAnswer(await xSearchLeadsTool(args, fetchClipDeps));
+ case "x_trending_topics":
+ return fromAnswer(await xTrendingTopicsTool(args, fetchClipDeps));
+ case "x_trending_posts":
+ return fromAnswer(await xTrendingPostsTool(args, fetchClipDeps));
case "notes":
return fromAnswer(await notesTool(args, fetchClipDeps));
case "generation_policy":
diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts
@@ -0,0 +1,129 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit";
+
+// ─── x_trending_topics / x_trending_posts (lane x-trending), through tools/call ───
+//
+// One GET on the fake editor (/api/ops/trending?slug=…); what is pinned is the
+// request sent and the words the agent reads. Invented ids, handles and words.
+
+const EDITOR = "http://editor.test";
+const READ = "tr-01JA0000000000000000000000";
+const TREND = "https://x.com/i/trending/1900000000000000001";
+
+const LISTING = {
+ ok: true,
+ slug: "trending",
+ name: "Trending",
+ topics: [
+ {
+ id: "kettle-festival",
+ title: "Kettle Festival",
+ posts: 2,
+ sources: [{ trendId: "1900000000000000001", url: TREND, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" }],
+ },
+ ],
+ posts: [
+ {
+ id: "1900000000000001001",
+ author: "teapot_news",
+ authorName: "Teapot News",
+ createdAt: "2026-11-16T12:00:00.000Z",
+ url: "https://x.com/teapot_news/status/1900000000000001001",
+ text: "The kettle festival\nopens today.",
+ media: { count: 2, kinds: ["image"] },
+ topic: "kettle-festival",
+ reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }],
+ },
+ {
+ id: "1900000000000001002",
+ author: "saucer_fan",
+ createdAt: "2026-11-16T13:00:00.000Z",
+ url: "https://x.com/saucer_fan/status/1900000000000001002",
+ text: "Second.",
+ media: { count: 0, kinds: [], thumbnail: "trending/posts-media/1900000000000001002/shot.png" },
+ topic: "kettle-festival",
+ reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }],
+ judgement: { state: "keep", note: "the reply everyone quotes", by: "agent", at: "2026-11-17T11:00:00.000Z" },
+ },
+ ],
+ total: 5,
+ reads: [READ],
+};
+
+const env = { ARCHILYZER_EDITOR_URL: EDITOR, WORKER_TOKEN: "t" };
+// The tool's own words: every answer ends with the server's corpus footer.
+const body = (res: unknown) => textOf(res as never).split("\n\n(corpus:")[0];
+
+test("x_trending_topics: the library's topics, their pages and reads", async () => {
+ const { deps, sent } = fakeEditor(() => ({ status: 200, body: LISTING }), env);
+ const client = await connectWith(deps);
+ const res = await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } });
+ const url = new URL(sent[0].url);
+ assert.equal(sent[0].method, "GET");
+ assert.equal(url.pathname, "/api/ops/trending");
+ assert.equal(url.searchParams.get("slug"), "trending");
+ assert.equal(url.searchParams.get("limit"), "1");
+ assert.equal(
+ body(res),
+ [
+ "X trending library trending: 1 topic, 5 posts (private: on no site, in no index)",
+ '- kettle-festival — "Kettle Festival": 2 posts',
+ ` ${TREND} · read 2×, last 2026-11-17 12:00 UTC`,
+ `Saved reads (newest first): ${READ}`,
+ ].join("\n"),
+ );
+});
+
+test("x_trending_posts: each post's id, author, words, media, reads and topic", async () => {
+ const { deps, sent } = fakeEditor(() => ({ status: 200, body: LISTING }), env);
+ const client = await connectWith(deps);
+ const res = await client.callTool({ name: "x_trending_posts", arguments: { channel: "trending", topic: "kettle-festival", limit: 2 } });
+ const url = new URL(sent[0].url);
+ assert.equal(url.searchParams.get("slug"), "trending");
+ assert.equal(url.searchParams.get("topic"), "kettle-festival");
+ assert.equal(url.searchParams.get("limit"), "2");
+ assert.equal(
+ body(res),
+ [
+ "X trending library trending, topic kettle-festival: 2 of 5 posts",
+ "1. 1900000000000001001 @teapot_news (Teapot News) · 2026-11-16 12:00 UTC · 2 media (image) · topic kettle-festival",
+ " https://x.com/teapot_news/status/1900000000000001001",
+ " The kettle festival / opens today.",
+ ` shown by: ${READ} (2026-11-17 10:00 UTC)`,
+ "2. 1900000000000001002 @saucer_fan · 2026-11-16 13:00 UTC · no media · topic kettle-festival",
+ " https://x.com/saucer_fan/status/1900000000000001002",
+ " Second.",
+ ` shown by: ${READ} (2026-11-17 10:00 UTC)`,
+ " captured: trending/posts-media/1900000000000001002/shot.png",
+ " judged keep by agent (2026-11-17 11:00 UTC): the reply everyone quotes",
+ "… 3 more (raise limit, or narrow by topic).",
+ ].join("\n"),
+ );
+});
+
+test("the two tools refuse a missing channel, a bad topic or limit, and say the editor's own sentence", async () => {
+ const { deps, sent } = fakeEditor(() => ({ status: 400, body: { ok: false, error: 'demo is not an X trending library (create one with platform "x-trending").' } }), env);
+ const client = await connectWith(deps);
+ for (const name of ["x_trending_topics", "x_trending_posts"]) {
+ const none = await client.callTool({ name, arguments: { channel: "" } });
+ assert.ok(isError(none));
+ assert.match(textOf(none), /channel is required \(the X trending library's slug\)/);
+ const traversing = await client.callTool({ name, arguments: { channel: "../x" } });
+ assert.ok(isError(traversing));
+ }
+ assert.match(textOf(await client.callTool({ name: "x_trending_posts", arguments: { channel: "demo", limit: 501 } })), /limit is a whole number, 1–500/);
+ assert.match(textOf(await client.callTool({ name: "x_trending_posts", arguments: { channel: "demo", topic: " " } })), /topic is a topic's id/);
+ assert.equal(sent.length, 0, "a refused ask sends nothing");
+ const refused = await client.callTool({ name: "x_trending_posts", arguments: { channel: "demo" } });
+ assert.ok(isError(refused));
+ assert.match(textOf(refused), /the editor refused \(HTTP 400\): demo is not an X trending library/);
+});
+
+test("with no editor configured, the tools say what is missing and ask nothing", async () => {
+ const { deps, sent } = fakeEditor(() => ({ status: 200, body: LISTING }), {});
+ const client = await connectWith(deps);
+ const res = await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } });
+ assert.ok(isError(res));
+ assert.equal(sent.length, 0);
+});
diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts
@@ -0,0 +1,170 @@
+import { describeEditorFailure, editorGet, type EditorDeps } from "./editorOps";
+import type { ToolAnswer } from "./archivalTools";
+
+// ─── x_trending_topics / x_trending_posts (lane x-trending, slice 1) ───
+//
+// An X TRENDING LIBRARY, read through the local editor
+// (GET /api/ops/trending?slug=<library>[&topic=][&limit=]): the operator's
+// topics with the trending pages read into each, and the posts those pages
+// showed — id, author, words, media by kind, the reads that showed each, its
+// topic. Read only. A library is PRIVATE: on no site and in no index build,
+// so no corpus tool (search_transcripts, get_post, …) and no published
+// archive carries its posts; only the editor can answer, and these tools read
+// nothing else of it — never a raw capture, a cookie or a token.
+//
+// Reading a page into a library is the operator's or an agent's ask of the
+// editor: `pnpm ops read-x-trending` (one job on X's queue, on a fresh cookie
+// jar — `pnpm ops get x-session` says whether one would start).
+
+const SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/i;
+export const X_TRENDING_POSTS_MAX = 500;
+
+type Topic = {
+ id: string;
+ title: string;
+ posts: number;
+ sources?: Array<{ trendId: string; url: string; title?: string; summary?: string; reads: number; lastReadAt: string | null }>;
+};
+
+type PostRow = {
+ id: string;
+ author: string;
+ authorName?: string;
+ createdAt: string;
+ url: string;
+ text: string;
+ media?: { count: number; kinds?: string[]; thumbnail?: string };
+ topic: string;
+ reads?: Array<{ read: string; trendId: string; at: string }>;
+ judgement?: { state: string; note?: string; by: string; at: string };
+};
+
+type ListingBody = { name?: string; topics?: Topic[]; posts?: PostRow[]; total?: number; reads?: string[] };
+
+const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "?");
+
+export function renderXTrendingTopics(slug: string, body: ListingBody): string {
+ const topics = body.topics ?? [];
+ const lines = [`X trending library ${slug}: ${topics.length} topic${topics.length === 1 ? "" : "s"}, ${body.total ?? 0} posts (private: on no site, in no index)`];
+ if (topics.length === 0) lines.push("No topic yet: no trending page has been read into it (pnpm ops read-x-trending).");
+ for (const t of topics) {
+ lines.push(`- ${t.id} — "${t.title}": ${t.posts} post${t.posts === 1 ? "" : "s"}`);
+ for (const s of t.sources ?? []) {
+ lines.push(` ${s.url}${s.title ? ` "${s.title}"` : ""} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC`);
+ if (s.summary) lines.push(` X's summary: ${s.summary}`);
+ }
+ }
+ if (body.reads?.length) lines.push(`Saved reads (newest first): ${body.reads.join(", ")}`);
+ return lines.join("\n");
+}
+
+function mediaText(m: PostRow["media"]): string {
+ if (!m || !m.count) return "no media";
+ return `${m.count} media${m.kinds?.length ? ` (${m.kinds.join(", ")})` : ""}`;
+}
+
+export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: string): string {
+ const posts = body.posts ?? [];
+ const total = body.total ?? posts.length;
+ const lines = [`X trending library ${slug}${topic ? `, topic ${topic}` : ""}: ${posts.length} of ${total} post${total === 1 ? "" : "s"}`];
+ if (posts.length === 0) lines.push("No post.");
+ for (const [i, p] of posts.entries()) {
+ const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC)`).join(", ");
+ lines.push(
+ `${i + 1}. ${p.id} @${p.author}${p.authorName ? ` (${p.authorName})` : ""} · ${day(p.createdAt)} UTC · ${mediaText(p.media)} · topic ${p.topic}`,
+ );
+ lines.push(` ${p.url}`);
+ lines.push(` ${p.text.replace(/\s*\n\s*/g, " / ")}`);
+ if (reads) lines.push(` shown by: ${reads}`);
+ if (p.media?.thumbnail) lines.push(` captured: ${p.media.thumbnail}`);
+ if (p.judgement) {
+ lines.push(` judged ${p.judgement.state} by ${p.judgement.by} (${day(p.judgement.at)} UTC)${p.judgement.note ? `: ${p.judgement.note}` : ""}`);
+ }
+ }
+ if (total > posts.length) lines.push(`… ${total - posts.length} more (raise limit, or narrow by topic).`);
+ return lines.join("\n");
+}
+
+function slugOf(tool: string, args: Record<string, unknown>): string | ToolAnswer {
+ const channel = typeof args.channel === "string" ? args.channel.trim() : "";
+ if (!channel || !SLUG_RE.test(channel)) {
+ return { text: `${tool}: channel is required (the X trending library's slug)`, isError: true };
+ }
+ return channel;
+}
+
+export async function xTrendingTopicsTool(args: Record<string, unknown>, deps: EditorDeps): Promise<ToolAnswer> {
+ const channel = slugOf("x_trending_topics", args);
+ if (typeof channel !== "string") return channel;
+ // The topics need no post: one is asked for, the smallest listing.
+ const q = new URLSearchParams({ slug: channel, limit: "1" });
+ const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`);
+ if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_topics", a), isError: true };
+ return { text: renderXTrendingTopics(channel, a.body as ListingBody) };
+}
+
+export async function xTrendingPostsTool(args: Record<string, unknown>, deps: EditorDeps): Promise<ToolAnswer> {
+ const channel = slugOf("x_trending_posts", args);
+ if (typeof channel !== "string") return channel;
+ const q = new URLSearchParams({ slug: channel });
+ let topic: string | undefined;
+ if (args.topic !== undefined) {
+ if (typeof args.topic !== "string" || !args.topic.trim()) {
+ return { text: "x_trending_posts: topic is a topic's id (x_trending_topics lists them)", isError: true };
+ }
+ topic = args.topic.trim();
+ q.set("topic", topic);
+ }
+ if (args.limit !== undefined) {
+ const n = Number(args.limit);
+ if (!Number.isInteger(n) || n < 1 || n > X_TRENDING_POSTS_MAX) {
+ return { text: `x_trending_posts: limit is a whole number, 1–${X_TRENDING_POSTS_MAX}`, isError: true };
+ }
+ q.set("limit", String(n));
+ }
+ const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`);
+ if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_posts", a), isError: true };
+ return { text: renderXTrendingPosts(channel, a.body as ListingBody, topic) };
+}
+
+export const X_TRENDING_TOOLS = [
+ {
+ name: "x_trending_topics",
+ description:
+ "An X TRENDING LIBRARY's topics: the operator's topics, each with the X trending pages " +
+ "(x.com/i/trending/<id>) read into it, how often and when, and its post count; and the " +
+ "ids of the saved reads. A library is PRIVATE — on no site, in no index, so no other " +
+ "tool here finds its posts. Read only: a page is read into a library with " +
+ "`pnpm ops read-x-trending` (one job on X's queue, on a fresh cookie jar). " +
+ "Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ channel: { type: "string", description: "The X trending library's slug (the editor's)." },
+ },
+ required: ["channel"],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: "x_trending_posts",
+ description:
+ "The posts of an X TRENDING LIBRARY (or of one of its topics): each post's id, author, " +
+ "date, words, media by kind and count, the reads that showed it, its topic, and — once " +
+ "it has them — its captured picture's path and its judgement (keep / drop / undecided) — the " +
+ "newest read's first, in the order the page showed them. For looking through what a " +
+ "trending page held before anything is archived or published. PRIVATE material: never " +
+ "quote it into a published report unless the operator says so. Read only. " +
+ "Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ channel: { type: "string", description: "The X trending library's slug (the editor's)." },
+ topic: { type: "string", description: "A topic's id (from x_trending_topics): only its posts." },
+ limit: { type: "number", description: `Posts to list (default 100, at most ${X_TRENDING_POSTS_MAX}).` },
+ },
+ required: ["channel"],
+ additionalProperties: false,
+ },
+ },
+] as const;
diff --git a/mcp/src/xTrendingPrivacy.test.ts b/mcp/src/xTrendingPrivacy.test.ts
@@ -0,0 +1,162 @@
+// AN X TRENDING LIBRARY NEVER REACHES THE MCP'S CORPUS TOOLS (lane x-trending,
+// hard rule 1). The MCP reads a COMPOSED site (`--local`, TRANSCRIPT_LOCAL_DIR,
+// export/public) or a published one, never the corpus. So the corpus is made
+// for real — an ordinary X account channel with one post (the control) and a
+// library with a post, a topic and a raw capture, each carrying a marker — on
+// a PRIVATE site whose site.json, written by hand, even NAMES the library;
+// then indexed and composed with the real build, and every read-only corpus
+// tool is asked over the composed dir. None answers with a marker, the
+// library's slug or its post; each does answer with the control.
+// common/bin/xTrendingPrivacy.test.ts holds the index, compose and site-writer
+// halves. (The library's own listing is the editor's: x_trending_topics and
+// x_trending_posts, xTrending.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";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "mcp-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("yt-dlp-transcript-common/lib/paths");
+const { buildIndex } = await import("yt-dlp-transcript-common/controller/buildIndex");
+const { main: composeSite } = await import("yt-dlp-transcript-common/bin/compose-site");
+const { writePosts } = await import("yt-dlp-transcript-common/lib/posts-server");
+const { recordXTrendingRead, writeXTrendingPosts, trendingReadDir } = await import("yt-dlp-transcript-common/lib/xTrending/store");
+const { createCorpusTools } = await import("./callTool");
+
+const paths = getPaths();
+const LIB = "trending-lib";
+const PUBLIC_X = "kettle-org-x";
+const PUBLIC_ID = "1900000000000005001";
+const PUBLIC_POST = "an ordinary archived post about kettles";
+const LIB_ID = "1900000000000006001";
+const MARKS = ["trendpostmarkerq7x", "trendhandlemarkerz4k", "trendtopicmarkerw2p", "trendrawmarkerj9m"];
+const READ = "tr-01JA0000000000000000000000";
+
+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, PUBLIC_ID, "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: {},
+});
+const libPosts = [post(LIB, LIB_ID, MARKS[1], `kettles ${MARKS[0]}`)];
+// Where a library keeps them, AND where an ordinary posts channel would (a
+// hand copy): neither may reach a build.
+await writeXTrendingPosts(libRoot, libPosts);
+await writePosts(libRoot, libPosts);
+await recordXTrendingRead(libRoot, {
+ readId: READ,
+ at: "2026-11-17T10:00:00.000Z",
+ ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" },
+ topic: `Topic ${MARKS[2]}`,
+ postIds: [LIB_ID],
+ 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: `kettles ${MARKS[3]}` } })}\n`);
+// Written by hand, naming the library (the site writer would refuse it).
+writeJson(path.join(paths.sitesDir, "priv", "site.json"), {
+ siteId: "priv", siteTitle: "priv", siteDescription: "fixture", headerTitle: "priv", homeTagline: "",
+ socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default", channels: [{ slug: PUBLIC_X, groupId: "default" }, { slug: LIB, groupId: "default" }],
+ siteUrl: "https://priv.example.test", archives: false, audience: "private",
+});
+
+test("every read-only corpus tool over the composed site: the account's post, never the library's", async () => {
+ await buildIndex({ paths, onLog: () => {} });
+ const log = console.log;
+ const warn = console.warn;
+ console.log = () => {};
+ console.warn = () => {};
+ try {
+ await composeSite({ siteId: "priv", paths });
+ } finally {
+ console.log = log;
+ console.warn = warn;
+ }
+ const corpus = await createCorpusTools({ source: `local:${paths.exportPublicDir}` });
+ const ask = (tool: string, args?: Record<string, unknown>) =>
+ corpus.call(tool as never, args as never).catch((e: Error) => `refused: ${e.message}`);
+ try {
+ const answers: Record<string, string> = {
+ list_channels: await ask("list_channels"),
+ search_control: await ask("search_transcripts", { query: "kettles" }),
+ enumerate: await ask("enumerate_matches", { query: "kettles" }),
+ get_post_control: await ask("get_post", { post_id: PUBLIC_ID }),
+ get_post_library: await ask("get_post", { post_id: LIB_ID }),
+ get_post_library_named: await ask("get_post", { post_id: LIB_ID, channel: LIB }),
+ get_thread_library: await ask("get_thread", { post_id: LIB_ID }),
+ channel_coverage: await ask("channel_coverage", { channel: LIB }),
+ };
+ for (const mark of MARKS) answers[`search ${mark}`] = await ask("search_transcripts", { query: mark });
+ assert.match(answers.list_channels!, new RegExp(PUBLIC_X), "control: the account channel is listed");
+ assert.match(answers.get_post_control!, new RegExp(PUBLIC_POST), "control: the account's post is read");
+ for (const [tool, text] of Object.entries(answers)) {
+ // A refusal may echo the id or slug it was asked for; nothing else may
+ // name the library, and nothing at all may carry its words.
+ const asked = tool.startsWith("get_post_library") || tool.startsWith("get_thread") || tool === "channel_coverage";
+ if (!asked) {
+ assert.ok(!text.includes(LIB), `${tool}: names ${LIB}`);
+ assert.ok(!text.includes(LIB_ID), `${tool}: names the library's post`);
+ }
+ for (const mark of MARKS) {
+ if (tool === `search ${mark}`) continue; // the search echoes its own query
+ assert.ok(!text.includes(mark), `${tool}: answers with ${mark}`);
+ }
+ assert.ok(!text.includes("responses.jsonl") && !text.includes(READ), `${tool}: names a raw capture`);
+ }
+ // Asked for by id, the library's post is not found.
+ for (const tool of ["get_post_library", "get_post_library_named", "get_thread_library"]) {
+ assert.ok(!answers[tool]!.includes(`https://x.com/${MARKS[1]}`), `${tool}: answered the post`);
+ assert.match(answers[tool]!, /not found|no post|No post|refused|unknown|not in|No channel|no channel/i, `${tool}: ${answers[tool]!.slice(0, 200)}`);
+ }
+ // A search for a marker finds no post.
+ for (const mark of MARKS) assert.ok(!answers[`search ${mark}`]!.includes("x.com/"), `search ${mark}: a hit`);
+ } finally {
+ await corpus.close();
+ }
+});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -11,6 +11,7 @@
// pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
// [--wait-timeout <seconds>] [--quiet]
// pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]]
+// pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>]
// pnpm ops get channels
// pnpm ops get tags [<tagId>]
// pnpm ops get job <id> [--tail [<lines>]]
@@ -172,6 +173,11 @@
// pnpm ops get channel demo-search --leads --limit 20
// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'
// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'
+// pnpm ops create-channel --json '{"fields":{"name":"Trending","handling":"transcribe","platform":"x-trending"}}'
+// pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait
+// pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait
+// pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait
+// pnpm ops get trending trending --topic kettle-festival --limit 50
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait
// pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait
@@ -335,6 +341,14 @@ const GETTERS = {
// until the next refresh" — the X posts channels in the default order, and
// the jar's age against social.x.maxCookieAgeMinutes.
"x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"),
+ // An X trending library's topics and posts (lane x-trending), from its own
+ // files: --topic narrows the posts to one topic, --limit caps them.
+ trending: (slug, { jobs }) => {
+ const q = new URLSearchParams({ slug });
+ if (jobs.topic) q.set("topic", jobs.topic);
+ if (jobs.limit) q.set("limit", String(jobs.limit));
+ return `/api/ops/trending?${q.toString()}`;
+ },
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// The speakers readout: waiting, freed this run, rate, days left, per channel.
@@ -414,6 +428,7 @@ const GET_FLAGS = {
transcript: ["slug"],
"lookout-run": ["run"],
channel: ["counts", "leads", "limit"],
+ trending: ["topic", "limit"],
job: ["tail"],
jobs: ["active", "failed", "kind", "slug", "limit"],
};
@@ -685,6 +700,10 @@ const ACTIONS = [
// account as its own X channel on no site, or never archive it (hidden),
// or restore it ({slug, handle, action, name?, fetch?, dryRun?}).
"x-search-lead",
+ // X TRENDING (lane x-trending): one trending page read into a private
+ // library, as one job on X's queue ({slug, url, topic?, scrolls?, posts?,
+ // probe?, headed?}), or a saved read parsed again offline ({slug, reparse}).
+ "read-x-trending",
// EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
// ({url} or a record's {slug, id}), read only and paced; and find-copy — a
// copy of every gone recording a report cites (Wayback, then archive.org),
@@ -809,6 +828,9 @@ export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
export const LIVE_CLIP_RESULT_MARKER = "@@live-clip ";
// The same for an X run (X_RUN_RESULT_MARKER in common/controller/xRun.ts).
export const X_RUN_RESULT_MARKER = "@@x-run ";
+// The same string is READ_X_TRENDING_RESULT_MARKER in
+// common/controller/readXTrending.ts.
+export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending ";
// The same for a lookout run (LOOKOUT_RUN_RESULT_MARKER in
// common/controller/lookoutRun.ts).
export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run ";
@@ -872,8 +894,8 @@ export function parseArgs(argv) {
} else if (arg === "--active" || arg === "--failed") {
jobs[arg.slice(2)] = true;
used.add(arg.slice(2));
- } else if (/^--(kind|slug|limit|run)(=|$)/.test(arg)) {
- const [, key, eq] = /^--(kind|slug|limit|run)(=?)/.exec(arg);
+ } else if (/^--(kind|slug|limit|run|topic)(=|$)/.test(arg)) {
+ const [, key, eq] = /^--(kind|slug|limit|run|topic)(=?)/.exec(arg);
const raw = eq ? arg.slice(key.length + 3) : argv[++i];
if (raw === undefined || raw === "") {
return { error: `--${key} needs a value` };
@@ -1068,6 +1090,7 @@ export function parseArgs(argv) {
...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}),
...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}),
+ ...(action === "read-x-trending" ? { resultMarker: READ_X_TRENDING_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1158,6 +1181,7 @@ export function usage() {
" pnpm ops get x-session [<slug>]",
" pnpm ops get cookies [fresh]",
" pnpm ops get x-run [<run id>]",
+ " pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get speakers",
" pnpm ops get lookouts [<id>]",
@@ -1267,6 +1291,17 @@ export function usage() {
" browser's cookie store (names and times only, never a value) instead of",
" the 5-minute cache. Check again is recheck-service; Refresh cookies and",
" the Connects are clicks on /cookies.",
+ "get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending",
+ " library's topics and posts, read from its own files (a library is in no",
+ " index): topics [{id, title, posts, sources: [{trendId, url, reads,",
+ " lastReadAt}]}], posts [{id, author, authorName, createdAt, url, text,",
+ " media: {count, kinds, thumbnail?}, topic, reads: [{read, trendId, at}],",
+ " judgement?}] (the newest read's first, in page order; --limit 1-500,",
+ " default 100; total is the count before it) and reads (the saved reads'",
+ " ids, newest first). thumbnail is a captured post's first picture",
+ " (trending/posts-media/<id>/<name>, relative to the channel); judgement",
+ " is {state: keep | drop | undecided, note?, by, at} once a post has one. Never the",
+ " raw capture, a cookie or a token.",
"get x-run [<run id>] is the X run as /review's X run console shows it:",
" the latest run (or the one named) — each channel's status (queued,",
" running, done with its new posts, deferred, failed), \"summary\" (\"N",
@@ -1844,6 +1879,37 @@ export function usage() {
" drained fetch stops at its next resume point and the next run of the",
" same walk resumes there.",
"",
+ 'read-x-trending reads ONE X trending page into an X trending library:',
+ ' {"slug", "url": "https://x.com/i/trending/<number>"}, as one job on X\'s',
+ " queue (the fresh-jar rule, the X alert and X's job gap apply; ask get",
+ " x-session first). The page is opened in the connected X profile's",
+ " browser, every GraphQL answer the page itself fetched is saved raw with",
+ " a screenshot (channels/<slug>/trending/reads/<readId>/), and the posts",
+ " are parsed from the saved file and written as the library's posts. A",
+ " read lists posts; it archives no media and no thread. \"topic\": a",
+ " 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 it). \"scrolls\": 1-20 moves",
+ " to the bottom of the page (default: the channel's cap, else 8);",
+ " \"posts\": stop once 1-200 are seen (else 60); a read also stops after two",
+ " scrolls with nothing new, and at once on a 429, a 403 or a login wall.",
+ " A 429 leaves X alone for 15 minutes (no read is queued or started",
+ " before the time its sentence names); a page that stops answering ends",
+ " the read within 6 minutes. Nothing retries.",
+ " \"probe\": true saves the capture and its summary and writes no",
+ " post. \"headed\": true opens a window on the editor's desktop. {\"slug\",",
+ " \"reparse\": \"<readId>\"} parses a saved read again OFFLINE (X is asked",
+ " nothing; a read left with no record takes \"url\" too).",
+ " No fresh jar needed. --wait prints the log's @@read-x-trending",
+ " {ok, mode, read, outcome, stop, responses, operations (names and sizes,",
+ " never a body), posts: {onPage, added}, topic, sentence}; a capture with",
+ " no post the parser knows ends ok, \"read saved, nothing recognised\".",
+ " Refused before a job: not a library, not a trending page URL, a cap out",
+ " of range, no connected X profile, X's Connect or Refresh in flight, a",
+ " stale jar. A library is made with create-channel, \"platform\":",
+ " \"x-trending\" (no \"url\", no \"sites\": it is private, never on a site,",
+ " in no index build; \"xTrendingMaxScrolls\"?, \"xTrendingMaxPosts\"? set",
+ " its caps).",
+ "",
'x-run fetches several X posts channels IN SEQUENCE as ONE job on X\'s',
' queue: {"channels": [slug, ...]} in that order, each a fetch-posts sync',
' new of at most 200 posts ("limit": N, 1-200, caps it lower), X\'s queue',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1131,3 +1131,22 @@ test("the local-media actions are POSTs to their routes, named in the usage", ()
assert.equal(parseArgs(["local-media-import", "--json", '{"slug":"demo-local","allNew":true}', "--wait"]).wait, true);
assert.match(usage(), /Actions:.*record-live, local-media-configure, local-media-preview, local-media-prepare, local-media-import, local-media-link/);
});
+
+// Lane x-trending: one trending page read into a private library, and the
+// library's listing.
+test("read-x-trending is a POST with a result marker; get trending reads the library's listing", () => {
+ const p = parseArgs(["read-x-trending", "--json", '{"slug":"lib","url":"https://x.com/i/trending/1900000000000000001","probe":true}', "--wait"]);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/read-x-trending");
+ assert.deepEqual(p.body, { slug: "lib", url: "https://x.com/i/trending/1900000000000000001", probe: true });
+ assert.equal(p.resultMarker, "@@read-x-trending ");
+ assert.equal(parseArgs(["get", "trending", "lib"]).path, "/api/ops/trending?slug=lib");
+ assert.equal(parseArgs(["get", "trending", "lib", "--topic", "kettle-festival", "--limit", "50"]).path, "/api/ops/trending?slug=lib&topic=kettle-festival&limit=50");
+ assert.equal(parseArgs(["get", "trending", "lib", "--topic=a b"]).path, "/api/ops/trending?slug=lib&topic=a+b");
+ assert.match(parseArgs(["get", "trending"]).error, /trending/);
+ assert.match(parseArgs(["get", "trending", "lib", "--leads"]).error, /get trending does not take --leads/);
+ assert.match(parseArgs(["get", "channel", "s", "--topic", "x"]).error, /get channel does not take --topic/);
+ assert.match(usage(), /pnpm ops get trending <slug> \[--topic <topicId>\] \[--limit <n>\]/);
+ assert.match(usage(), /read-x-trending reads ONE X trending page into an X trending library/);
+ assert.match(usage(), /Actions:.*x-search-lead, read-x-trending/);
+});
diff --git a/umtool/lib/report/postCards.mjs b/umtool/lib/report/postCards.mjs
@@ -13,6 +13,7 @@
// The cure is a crop (`shotMaxHeight` on the post) or another post.
//
// Plain ESM.
+import { isTrendingLibrary } from "./xTrendingMarker.mjs";
import { readFile, readdir, stat } from "node:fs/promises";
import path from "node:path";
@@ -64,6 +65,8 @@ const dateOf = (row) =>
*/
export async function searchPostArchive(channelsDir, slug, q, { limit = POST_SEARCH_MAX, manifest = null } = {}) {
if (!SLUG_RE.test(slug)) throw new Error(`not a channel slug: ${slug}`);
+ // An X trending library is private: it has no archive to search here.
+ if (await isTrendingLibrary(channelsDir, slug)) return { slug, archive: false, hits: [], total: 0 };
const dir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts");
const names = (await readdir(dir).catch(() => null))?.filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse() ?? null;
if (names === null) return { slug, archive: false, hits: [], total: 0 };
@@ -128,6 +131,7 @@ export async function postChannels(channelsDir, manifest, cited = []) {
const have = [];
for (const d of dirs) {
if (!d.isDirectory() || !SLUG_RE.test(d.name)) continue;
+ if (await isTrendingLibrary(channelsDir, d.name)) continue;
if (await stat(path.join(/* turbopackIgnore: true */ channelsDir, d.name, "posts")).then((s) => s.isDirectory(), () => false)) have.push(d.name);
}
const used = new Set(
diff --git a/umtool/lib/report/postContext.mjs b/umtool/lib/report/postContext.mjs
@@ -31,6 +31,7 @@
// archive holds it (read lazily, only for a link), else the capture's. The
// same pass snapshots the row's `threadId` as the entry's `conversation`
// (post-conversation.mjs reads a conversation by it).
+import { isTrendingLibrary } from "./xTrendingMarker.mjs";
import { readFile, readdir, stat } from "node:fs/promises";
import path from "node:path";
import { joinSplitLinks } from "umtool-report-to-video/post-narration";
@@ -163,7 +164,8 @@ export function statusResolver(channelsDir) {
if (slugs === null) {
const names = await readdir(channelsDir).catch(() => []);
slugs = [];
- for (const n of names) if (POST_KEY_RE.test(n) && (await stat(path.join(channelsDir, n, "posts")).catch(() => null))?.isDirectory()) slugs.push(n);
+ // Never an X trending library: a link must not resolve to a private one.
+ for (const n of names) if (POST_KEY_RE.test(n) && !(await isTrendingLibrary(channelsDir, n)) && (await stat(path.join(channelsDir, n, "posts")).catch(() => null))?.isDirectory()) slugs.push(n);
}
const h = str(handle).toLowerCase();
const order = [...slugs.filter((s) => h && s.toLowerCase().startsWith(h)), ...slugs.filter((s) => !(h && s.toLowerCase().startsWith(h)))];
diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs
@@ -33,6 +33,7 @@
// checks.
//
// Plain ESM: the CLI runs it under bare node.
+import { isTrendingLibrary } from "./xTrendingMarker.mjs";
import { execFile } from "node:child_process";
import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
@@ -71,6 +72,8 @@ const timeOf = (row) => {
* wins), each with `channelSlug` set to `slug`. A channel with no archive is [].
*/
export async function readPostsArchive(channelsDir, slug) {
+ // An X trending library is private: a reel is never made from one.
+ if (await isTrendingLibrary(channelsDir, slug)) return [];
const dir = path.join(channelsDir, slug, "posts");
const names = (await readdir(dir).catch(() => [])).filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort();
const byId = new Map();
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -28,6 +28,7 @@
// replaced (its attachTo kept unless --attach says otherwise).
//
// Plain ESM: the CLI runs under bare node.
+import { isTrendingLibrary } from "./xTrendingMarker.mjs";
import { readFileSync } from "node:fs";
import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
@@ -222,6 +223,8 @@ export function snowflakeMonth(id) {
* line with the id wins (a re-fetch appends).
*/
export async function findPostRow(channelsDir, slug, postId) {
+ // An X trending library is private: `posts add` finds no post in one.
+ if (await isTrendingLibrary(channelsDir, slug)) return { row: null, shard: null, shards: 0 };
const dir = path.join(channelsDir, slug, "posts");
const names = (await readdir(dir).catch(() => [])).filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse();
const first = snowflakeMonth(postId);
diff --git a/umtool/lib/report/xTrendingLibrary.test.mjs b/umtool/lib/report/xTrendingLibrary.test.mjs
@@ -0,0 +1,76 @@
+// AN X TRENDING LIBRARY IS NOT OFFERED TO A VIDEO PROJECT (lane x-trending,
+// review 1). umtool reads a posts channel's archive straight off the corpus
+// (`channels/<slug>/posts/*.jsonl`: the post search, Add posts, the reels). A
+// library keeps its posts one directory down, `channels/<lib>/trending/posts/`
+// (common/lib/xTrending/store.ts xTrendingPostsRoot), so none of those readers
+// finds a library or its posts until the Posts library page (slice 3) reads
+// it on purpose. Pinned here over a temp corpus, laid out as the editor's
+// store writes it; invented ids, handles and words.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { postChannels, searchPostArchive } from "./postCards.mjs";
+import { readPostsArchive } from "./postReel.mjs";
+import { findPostRow } from "./postsCli.mjs";
+import { statusResolver } from "./postContext.mjs";
+
+const row = (slug, id, author, text) => ({ id, slug: `${slug}/${id}`, channelSlug: slug, author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] });
+
+test("the post search, the channels offered and the reels' archive reader find nothing of a library", async () => {
+ const channels = await mkdtemp(path.join(tmpdir(), "umtool-x-trending-"));
+ try {
+ // An ordinary X account channel (the control) and a library.
+ await mkdir(path.join(channels, "kettle-org-x", "posts"), { recursive: true });
+ await writeFile(path.join(channels, "kettle-org-x", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/kettle_org" }));
+ await writeFile(path.join(channels, "kettle-org-x", "posts", "2026-11.jsonl"), JSON.stringify(row("kettle-org-x", "1900000000000005001", "kettle_org", "an ordinary post about kettles")) + "\n");
+ await mkdir(path.join(channels, "trending-lib", "trending", "posts"), { recursive: true });
+ await writeFile(path.join(channels, "trending-lib", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }));
+ await writeFile(path.join(channels, "trending-lib", "trending", "posts", "2026-11.jsonl"), JSON.stringify(row("trending-lib", "1900000000000006001", "trend_author", "kettles trendmarkerq7x")) + "\n");
+ await writeFile(path.join(channels, "trending-lib", "trending", "posts-archive"), "twitter 1900000000000006001\n");
+
+ assert.deepEqual((await postChannels(channels, null)).map((c) => c.slug), ["kettle-org-x"]);
+ const control = await searchPostArchive(channels, "kettle-org-x", "kettles");
+ assert.equal(control.total, 1);
+ assert.deepEqual(await searchPostArchive(channels, "trending-lib", "kettles"), { slug: "trending-lib", archive: false, hits: [], total: 0 });
+ assert.deepEqual(await searchPostArchive(channels, "trending-lib", ""), { slug: "trending-lib", archive: false, hits: [], total: 0 });
+ assert.equal((await readPostsArchive(channels, "kettle-org-x")).length, 1);
+ assert.deepEqual(await readPostsArchive(channels, "trending-lib"), []);
+ } finally {
+ await rm(channels, { recursive: true, force: true });
+ }
+});
+
+// Review 2 N8b: BY NAME, not only by layout. A marker-carrying library whose
+// posts sit where an ordinary posts channel keeps them (a hand copy, a library
+// from before the move) is still not offered: each reader asks the marker.
+test("a library with posts in the ordinary place is refused by its marker: not offered, not searched, not read into a reel", async () => {
+ const channels = await mkdtemp(path.join(tmpdir(), "umtool-x-trending-legacy-"));
+ try {
+ await mkdir(path.join(channels, "kettle-org-x", "posts"), { recursive: true });
+ await writeFile(path.join(channels, "kettle-org-x", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/kettle_org" }));
+ await writeFile(path.join(channels, "kettle-org-x", "posts", "2026-11.jsonl"), JSON.stringify(row("kettle-org-x", "1900000000000005001", "kettle_org", "an ordinary post about kettles")) + "\n");
+ await mkdir(path.join(channels, "old-lib", "posts"), { recursive: true });
+ // The marker alone makes it a library, whatever its kind says.
+ await writeFile(path.join(channels, "old-lib", "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "video", platform: "twitter", xTrending: {} }));
+ await writeFile(path.join(channels, "old-lib", "posts", "2026-11.jsonl"), JSON.stringify(row("old-lib", "1900000000000006001", "trend_author", "kettles trendmarkerq7x")) + "\n");
+
+ assert.deepEqual((await postChannels(channels, null)).map((c) => c.slug), ["kettle-org-x"]);
+ assert.deepEqual(await searchPostArchive(channels, "old-lib", "kettles"), { slug: "old-lib", archive: false, hits: [], total: 0 });
+ assert.deepEqual(await readPostsArchive(channels, "old-lib"), []);
+ assert.equal((await searchPostArchive(channels, "kettle-org-x", "kettles")).total, 1);
+ assert.equal((await readPostsArchive(channels, "kettle-org-x")).length, 1);
+ // `posts add` and a link's resolver find nothing in it either.
+ assert.deepEqual(await findPostRow(channels, "old-lib", "1900000000000006001"), { row: null, shard: null, shards: 0 });
+ assert.equal((await findPostRow(channels, "kettle-org-x", "1900000000000005001")).row?.author, "kettle_org");
+ const resolve = statusResolver(channels);
+ assert.equal(await resolve({ handle: "trend_author", id: "1900000000000006001" }), null);
+ assert.ok(await resolve({ handle: "kettle_org", id: "1900000000000005001" }));
+ } finally {
+ await rm(channels, { recursive: true, force: true });
+ }
+});
+
diff --git a/umtool/lib/report/xTrendingMarker.mjs b/umtool/lib/report/xTrendingMarker.mjs
@@ -0,0 +1,26 @@
+// IS THIS CHANNEL AN X TRENDING LIBRARY? (lane x-trending, review 2 N8b.) The
+// readers of a posts channel's archive in umtool -- the post search, the
+// channels offered, Add posts and the reels, the status resolver -- ask it of
+// every channel they enumerate or are handed, so a library is refused BY NAME
+// (its marker, common/lib/xTrending/marker.mjs isXTrendingChannel), not only
+// because its posts are kept one directory down. A library reaches a video
+// project through the Posts library page alone, once that exists.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { isXTrendingChannel } from "yt-dlp-transcript-common/lib/xTrending/marker.mjs";
+
+/**
+ * True when `channels/<slug>/config.json` carries the library marker. A
+ * channel with no readable config is not a library.
+ * @param {string} channelsDir
+ * @param {string} slug
+ */
+export async function isTrendingLibrary(channelsDir, slug) {
+ const text = await readFile(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8").catch(() => null);
+ if (text === null) return false;
+ try {
+ return isXTrendingChannel(JSON.parse(text));
+ } catch {
+ return false;
+ }
+}