commit 6f1a7e1b2dd8ceacc39f6282797915e448a501f0
parent af6737d913c6c1f2ef3ee5cc23235d0aa180d145
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 19:15:50 -0500
x-trending S1: the MCP's two read tools, the docs and the changelog
x_trending_topics and x_trending_posts read an X trending library through the
editor (GET /api/ops/trending): topics with their pages and reads; each post's id,
author, words, media by kind, the reads that showed it and its topic. Never the raw
capture. mcp/src/xTrendingPrivacy.test.ts asks every read-only corpus tool over a
real composed private site whose site.json names the library: none answers with it.
OPERATING.md gains "X trending pages, in a private library"; COMMANDS.md and
CHANNEL.md are regenerated; editor CHANGELOG.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
9 files changed, 544 insertions(+), 2 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 (`channels/<slug>/trending/`). `{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 or a login wall — 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; 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,14 @@ 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, createdAt, url, text, media: {count,
+ kinds}, topic, reads: [{read, trendId, at}]}] (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). 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,57 @@ 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.
+- **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 401 or X's login page. Nothing retries. 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.
+- **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 no longer has this trending page …` and `The trending page could not be loaded: …`: 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; while a Connect or Refresh is
+ running, a read is refused. Refresh the cookies first, then read.
+
## Transcribe
```sh
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,29 @@
# 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.
+- **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 a trending-page read is
+ refused while a Connect or Refresh is running. 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.
- **Connect X account, Connect archive session and Connect forum session open their window even when the editor
started before the desktop.** The editor runs as a user service that starts at boot, so it had no display, and every
Connect failed with "launched a headed browser without having a XServer running" until a restart. Each press now looks
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,126 @@
+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: [] },
+ topic: "kettle-festival",
+ reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10: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)`,
+ "… 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,164 @@
+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[] };
+ topic: string;
+ reads?: Array<{ read: string; trendId: 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 (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, and its topic — 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,158 @@
+// 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, 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: {},
+});
+await writePosts(libRoot, [post(LIB, LIB_ID, MARKS[1], `kettles ${MARKS[0]}`)]);
+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();
+ }
+});