Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit b059c992f34ea8426f12267c509787df2f069705
parent 237f2fb0c376bdba1d3fe64d0cd2fe90dfe04889
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 06:06:48 -0500

Merge lane/x-trending-2: the trending library keeps posts, saves media once and watches a topic, slice 2 -- `judge-trending` writes keep / drop / later per post or thread through one writer, and the operator's word outranks an agent's whatever the order; a kept post gets its media, a screenshot and its thread by the capture job, rooted under trending/; media comes from the addresses the saved read already holds and is stored once, by content hash, across posts and topics; `watch-trending` re-reads a topic on an interval until an end time, one paced read at a time across every library, saving new posts' media at once and marking a post gone from the page only after a read that reached the page's end; a watch runs only on a fresh cookie jar, asked again when its job starts, pauses with an alert and a place on /review, and stops after three failed reads until the operator restarts it; a hung profile browser is killed by its checked pid; the library and everything under it stay behind every publishing door

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 2+-
MCOMMANDS.md | 18++++++++++++++----
MOPERATING.md | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/bin/xTrendingPrivacy.test.ts | 35+++++++++++++++++++++++++++++++----
Mcommon/controller/capturePosts.test.ts | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 145++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/readXTrending.test.ts | 84++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/readXTrending.ts | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Acommon/controller/xTrendingWatch.test.ts | 549+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/xTrendingWatch.ts | 553+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/xTrendingWatchJob.test.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 7+++++--
Mcommon/lib/channelConfig.ts | 2+-
Acommon/lib/xTrending/__fixtures__/slice2Library.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/config.test.ts | 9+++++++++
Mcommon/lib/xTrending/config.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/judgements.test.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/judgements.ts | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/mediaStore.test.ts | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/mediaStore.ts | 376+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.test.ts | 85++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/xTrending/store.ts | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Acommon/lib/xTrending/watch.ts | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/xTrendingReportDoor.test.ts | 29+++++++++++++++++++++++++++++
Mcommon/social/__fixtures__/xTrendingCapture.ts | 32++++++++++++++++++++++++++++----
Mcommon/social/fakeXProfileBrowser.ts | 31+++++++++++++++++++++++++++++++
Mcommon/social/fetchers.ts | 37+++++++++++++++++++++++++++++++++++++
Mcommon/social/postCapture.ts | 4++++
Acommon/social/profileBrowserPid.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/profileBrowserPid.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 18+++++++++++++-----
Mcommon/social/xPostCapture.test.ts | 27+++++++++++++++++++++++++++
Mcommon/social/xPostCapture.ts | 16++++++++++++----
Acommon/social/xTrendingMedia.test.ts | 409+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xTrendingMedia.ts | 387+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.test.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.ts | 184++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/social/xTrendingRead.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingRead.ts | 30+++++++++++++++++++++++-------
Mcommon/views/review.ts | 6++++++
Meditor/CHANGELOG.md | 26++++++++++++++++++++++++++
Aeditor/app/api/ops/_xTrendingWatch.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 22++++++++++++++++++++--
Aeditor/app/api/ops/judge-trending/route.test.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/judge-trending/route.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/read-x-trending/route.test.ts | 1+
Meditor/app/api/ops/trending/route.ts | 21++++++++++++++++-----
Aeditor/app/api/ops/watch-trending/route.test.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/watch-trending/route.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/XTrendingPanel.tsx | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/channels/[slug]/socialActions.ts | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/xTrendingActions.ts | 292+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/app/jobs/jobReplayRegistry.ts | 3+++
Meditor/app/review/lib/loadReview.ts | 11++++++++++-
Meditor/app/review/page.tsx | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/e2e/x-trending.spec.ts | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/instrumentation.ts | 15+++++++++++++++
Mmcp/src/xTrending.test.ts | 36++++++++++++++++++++++++++++++++++++
Mmcp/src/xTrending.ts | 36++++++++++++++++++++++++++++++------
Mmcp/src/xTrendingPrivacy.test.ts | 12++++++++++--
Aplans/x-trending.md | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 95++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mscripts/archilyzer-ops.test.mjs | 23++++++++++++++++++++++-
Mumtool/lib/report/xTrendingLibrary.test.mjs | 23+++++++++++++++++++++++
64 files changed, 6949 insertions(+), 111 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -61,7 +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. | +| `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?, maxVideoMb?, watchIntervalMinutes?, watchHours?, watchMaxTopics?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); and the defaults of the watch: how often a watched topic is read (15–1440 minutes, default 30), for how long (1–168 hours, default 48) and how many topics may be watched at once (1–12, default 4) — `pnpm ops watch-trending` sets these three and `maxVideoMb`; `{}` 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 @@ -169,7 +169,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | | `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | -| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. | | +| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; three refusals in a row (a 403, or no answer) and the job asks the CDN no more; nothing retries. "keptMedia": true is for posts marked keep (refused for any other id): no per-file cap, and a post the CDN cannot serve whole is downloaded the logged-in way, if it is still kept when that download would start. A library's capture runs on X's queue only: "queueKey" is refused for it. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | | `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | | @@ -219,6 +219,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `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) -&gt; {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 &lt;handle&gt;-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) -&gt; {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 -&gt; {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/&lt;number&gt;"}, 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/&lt;slug&gt;/trending/reads/&lt;readId&gt;/), 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": "&lt;readId&gt;"} 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` | +| `judge-trending` | judge-trending judges posts of an X trending library: {"slug", "set": \[{"id" \| "thread", "state", "note"?}, ...\], "by"?}. "id" is a post of the library; "thread" a thread's ROOT post id (get trending gives each post's thread), judging every post of it that has no judgement of its own. "state": keep, drop, later, or undecided (the judgement is removed: no entry is undecided). "note": up to 2000 characters. "by": "agent" (the default) or "operator" - the caller's word: an agent says "agent". An agent's judgement is a suggestion: an agent's write over a judgement the operator made is skipped for that id and named in skipped, and the rest is written; a post the operator judged through its thread is the operator's too. Answers {written, skipped: \[{id \| thread, reason}\], kept, archive?} - kept names the posts whose judgement BECAME keep. A keep archives them: ONE capture-posts job on X's queue (a screenshot, the context, a reply's thread shot, the media), its id in archive.jobId; "archive": false marks only. When that job is refused (a stale jar, the X alert, X cooling down) the judgements are written all the same and archive.error says why; capture-posts {slug, ids, "thread": true, "keptMedia": true} archives them later. Drop deletes nothing: the post, its capture and its media stay, and a later keep puts it back. An id the library does not hold is skipped by name, not refused. | `pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}'` | +| `watch-trending` | watch-trending watches a topic of an X trending library: {"slug", "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}. While a topic is watched its trending page is read again every intervalMinutes (15-1440; default the library's, else 30) until hours from now (1-168; else 48), each tick the SAME single read-x-trending job on X's queue, started by the editor's own scan (once a minute, at most one read per scan, none while a trending read or capture of ANY library waits its turn: every library's ticks are one stream). A topic of several pages reads one page per tick, in turn. At most 4 topics of a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN, no page opened; "shots": true also screenshots every new post. "on": false stops it. A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes): the editor never refreshes the jar by itself, so a watch pauses when the jar goes stale (X's jar-age alert goes up, /review lists the paused watches) and resumes at the first scan after Refresh cookies on /cookies. It does not cover a night nobody presses Refresh in. That limit is the watch's own, whatever the login source or the setting: a jar whose age cannot be read, a limit set to 0 and an unreadable settings file all pause it. The X alert, a rate-limit cooldown and a missing profile pause it the same way. Three reads in a row that do not end "read" (a rate limit, a 403, a page that will not load) pause it until someone switches it on again. A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) is recorded gone from the page at that time (get trending: gone) - never "deleted". A page X no longer has is not read again, and ends the watch when it was the topic's last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?, "hours"?, "maxTopics"?}} changes the library's defaults; {"slug", "tick": true} runs one scan now (refused on an idle boot; two asks at once are one scan). get trending shows each topic's watch and what it is doing (watch.sentence). | `pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'`<br>`pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'` | | `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) -&gt; {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"? -&gt; {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"? -&gt; {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.&lt;fmt&gt;; 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"? -&gt; {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"?} -&gt; {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` | @@ -375,11 +377,19 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending 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, + gone?, capture?, thread, 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 + (trending/posts-media/<id>/<name>, relative to the channel); thread is + the root post id of the thread a post belongs to; judgement is {state: + keep | drop | later, note?, by, at, from?} once a post has one (its own, + or its thread's: from "thread"); no judgement is undecided. gone is + {at, read, trendId}: a page that showed the post before did not show it + at a read that reached the page's end (gone from the page, not + deleted). capture is {at, state, shot, files, mediaState, mediaOwed?} + (mediaOwed "next": a later capture asks again; "kept": once the post + is kept). A topic carries watch {on, intervalMinutes, until, shots, + ticks, paused?, ended?, sentence} once it has been watched. 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, diff --git a/OPERATING.md b/OPERATING.md @@ -628,6 +628,9 @@ pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trend 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 judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"}]}' +pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}' +pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}' ``` - **X trending library** in the New channel form's Platform (`"platform": "x-trending"`) makes a private posts @@ -675,7 +678,8 @@ pnpm ops get trending trending --topic kettle-festival --limit 50 `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. + reparsed: ask once it has finished. The job asks again when it starts, and parses nothing if the read is + running by then. - **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 @@ -700,6 +704,96 @@ pnpm ops get trending trending --topic kettle-festival --limit 50 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. +- **A browser that will not close is killed, by its own pid.** The pid is the one Chromium wrote into the + profile's `SingletonLock`, and it is signalled only when that process's command line names this exact profile + directory, is a Chromium binary, is the browser itself (not one of its child processes), and the lock was + written on this machine. Anywhere but Linux, or when that check does not hold, nothing is killed: the browser + is closed again and the job's log says why. + +### Judge, keep and watch a library + +- **Judge a post**: **Keep / Drop / Later** under each post on the library's page (the operator), or + `judge-trending` (`"by": "agent"` unless told `"operator"`). `"state"` is `keep`, `drop`, `later`, or + `undecided`, which removes the judgement: a post with none is undecided. `"thread": "<root post id>"` judges a + whole thread (`get trending` gives each post's `thread`); a post's own judgement comes before its thread's. + Judgements are in `channels/<slug>/trending/judgements.json`, with who decided, when and the note. +- **An agent's judgement is a suggestion.** An agent's write over a judgement the operator made is skipped for + that id and named in `skipped`; the rest of the ask is written. The operator overturns anything. `"by"` is the + caller's word: an agent says `"agent"`. +- **Which judgement is in force.** The operator's entry, for the post or for its thread, always outranks an + agent's about the same post, whatever the order in time; between two entries of the same hand, the post's own + outranks its thread's. So an agent's post-level write is skipped whenever the post's thread is the operator's, + and an operator's thread judgement overrides an agent's older entry for one of its posts (the entry stays in + the file and decides nothing). +- **Keep archives the post.** The posts that became keep go into one `capture-posts` job on X's queue: a + screenshot, the post's context, a reply's thread shot, and its media. `"archive": false` marks only. If the + capture is refused (a stale jar, the X alert, X cooling down) the judgement is written all the same and + `archive.error` says why; `capture-posts {"slug", "ids", "thread": true, "keptMedia": true}` archives them later. + A post dropped again before that job reaches it is fetched as any post is, under the library's cap and with no + logged-in download: the judgements are read again, once per post, before its media. A library's capture runs on X's queue only (`"queueKey"` is refused). +- **Drop deletes nothing.** The post, its capture and its media stay, and a later keep puts it back. Nothing in + this release removes a capture. +- **A library's media comes from X's media CDN and is kept once.** The saved capture of the read that showed a + post names where the CDN serves its files, so the capture job asks the CDN for them: no login, no page, one file + after another 1–2 s apart, under X's 15-minute cooldown. Only `pbs.twimg.com` and `video.twimg.com` are ever + asked. Each file is stored once, by its SHA-256, in `channels/<slug>/trending/media-store/`, with a hardlink at + `trending/posts-media/<id>/<name>` and an entry in `trending/media-index.json`. The same bytes on two posts, or + in two topics, are one file; an address the library has seen is linked without a fetch. Exact duplicates only: + the same video at another quality is another file. +- **What is owed.** A job fetches at most 40 files or 200 MB; the rest is owed and the next capture of those posts + asks again. For a post nobody has kept, a file over `maxVideoMb` (100 MB) is not fetched and is owed until the + post is kept, as is a file the capture names no CDN address for. A kept post has no per-file cap, and a file the + CDN cannot serve is downloaded the logged-in way. `get trending` shows each post's `capture` and `mediaOwed`. +- **How the CDN can refuse.** A 429 stops the job at once and leaves X alone for 15 minutes. A 403 or a 404 + marks that file and the job moves on. After three refusals in a row (a 403, or no answer at all) the job asks + the CDN for nothing more and the rest is owed. Nothing retries by itself. +- **A media index that cannot be read stops the capture.** `trending/media-index.json` that is there and is not + JSON fails the job with a sentence naming the file, and nothing is written over it. Repair it or move it away. +- **The media is not in the media tier and is never committed.** No posts channel's `posts-media/` is tiered, + and a library's is not either: it stays on the corpus disk beside the library's text. `trending/.gitignore` + keeps `posts-media/` and `media-store/` out of the corpus's git repo. +- **Watch a topic**: **Watch** on the topic (the operator) or `watch-trending {"slug", "topic", "on": true}`. + The topic's trending page is read again every `intervalMinutes` (15–1440, default 30) until `hours` from now + (1–168, default 48), each tick the same single `read-x-trending` job. The editor scans once a minute and starts + at most one read per scan, the watch longest overdue, and none while a trending read, a reparse or a capture of + **any** library is queued or running. All libraries share that one stream of ticks; the cap of 4 watched topics + is per library. X's 5-minute gap between jobs applies, and a tick is a read and then a capture, so four watched + topics at 30 minutes run closer to every 40, and a second library slows both. A topic of several trending pages reads one page per + tick, in turn. At most 4 topics of a library are watched at once. +- **A watch runs only while X's cookie jar is under its limit (60 minutes).** The editor never refreshes the jar + by itself, because a refresh is a visit to X. When the jar goes stale the watch pauses: nothing is queued, X's + jar-age banner goes up on the dashboard and /cookies, and **/review** lists the paused watches. It resumes at + the first scan after **Refresh cookies** on /cookies. So a watch does not cover a night nobody presses Refresh + in. The X alert, X cooling down after a rate limit and a missing profile pause it the same way. +- **The watch's jar limit is its own.** A person's X job is let through when the login comes from the browser + (its age cannot be read), when `social.x.maxCookieAgeMinutes` is 0, or when settings cannot be read. A watch is + not: whatever the source, it ticks only when the profile's exported jar is between 0 and the limit old (the + setting when it is above 0, else 60 minutes). A jar dated in the future, or settings that cannot be read, pause + it. The rule is asked when a tick is queued and again when its job starts, and likewise for the capture that + follows a read: a tick whose turn on X's queue comes after the jar passed the limit is not read (no browser + opens), the watch pauses, and it does not count as a failed read. +- **Three failed reads pause a watch for good.** Three reads of a watched topic in a row that do not end "read" (a + rate limit, a 403, a login wall, a page that will not load) pause its watch as `failing`. That pause does not + end by itself, and only the operator ends it: press **Watch** again, or `watch-trending {"on": true, "by": + "operator"}`. An agent's ask to switch it on is refused. /review lists it. +- **New posts of a watched topic get their media at once.** After a read into a watched topic, one capture job + takes the read's new posts: their media only, from the CDN, with no page opened. The same job takes the topic's + posts whose media an earlier capture left owed, and its posts that have media and were never captured (so + switching a watch on fetches the media of what the topic already holds, 80 posts a job). `"shots": true` (**Screenshot + everything new**) also screenshots each new post, a page load apiece. +- **Gone from the page.** A post a page showed before and does not show at a read that reached the page's end is + recorded `gone` with that read's time, and shown as "Gone from the page at …". It is not called deleted: a + trending page is a ranked list, and a post leaves it by being outranked too. The end has to be in the capture: + the page asked for more from the bottom (the request carries the previous answer's bottom cursor) and got + nothing new, and no answer failed, was dropped or carried errors. A read that + stopped at a cap, was cancelled, failed, or simply stopped getting answers says nothing. A post shown again is no longer gone, and the absence is kept as history. +- **A watch ends** at its end time, when it is switched off, or when X no longer has the topic's last trending + page (trending pages expire); each with a sentence in `get trending` (`watch.sentence`). +- **The library's settings**: `watch-trending {"slug", "settings": {"maxVideoMb", "intervalMinutes", "hours", + "maxTopics"}}`. `{"slug", "tick": true}` runs one scan now; two asks at once are one scan, and an editor booted + with `ARCHILYZER_IDLE_BOOT` refuses it. +- **A restart.** A tick left queued when the editor stops is cancelled; the scan starts another at its next pass, + jar permitting. `ARCHILYZER_IDLE_BOOT` does not arm the scan at all. ## Transcribe diff --git a/common/bin/xTrendingPrivacy.test.ts b/common/bin/xTrendingPrivacy.test.ts @@ -18,7 +18,7 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -47,7 +47,7 @@ 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 { recordXTrendingRead, writeXTrendingPosts, trendingReadDir, listXTrending, readXTrendingTopics: readXTrendingTopicsOf } = await import("../lib/xTrending/store"); const { X_TRENDING_NOT_ON_A_SITE } = await import("../lib/xTrending/config"); const { open } = await import("lmdb"); @@ -59,7 +59,11 @@ 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]; +// Lane x-trending-2: the judgement's note, the captured media's bytes and +// address, the capture's context and the shot — planted below, and looked for +// in everything a build writes, like the four above. +const { plantSlice2Library, SLICE2_CAPTURES_DIRNAME, SLICE2_FILE_NAMES, SLICE2_MARK_LIST } = await import("../lib/xTrending/__fixtures__/slice2Library"); +const MARKS = [POST_MARK, HANDLE_MARK, TOPIC_MARK, RAW_MARK, ...SLICE2_MARK_LIST]; const READ = "tr-01JA0000000000000000000000"; const quiet = () => {}; @@ -110,6 +114,9 @@ await recordXTrendingRead(libRoot, { 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 planted = (await readXTrendingTopicsOf(libRoot))[0]; +await plantSlice2Library(libRoot, { postId: "1900000000000006001", topicId: planted.id }); + const site = (channels: string[]) => ({ siteId: "priv", siteTitle: "priv", siteDescription: "fixture", headerTitle: "priv", homeTagline: "", socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }], @@ -128,7 +135,7 @@ function filesUnder(dir: string): { rel: string; text: string }[] { else if (e.isFile() || (e.isSymbolicLink() && statSync(p).isFile())) out.push({ rel: path.relative(dir, p), text: readFileSync(p).toString("latin1") }); } }; - walk(dir); + if (existsSync(dir)) walk(dir); return out; } @@ -218,6 +225,26 @@ test("the library's own listing needs no index: it reads its files", async () => assert.ok(!JSON.stringify(listing).includes(RAW_MARK)); }); +// Lane x-trending-2. +test("what a keep, a capture and a watch leave in a library is in no build: not its words, not its bytes, not a file of its name", async () => { + // Planted for real: the files exist, where the editor leaves them. + for (const rel of ["judgements.json", "watch.json", "media-index.json", "posts-availability.json", ".gitignore", path.join(SLICE2_CAPTURES_DIRNAME, "1900000000000006001", "capture.json")]) { + assert.ok(existsSync(path.join(libRoot, "trending", rel)), `${rel} was planted`); + } + const built = [...filesUnder(paths.exportIndexDir), ...filesUnder(paths.exportPublicDir)]; + assert.ok(built.length > 0, "the builds above wrote files"); + assertNoLeak(built, "index and public dirs"); + for (const f of built) { + for (const name of SLICE2_FILE_NAMES) { + assert.ok(!f.rel.split(path.sep).includes(name), `a build wrote ${f.rel}`); + } + } + // The library's own listing does carry the judgement — and that is the only door. + const listing = await listXTrending(libRoot); + assert.equal(listing.posts[0].judgement?.state, "keep"); + assert.equal(listing.topics[0].watch?.on, true); +}); + 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")); diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -484,3 +484,188 @@ test("context (X): read by default with each post's archived parent and quoted i assert.equal(calls.length, 0); answer = { outcomes: [] }; }); + +// Lane x-trending-2: an X trending library is captured one directory down. +test("an X trending library: its posts, captures and availability are under trending/, never in the channel's own", async () => { + const root = path.join(channelsDir, "demo-library"); + await mkdir(path.join(root, "trending"), { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "test-capture-x", name: "Library", xTrending: {} }), + ); + await writeFile(path.join(root, "trending", "posts-archive"), "twitter 7001\ntwitter 7002\n"); + // An id in the channel's OWN archive is not the library's: refused as stray. + await writeFile(path.join(root, "posts-archive"), "twitter 7999\n"); + calls = []; + answer = { outcomes: [] }; + const stray = await run("demo-library", ["7999"]); + assert.equal(stray.ok, false); + assert.match(stray.error ?? "", /1 id\(s\) not in demo-library's posts archive: 7999/); + assert.equal(calls.length, 0); + + answer = { outcomes: [{ id: "7001", state: "deleted", availability: "deleted", files: 0 }] }; + const res = await run("demo-library", ["7001", "7002"], { articles: false, context: false }); + assert.equal(res.ok, true, res.error); + assert.equal(calls.length, 1); + assert.equal(calls[0].outDir, path.join(root, "trending", "posts-media")); + // A library has no account: its slug stands for the handle, as a search channel's does. + assert.equal(calls[0].handle, "demo-library"); + assert.equal((await readPostAvailability(path.join(root, "trending")))["7001"]?.availability, "deleted"); + assert.deepEqual(await readPostAvailability(root), {}); +}); + +test("an X trending library's media comes from the CDN addresses in its saved capture, kept once, and is ignored by the corpus repo", async () => { + const { fixtureTimelineBody } = await import("../social/__fixtures__/xTrendingCapture"); + const { recordXTrendingRead, trendingReadDir, writeXTrendingPosts } = await import("../lib/xTrending/store"); + const { readXTrendingMediaIndex } = await import("../lib/xTrending/mediaStore"); + const { parseTrendingCapture } = await import("../social/xTrendingParse"); + const { readFile, stat } = await import("node:fs/promises"); + const root = path.join(channelsDir, "demo-library-media"); + await mkdir(path.join(root, "trending"), { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "test-capture-x", name: "Library", xTrending: {} }), + ); + // One saved read: a post with two pictures, a post with a video, a post with none. + const READ = "tr-01JA0000000000000000000000"; + const A = "1900000000000003001"; + const B = "1900000000000003002"; + const C = "1900000000000003003"; + const line = { + n: 1, + at: "2026-11-18T10:00:00.000Z", + op: "ExampleTrendTimeline", + status: 200, + url: "u", + bytes: 1, + body: fixtureTimelineBody([ + { id: A, handle: "teapot_news", text: "Two pictures.", media: ["photo", "photo"] }, + { id: B, handle: "spout_clips", text: "A video.", media: ["video"] }, + { id: C, handle: "lid_watch", text: "Words only." }, + ]), + }; + await mkdir(trendingReadDir(root, READ), { recursive: true }); + await writeFile(path.join(trendingReadDir(root, READ), "responses.jsonl"), JSON.stringify(line) + "\n"); + const parsed = parseTrendingCapture([line], "demo-library-media"); + await writeXTrendingPosts(root, parsed.posts); + await recordXTrendingRead(root, { + readId: READ, + at: "2026-11-18T10:00:00.000Z", + ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }, + topic: "Kettles", + postIds: parsed.posts.map((p) => p.id), + added: 3, + media: parsed.media, + }); + + // The stand-in fetcher runs the media half it was handed, as X's does. + const asked: string[] = []; + const results: Record<string, unknown> = {}; + const { getSocialFetcher } = await import("../social/fetchers"); + const fake = getSocialFetcher("test-capture-x")!; + const original = fake.captureByIds!; + fake.captureByIds = async (input) => { + calls.push(input); + assert.equal(typeof input.downloadMedia, "function"); + for (const id of input.ids) { + results[id] = await input.downloadMedia!( + { id, dir: path.join(input.outDir, id), signal: new AbortController().signal }, + async () => { + throw new Error("no logged-in download for a post nobody kept"); + }, + ); + } + return { outcomes: [] }; + }; + calls = []; + try { + const res = await run("demo-library-media", [A, B, C], { + shots: false, + articles: false, + context: false, + libraryMedia: { + deps: { + fetch: async (url: string) => { + asked.push(url); + const bytes = Buffer.from(`BYTES OF ${url.includes("video") ? "VIDEO" : "PICTURE"}`); + return { status: 200, headers: { get: () => String(bytes.length) }, body: (async function* () { yield bytes; })() }; + }, + pause: async () => {}, + cooldownMs: async () => 0, + }, + }, + }); + assert.equal(res.ok, true, res.error); + } finally { + fake.captureByIds = original; + } + assert.equal(calls[0].outDir, path.join(root, "trending", "posts-media")); + assert.deepEqual(asked, [ + "https://pbs.twimg.com/media/Fixture30010?format=jpg&name=orig", + "https://pbs.twimg.com/media/Fixture30011?format=jpg&name=orig", + `https://video.twimg.com/ext_tw_video/${B}0/vid/1280x720/high.mp4`, + ]); + assert.deepEqual((results[A] as { files: { name: string }[] }).files.map((f) => f.name), [`${A}_1.jpg`, `${A}_2.jpg`]); + assert.deepEqual(results[C], { ok: true, files: [] }); + // The two pictures had the same bytes: one blob, two names. + const one = await stat(path.join(root, "trending", "posts-media", A, `${A}_1.jpg`)); + const two = await stat(path.join(root, "trending", "posts-media", A, `${A}_2.jpg`)); + assert.equal(one.ino, two.ino); + assert.equal(Object.keys((await readXTrendingMediaIndex(root)).blobs).length, 2); + assert.match(await readFile(path.join(root, "trending", ".gitignore"), "utf8"), /^posts-media\/$/m); +}); + +// Review 1 M4: the still-kept check reaches the media half. +test("an X trending library's logged-in fallback asks, per post and at that moment, whether it may", async () => { + const { recordXTrendingRead, writeXTrendingPosts } = await import("../lib/xTrending/store"); + const root = path.join(channelsDir, "demo-library-kept"); + await mkdir(path.join(root, "trending"), { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "test-capture-x", name: "Library", xTrending: {} }), + ); + const post = (id: string) => ({ + id, slug: `demo-library-kept/${id}`, channelSlug: "demo-library-kept", author: "a", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", + text: "t", url: `https://x.com/a/status/${id}`, platform: "twitter" as const, isReply: false, isRepost: false, links: [], + }); + await writeXTrendingPosts(root, [post("8001"), post("8002")]); + // Media the saved captures name no address for: only a login could fetch it. + await recordXTrendingRead(root, { + readId: "tr-01JA0000000000000000000000", at: "2026-11-18T10:00:00.000Z", + ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }, + topic: "T", postIds: ["8001", "8002"], added: 2, + media: { "8001": { count: 1, kinds: ["video"] }, "8002": { count: 1, kinds: ["video"] } }, + }); + const { getSocialFetcher } = await import("../social/fetchers"); + const fake = getSocialFetcher("test-capture-x")!; + const original = fake.captureByIds!; + const logins: string[] = []; + const results: Record<string, { ok: boolean }> = {}; + fake.captureByIds = async (input) => { + for (const id of input.ids) { + results[id] = await input.downloadMedia!({ id, dir: path.join(input.outDir, id), signal: new AbortController().signal }, async () => { + logins.push(id); + return { ok: true, files: [] }; + }); + } + return { outcomes: [] }; + }; + const asked: string[] = []; + try { + const res = await run("demo-library-kept", ["8001", "8002"], { + shots: false, articles: false, context: false, + libraryMedia: { + fallback: "login", + // 8002 was dropped after the job was queued. + isKept: async (id: string) => (asked.push(id), id === "8001"), + deps: { cooldownMs: async () => 0, pause: async () => {} }, + }, + }); + assert.equal(res.ok, true, res.error); + } finally { + fake.captureByIds = original; + } + assert.deepEqual(asked, ["8001", "8002"]); + assert.deepEqual(logins, ["8001"]); + assert.deepEqual([results["8001"].ok, results["8002"].ok], [true, false]); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -14,6 +14,13 @@ // archived text and links go to the fetcher with it, so a post that is an X // Article's link is known as one before its page is opened. // +// AN X TRENDING LIBRARY (lane x-trending-2) is captured through this same +// job, one directory down: its posts are under `channels/<lib>/trending/` +// (lib/xTrending/store.ts xTrendingPostsRoot says why), so its captures land +// in `trending/posts-media/<id>/` and its availability in +// `trending/posts-availability.json`. The marker alone decides — no caller +// can capture a library into the channel's own `posts-media/`. +// // X also keeps the posts' AUTHORS' AVATARS, read off the page the shot loads, // in `posts-media/_avatars/` (social/xAvatars.ts has the store): on by // default (`avatars: false` turns it off), and `avatarsOnly` loads one page @@ -27,6 +34,24 @@ import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; +import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; +import { + readXTrendingMembership, + TRENDING_RESPONSES_FILENAME, + trendingReadDir, + xTrendingPostsRoot, +} from "../lib/xTrending/store"; +import { ensureXTrendingMediaIgnore } from "../lib/xTrending/mediaStore"; +import { platformCooldownRemainingMs, recordPlatformCooldown } from "../jobs/downloadBackoff"; +import type { ChromiumLike } from "../social/playwrightRuntime"; +import { + createLibraryMediaDownloader, + libraryMediaPauseMs, + type LibraryMediaDeps, + type MediaFetch, +} from "../social/xTrendingMedia"; +import { mediaSourcesInCapture, readCaptureLines, type TrendingMediaSource } from "../social/xTrendingParse"; +import { X_RATE_LIMIT_HOLD_MS } from "./readXTrending"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; import type { Post, PostAvailability } from "../lib/posts"; @@ -44,6 +69,7 @@ import { writePostAvailability, } from "../lib/posts-server"; import { + getSocialFetcher, handleFromAccountUrl, resolveSocialFetcher, type PostCaptureOutcome, @@ -105,6 +131,28 @@ export type CapturePostsOptions = { // A Wayback pages channel's render and archive (tests; default the // process's Wayback client and a headless Chromium). pageDeps?: WaybackPageCaptureDeps; + // AN X TRENDING LIBRARY'S MEDIA HALF (social/xTrendingMedia.ts): the files + // come from X's media CDN, by the addresses in the library's saved + // captures, and are kept once. + // fallback "login": a post the CDN could not serve whole is + // downloaded the logged-in way (a post marked keep). + // Default "none" (a watch never logs in for media). + // maxVideoBytes a file over this is owed, not kept; null = no cap (a + // kept post). Default: the library's `maxVideoMb`. + // deps tests and the e2e test server: the fetch and the waits. + // isKept whether a post is STILL marked keep, asked once per + // post before its media (review 1 M4, review 2 N3): only + // then has it no per-file cap and the logged-in fallback. + // With it, `maxVideoBytes` is the cap of a post that is + // no longer kept (the library's, by default). + libraryMedia?: { + fallback?: "login" | "none"; + isKept?: (id: string) => Promise<boolean>; + maxVideoBytes?: number | null; + deps?: Partial<LibraryMediaDeps>; + }; + // X: the browser the profile is opened with (the e2e suite's fake). + chromium?: ChromiumLike; }; export type CapturePostsResult = { @@ -193,13 +241,16 @@ export function strayIdsRefusal(slug: string, stray: string[]): string { return `${stray.length} id(s) not in ${slug}'s posts archive: ${stray.join(", ")}`; } +// The fetcher that captures an X trending library's posts. +export const X_LIBRARY_FETCHER = "x-gallery-dl"; + export async function capturePosts( opts: CapturePostsOptions, ): Promise<CapturePostsResult> { const { paths, slug, settings, onLog } = opts; const log = (line: string) => onLog?.(line); const fail = (error: string): CapturePostsResult => ({ ok: false, outcomes: [], error }); - const channelRoot = path.join(paths.channelsDir, slug); + const channelDir = path.join(paths.channelsDir, slug); const ids = [...new Set(opts.ids)]; if (nothingToCapture(opts)) return fail(NOTHING_TO_CAPTURE); @@ -214,11 +265,19 @@ export async function capturePosts( if (isWaybackPagesChannel(config)) { if (opts.avatarsOnly) return fail(avatarsOnlyProblem(undefined, "a Wayback pages channel")!); if (opts.contextOnly) return fail(contextOnlyProblem(undefined, "a Wayback pages channel", opts)!); - return captureChannelPageRecords(opts, channelRoot, ids); + return captureChannelPageRecords(opts, channelDir, ids); } + // WHERE THIS CHANNEL'S POSTS, CAPTURES AND AVAILABILITY LIVE: the channel's + // own directory — or, for an X trending library, its trending/ directory. + const library = isXTrendingChannel(config); + const channelRoot = library ? xTrendingPostsRoot(channelDir) : channelDir; + const accountUrl = config.url ?? ""; - const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl); + // A library has no account URL to tell its fetcher by: X's own. + const fetcher = library + ? (getSocialFetcher(config.postFetcher) ?? getSocialFetcher(X_LIBRARY_FETCHER)) + : resolveSocialFetcher(config.postFetcher, accountUrl); const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); const avatarsOnly = opts.avatarsOnly === true; @@ -239,7 +298,7 @@ export async function capturePosts( // The thread shot: X only, the run's word or the channel's default. const thread = fetcher.platform === "twitter" ? (opts.thread ?? config.postCaptureThread ?? false) : false; if (opts.thread && fetcher.platform !== "twitter") log(`Thread shots are X's only; ${fetcher.label} takes none.`); - const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) ? slug : ""); + const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) || library ? slug : ""); if (!handle) return fail(`Could not determine an account handle for ${slug}`); const stray = strayCaptureIds(ids, await readSeenPostIds(channelRoot)); @@ -328,10 +387,19 @@ export async function capturePosts( ".", ); + // A library's media: from the CDN addresses in its saved captures. + const libraryDownload = + library && opts.media !== false && !avatarsOnly && !contextOnly + ? await libraryMediaDownloader(paths, channelDir, ids, config.xTrending, opts.libraryMedia, log) + : undefined; + if (library) await ensureXTrendingMediaIgnore(channelDir); + const controller = new AbortController(); let result; try { result = await fetcher.captureByIds({ + ...(libraryDownload ? { downloadMedia: libraryDownload } : {}), + ...(opts.chromium ? { chromium: opts.chromium } : {}), ids, handle, accountUrl, @@ -425,6 +493,75 @@ export async function capturePosts( return { ok: true, outcomes: result.outcomes, ...avatars }; } +const waitFor = (ms: number, signal: AbortSignal) => + new Promise<void>((resolve) => { + if (ms <= 0 || signal.aborted) return resolve(); + const done = () => { + clearTimeout(t); + signal.removeEventListener("abort", done); + resolve(); + }; + const t = setTimeout(done, ms); + signal.addEventListener("abort", done, { once: true }); + }); + +// The library's media half for these ids: where the CDN serves each post's +// files, read from the saved captures of the reads that showed the post +// (newest first; a read is parsed once), and the downloader over them. +async function libraryMediaDownloader( + paths: Paths, + channelDir: string, + ids: ReadonlyArray<string>, + config: XTrendingConfig | undefined, + asked: CapturePostsOptions["libraryMedia"], + log: (line: string) => void, +) { + const membership = await readXTrendingMembership(channelDir); + const sources = new Map<string, TrendingMediaSource[]>(); + const expected = new Map<string, number>(); + const parsed = new Map<string, Map<string, TrendingMediaSource[]>>(); + for (const id of ids) { + const member = membership[id]; + if (!member) continue; + if (member.media?.count) expected.set(id, member.media.count); + const reads = [...member.seen].sort((a, b) => (a.at < b.at ? 1 : -1)).map((s) => s.read); + for (const read of reads) { + let found = parsed.get(read); + if (!found) { + const file = path.join(trendingReadDir(channelDir, read), TRENDING_RESPONSES_FILENAME); + found = mediaSourcesInCapture(await readCaptureLines(file).catch(() => [])); + parsed.set(read, found); + } + const have = found.get(id); + if (have?.length) { + sources.set(id, have); + break; + } + } + } + const withMedia = [...expected.keys()].length; + if (withMedia > 0) { + log(`Media: ${sources.size} of ${withMedia} post(s) with media have CDN addresses in the saved captures (${parsed.size} read(s) looked at).`); + } + const X = "twitter"; + return createLibraryMediaDownloader({ + channelRoot: channelDir, + sources, + expected, + maxVideoBytes: asked?.maxVideoBytes === undefined ? xTrendingMaxVideoBytes(config) : asked.maxVideoBytes, + fallback: asked?.fallback ?? "none", + ...(asked?.isKept ? { isKept: asked.isKept } : {}), + deps: { + fetch: (url, init) => fetch(url, init) as unknown as ReturnType<MediaFetch>, + pauseMs: () => libraryMediaPauseMs(), + pause: waitFor, + cooldownMs: () => platformCooldownRemainingMs(X, paths), + noteRateLimit: () => recordPlatformCooldown(X, X_RATE_LIMIT_HOLD_MS, paths), + ...asked?.deps, + }, + }); +} + // capture-posts on a Wayback pages channel: the records' shots from their // captures' replays (social/waybackPageCapture.ts). Only ids in the channel's // posts archive; nothing is recorded in the availability sidecar (a capture diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -15,6 +15,7 @@ import { FIXTURE_TIMELINE_OP, FIXTURE_TREND_ID, FIXTURE_TREND_URL, + fixtureContinuation, fixtureTimelineBody, fixtureTrendingResponses, } from "../social/__fixtures__/xTrendingCapture"; @@ -159,14 +160,28 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit const paths = corpus("reread"); const first = fixtureTrendingResponses(); await run(paths, { load: first.load, scrolls: [] }); + // The page's end, as the capture shows it: asked for more, the timeline had none. + const nothingMore = fixtureContinuation(); const again = await run( paths, - { load: [first.scrolls[0][0]], scrolls: [] }, + { load: [first.scrolls[0][0]], scrolls: [[nothingMore]] }, {}, { 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); + // Lane x-trending-2: the ids it added; and, the read having reached the + // page's end, the posts the page showed before and not now — gone FROM THE + // PAGE, at the read's time, never "deleted". + assert.equal(again.result.stop, "idle"); + assert.deepEqual(again.result.newIds, ["1900000000000001005"]); + // Each post's thread is kept with its place: 1005 answers 1001. + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.equal(members["1900000000000001005"].thread, "1900000000000001001"); + assert.equal(members["1900000000000001004"].thread, "1900000000000001004"); + assert.deepEqual([...(again.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); + assert.match(again.result.sentence, /2 posts this page showed before are gone from the page at 12:00 UTC\.$/); + assert.doesNotMatch(again.result.sentence, /delet/i); const listing = await listXTrending(root(paths)); assert.equal(listing.total, 4); assert.deepEqual(listing.topics[0].sources, [ @@ -513,3 +528,70 @@ test("N7: a reparse of a read that is still running is refused; of one that died }); assert.equal((dead as unknown as { ok: boolean }).ok, true); }); + +// Lane x-trending-2: the same refusal INSIDE the job. +test("a reparse whose read is still running when the job starts parses nothing and leaves the read's record alone", async () => { + const paths = corpus("running-in-job"); + const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + let inJob: Awaited<ReturnType<typeof reparseXTrendingRead>> | null = null; + let recordThen: unknown = null; + await run(paths, fixtureTrendingResponses(), {}, { + openPage: (async () => { + // Planned as though no read were in flight (the plan can be old) — and + // run while the read is: the job itself refuses. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); + assert.equal(planned.ok, true); + if (planned.ok && planned.plan.mode === "reparse") { + inJob = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); + recordThen = await readXTrendingReadRecord(root(paths), READ_1); + } + return { page, close: async () => {} }; + }) as never, + }); + const refused = inJob as unknown as { ok: boolean; outcome: string; sentence: string; posts: { onPage: number; added: number } }; + assert.equal(refused.ok, false); + assert.equal(refused.outcome, "error"); + assert.match(refused.sentence, new RegExp(`^Read ${READ_1} is still running: its capture is still being written\\..*Nothing was parsed or written\\.$`)); + assert.deepEqual(refused.posts, { onPage: 0, added: 0 }); + assert.equal((recordThen as { stop: string }).stop, "started"); + // Once the read has ended, the same reparse goes through. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }, { readInFlight: async () => false }); + assert.equal(planned.ok, true); + if (planned.ok && planned.plan.mode === "reparse") { + const done = await reparseXTrendingRead({ plan: planned.plan, readInFlight: async () => true }); + assert.equal(done.ok, true); + } +}); + +// Review 1 S2: "idle" is not the page's end. +test("S2: a read that went idle without the capture showing the page's end marks nothing gone", async () => { + const first = fixtureTrendingResponses(); + const timeline = first.scrolls[0][0]; + const reread = async (name: string, second: FakeTrendingPage) => { + const paths = corpus(name); + await run(paths, { load: first.load, scrolls: [] }); + return run(paths, second, {}, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + }; + // The scrolls simply brought no further answer (a next page that never loaded looks the same). + const silent = await reread("s2-silent", { load: [timeline], scrolls: [[], []] }); + assert.equal(silent.result.stop, "idle"); + assert.equal(silent.result.outcome, "read"); + assert.equal(silent.result.gone, undefined); + assert.doesNotMatch(silent.result.sentence, /gone from the page/); + // An answer with nothing new that was not asked from the bottom (review 2 N4): nothing. + const fromTop = await reread("s2-from-top", { load: [timeline], scrolls: [[{ url: first.load[1].url, status: 200, body: fixtureTimelineBody([]) }], []] }); + assert.equal(fromTop.result.gone, undefined); + // The next page answered 500: the read still ends idle, and asserts nothing. + const failed = await reread("s2-failed", { load: [timeline], scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], []] }); + assert.equal(failed.result.stop, "idle"); + assert.equal(failed.result.gone, undefined); + // ...even when an empty page follows the failure. + const after500 = await reread("s2-failed-then-empty", { + load: [timeline], + scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], [fixtureContinuation()]], + }); + assert.equal(after500.result.gone, undefined); + // Asked for more and answered "none", cleanly: the page's end. + const ended = await reread("s2-end", { load: [timeline], scrolls: [[fixtureContinuation()], []] }); + assert.deepEqual([...(ended.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -54,7 +54,10 @@ import { import { ensureXTrendingReadsDir, isXTrendingReadId, + readXTrendingPostIds, + readXTrendingPosts, readXTrendingReadRecord, + xTrendingThreadKey, recordXTrendingRead, topicTitleProblem, TRENDING_DIRNAME, @@ -125,6 +128,11 @@ export type ReadXTrendingAsk = { posts?: unknown; probe?: boolean; headed?: boolean; + // THIS READ IS A WATCH'S TICK (controller/xTrendingWatch.ts): nobody is + // there when it starts, so the watch's own jar rule is asked again at its + // start (runXTrendingRead `watchRefusal`). Set by the scan only — the ops + // route does not take it. + watch?: boolean; }; export type ReadXTrendingPlan = @@ -137,6 +145,7 @@ export type ReadXTrendingPlan = topic?: string; probe: boolean; headed: boolean; + watch?: boolean; } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; @@ -253,6 +262,7 @@ export async function planReadXTrending( ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, + ...(ask.watch === true ? { watch: true } : {}), }, }; } @@ -275,6 +285,15 @@ export type ReadXTrendingResult = { operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; topic?: { id: string; title: string; created?: boolean }; + // A watch's tick that was NOT read, because the watch's jar rule refused it + // at the job's start: no browser opened, nothing asked of X. It is neither + // a read nor a failed read (the watch counts no strike for it). + watchRefused?: { reason: string; sentence: string }; + // The posts this read added to the library (ids), and the posts the page + // showed before and did not show now — "gone from the page", said only by a + // read that reached the page's end, and never meaning deleted. + newIds?: string[]; + gone?: string[]; // What happened, as one sentence (the refusal, when `ok` is false). sentence: string; error?: string; @@ -300,6 +319,10 @@ type Ingested = { onPage: number; added: number; topic?: { id: string; title: string; created: boolean }; + // The posts this pass added to the library, and — after a read that reached + // the page's end — the posts the page showed before and not now. + newIds?: string[]; + gone?: string[]; }; // The saved capture → the library: its posts written, the read recorded. @@ -312,14 +335,28 @@ async function ingestCapture(o: { ref: XTrendingRef; topic?: string; write: boolean; + // The read reached the page's end (store.ts: only then is a post it did + // not show marked gone from the page). Never set by a reparse. + complete?: 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 had = await readXTrendingPostIds(o.channelRoot); + const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id)); const written = await writeXTrendingPosts(o.channelRoot, parsed.posts); + // A THREAD'S KEY IS DECIDED ONCE, when a post is first placed, and kept in + // its membership record (store.ts): it does not move as ancestors arrive. + const byId = new Map((await readXTrendingPosts(o.channelRoot)).map((p) => [p.id, p])); + const threads: Record<string, string> = {}; + for (const p of parsed.posts) threads[p.id] = xTrendingThreadKey(byId.get(p.id) ?? p, byId); const recorded = await recordXTrendingRead(o.channelRoot, { + threads, + // Only when the scrolling stopped at the page's end AND the capture shows + // it (review 1 S2: "idle" alone also follows a next page that failed). + ...(o.complete && parsed.pageEnd ? { complete: true } : {}), readId: o.readId, at: o.at, ref: o.ref, @@ -328,7 +365,7 @@ async function ingestCapture(o: { added: written.written, media: parsed.media, }); - return { ...base, added: written.written, topic: recorded.topic }; + return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone }; } export type ReadXTrendingDeps = { @@ -349,6 +386,13 @@ export type ReadXTrendingDeps = { noteRateLimit?: () => Promise<number>; // For tests: the capture → library step (default: ingestCapture). ingest?: typeof ingestCapture; + // A WATCH'S TICK, AT ITS START (review 2 N1): why the watch may not read + // now, by its own jar rule (xTrendingWatch.ts refuseWatchJob), or null. The + // scan asked when it queued the tick; the job may start much later (X's + // gap, another X job ahead of it), and the guard a person's job meets lets + // through what a watch must not. A plan marked `watch` with no check here + // does not run. + watchRefusal?: () => Promise<{ reason: string; sentence: string } | null>; }; export async function runXTrendingRead(o: { @@ -377,6 +421,16 @@ export async function runXTrendingRead(o: { // 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 }; + if (plan.watch) { + const refused = deps.watchRefusal + ? await deps.watchRefusal() + : { reason: "refused", sentence: "This watch tick was started with no check of X's cookie jar, so it is not run." }; + if (refused) { + const sentence = `This watch tick was not read (no browser was opened, X was asked nothing): ${refused.sentence}`; + log(sentence); + return { ...base, ...none, ok: false, outcome: "error", sentence, error: sentence, watchRefused: refused }; + } + } // 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())))(); @@ -395,6 +449,7 @@ export async function runXTrendingRead(o: { endedAt: startedAt, probe: plan.probe, headed: plan.headed, + ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: 0, stop: "started", @@ -412,7 +467,8 @@ export async function runXTrendingRead(o: { 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." : "."), + (plan.probe ? " — a probe: the capture is saved, no post is written." : ".") + + (plan.watch ? " A watch's tick." : ""), ); const dir = trendingReadDir(plan.channelRoot, readId); const page: TrendingPageRead = await readXTrendingPage({ @@ -450,6 +506,13 @@ export async function runXTrendingRead(o: { ref: plan.ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !plan.probe && !walled, + // "idle": two scrolls brought no new post — the page's end, OR a next + // page that did not load. So also: no answer that failed, none that was + // not kept; and the capture itself must show the end (ingestCapture). + complete: + page.stop === "idle" && + page.saved === page.responses && + Object.keys(page.statuses).every((status) => /^2\d\d$/.test(status)), }); } catch (err) { ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0]; @@ -534,7 +597,10 @@ export async function runXTrendingRead(o: { 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." : "."); + (page.stop === "cancelled" ? "; the read was stopped early." : ".") + + (ingested.gone?.length + ? ` ${plural(ingested.gone.length, "post")} this page showed before ${ingested.gone.length === 1 ? "is" : "are"} gone from the page at ${hhmm(Date.parse(startedAt))} UTC.` + : ""); // 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); @@ -552,6 +618,7 @@ export async function runXTrendingRead(o: { endedAt: new Date(now()).toISOString(), probe: plan.probe, headed: plan.headed, + ...(plan.watch ? { watch: true as const } : {}), limits: plan.limits, scrolls: page.scrolls, stop: page.stop, @@ -580,6 +647,8 @@ export async function runXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), + ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}), + ...(ingested.gone?.length ? { gone: ingested.gone } : {}), sentence, ...(ok ? {} : { error: sentence }), }; @@ -591,6 +660,11 @@ export async function reparseXTrendingRead(o: { plan: Extract<ReadXTrendingPlan, { mode: "reparse" }>; onLog?: (line: string) => void; now?: () => number; + // Whether a read of this library is queued or running NOW (the editor asks + // its registry). Asked INSIDE the job too (lane x-trending-2), not only at + // enqueue: a reparse moved to another queue can start beside the read whose + // capture it would parse half-written. + readInFlight?: () => Promise<boolean>; }): Promise<ReadXTrendingResult> { const { plan } = o; const log = o.onLog ?? (() => {}); @@ -600,6 +674,24 @@ export async function reparseXTrendingRead(o: { // 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 }; + if (record.stop === "started" && (await o.readInFlight?.())) { + const sentence = `Read ${record.id} is still running: its capture is still being written. Parse it again once it has finished (its job is on /jobs). Nothing was parsed or written.`; + log(sentence); + return { + ok: false, + slug: plan.slug, + mode: "reparse", + url: record.url, + trendId: record.trendId, + read: record.id, + outcome: "error", + responses: 0, + operations: [], + posts: { onPage: 0, added: 0 }, + sentence, + error: sentence, + }; + } const walled = record.outcome === "login-wall"; const ingested = await ingestCapture({ channelRoot: plan.channelRoot, diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts @@ -0,0 +1,549 @@ +// The watch scan over temp libraries and stand-in deps: nothing here opens a +// browser, enqueues a real job or asks X anything. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatch.test.ts + +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 type { Paths } from "../lib/paths"; +import { readXTrendingTopics, recordXTrendingRead, TRENDING_DIRNAME, writeXTrendingPosts } from "../lib/xTrending/store"; +import { describeXTrendingWatch, readXTrendingWatches, setXTrendingWatch, xTrendingWatchPath } from "../lib/xTrending/watch"; +import { xTrendingWatchTerms } from "../lib/xTrending/config"; +import type { Post } from "../lib/posts"; +import { + armXTrendingWatch, + disarmXTrendingWatch, + isXTrendingWatchArmed, + noteXTrendingWatchRead, + pausedXTrendingWatches, + runXTrendingWatchScan, + scanXTrendingWatches, + watchRefusal, + xTrendingWatchFollowUp, + type WatchRefusal, + type WatchScanDeps, + type WatchTick, +} from "./xTrendingWatch"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-watch-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const T0 = Date.parse("2026-11-18T10:00:00.000Z"); +const MIN = 60_000; +const trend = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); +const readId = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; + +function post(id: string): Post { + return { + id, + slug: `lib/${id}`, + channelSlug: "lib", + author: "kettle_fan", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: `post ${id}`, + url: `https://x.com/kettle_fan/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }; +} + +let n = 0; +// A corpus with libraries; each topic gets one read of one page per `pages`. +async function corpus(libs: Record<string, Record<string, number[]>>): Promise<Paths> { + const dir = path.join(TMP, `c${++n}`); + const paths = { transcriptsDir: dir, channelsDir: path.join(dir, "channels") } as Paths; + let r = 0; + for (const [slug, topics] of Object.entries(libs)) { + const root = path.join(paths.channelsDir, slug); + mkdirSync(root, { recursive: true }); + writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); + for (const [topic, pages] of Object.entries(topics)) { + for (const p of pages) { + const id = `9${p}0${++r}`; + await writeXTrendingPosts(root, [post(id)]); + await recordXTrendingRead(root, { readId: readId(r), at: new Date(T0 - 60 * MIN).toISOString(), ref: trend(p), topic, postIds: [id], added: 1 }); + } + } + } + return paths; +} + +type Harness = { deps: WatchScanDeps; ticks: WatchTick[]; state: { now: number; refusal: WatchRefusal | null; busy: Set<string>; refuse: string | null; jar: string[] } }; + +function harness(paths: Paths, libraries: string[]): Harness { + const ticks: WatchTick[] = []; + const state: Harness["state"] = { now: T0, refusal: null, busy: new Set(), refuse: null, jar: [] }; + return { + ticks, + state, + deps: { + paths, + now: () => state.now, + libraries: async () => libraries, + busy: () => state.busy.size > 0, + refusal: async () => state.refusal, + enqueue: async (tick) => { + if (state.refuse) return { ok: false, error: state.refuse }; + ticks.push(tick); + return { ok: true, jobId: `job-${ticks.length}` }; + }, + noteJarStale: async (line) => void state.jar.push(line), + jitter: () => 0, + }, + }; +} + +const root = (paths: Paths, slug = "lib") => path.join(paths.channelsDir, slug); +const on = async (paths: Paths, topic: string, over: Partial<Parameters<typeof setXTrendingWatch>[1]> = {}, slug = "lib") => + setXTrendingWatch(root(paths, slug), { topics: await readXTrendingTopics(root(paths, slug)), topic, on: true, intervalMinutes: 30, hours: 48, by: "agent", maxTopics: 4, now: T0, ...over }); + +test("the switch: a topic with a page is watched with an interval and an end time; at most the library's limit; off ends it", async () => { + const paths = await corpus({ lib: { Kettles: [1], Saucers: [2], Lids: [3] } }); + const first = await on(paths, "Kettles"); + assert.equal(first.ok, true); + if (!first.ok) return; + assert.equal(first.topic, "kettles"); + assert.deepEqual( + { on: first.watch.on, intervalMinutes: first.watch.intervalMinutes, until: first.watch.until, shots: first.watch.shots, ticks: first.watch.ticks }, + { on: true, intervalMinutes: 30, until: "2026-11-20T10:00:00.000Z", shots: false, ticks: 0 }, + ); + assert.match(describeXTrendingWatch(first.watch, T0), /^Watched every 30 min until 2026-11-20 10:00 UTC; 0 ticks so far, next at the next scan\.$/); + // By title too; a topic that does not exist is refused by name. + assert.equal((await on(paths, "saucers", { maxTopics: 2 })).ok, true); + const none = await on(paths, "Spouts"); + assert.equal(none.ok, false); + assert.match(none.ok ? "" : none.error, /no topic "Spouts" \(its topics: kettles, saucers, lids\)/); + // The limit counts the OTHER live watches. + const third = await on(paths, "Lids", { maxTopics: 2 }); + assert.match(third.ok ? "" : third.error, /already watches 2 topics \(at most 2\)/); + // Switching a live one on again changes its terms and is not a new watch. + const again = await on(paths, "Kettles", { intervalMinutes: 60, shots: true, maxTopics: 2, now: T0 + 5 * MIN }); + assert.equal(again.ok && again.watch.intervalMinutes, 60); + assert.equal(again.ok && again.watch.shots, true); + assert.equal(again.ok && again.watch.startedAt, "2026-11-18T10:00:00.000Z"); + // Off. + const off = await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 + 6 * MIN }); + assert.equal(off.ok && off.watch.ended?.sentence, 'The watch of "Kettles" was switched off.'); + assert.match((await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 })).ok ? "" : "not watched", /not watched/); + // Now there is room for the third. + assert.equal((await on(paths, "Lids", { maxTopics: 2 })).ok, true); +}); + +test("the watch's terms: the ask's, else the library's, else 30 minutes and 48 hours; out of range is refused", () => { + assert.deepEqual(xTrendingWatchTerms(undefined), { ok: true, terms: { intervalMinutes: 30, hours: 48 } }); + assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45, watchHours: 12 }), { ok: true, terms: { intervalMinutes: 45, hours: 12 } }); + assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45 }, { intervalMinutes: 20, hours: 6 }), { ok: true, terms: { intervalMinutes: 20, hours: 6 } }); + const short = xTrendingWatchTerms(undefined, { intervalMinutes: 5 }); + assert.match(short.ok ? "" : short.error, /"intervalMinutes" is a whole number, 15–1440/); + const long = xTrendingWatchTerms(undefined, { hours: 169 }); + assert.match(long.ok ? "" : long.error, /"hours" is a whole number, 1–168/); +}); + +test("one scan starts at most one read — the longest overdue — and the next tick is an interval away, never sooner", async () => { + const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] }, other: { Lids: [3] } }); + await on(paths, "Kettles", { now: T0 - 10 * MIN }); + await on(paths, "Saucers", { now: T0 - 20 * MIN }); + await on(paths, "Lids", { now: T0 - 5 * MIN }, "other"); + const h = harness(paths, ["lib", "other"]); + const first = await scanXTrendingWatches(h.deps); + assert.deepEqual(h.ticks, [{ slug: "lib", topic: "saucers", url: trend(2).url, trendId: trend(2).trendId }]); + assert.equal(first.enqueued?.jobId, "job-1"); + assert.equal(first.live, 3); + let w = (await readXTrendingWatches(root(paths))).saucers; + assert.deepEqual([w.lastTickAt, w.lastJobId, w.nextTickAt, w.ticks], ["2026-11-18T10:00:00.000Z", "job-1", "2026-11-18T10:30:00.000Z", 1]); + // A minute later: the next longest overdue, one again. + h.state.now = T0 + MIN; + await scanXTrendingWatches(h.deps); + h.state.now = T0 + 2 * MIN; + await scanXTrendingWatches(h.deps); + assert.deepEqual(h.ticks.map((t) => `${t.slug}/${t.topic}`), ["lib/saucers", "lib/kettles", "other/lids"]); + // Nothing is due until an interval has passed. + h.state.now = T0 + 29 * MIN; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); + h.state.now = T0 + 30 * MIN; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "saucers"); + // Hours missed (the editor was down): ONE catch-up tick, not several. + h.state.now = T0 + 6 * 60 * MIN; + const before = h.ticks.length; + await scanXTrendingWatches(h.deps); + assert.equal(h.ticks.length, before + 1); + // (Kettles was the longest overdue by then.) + assert.equal((await readXTrendingWatches(root(paths))).kettles.ticks, 2); + assert.equal((await readXTrendingWatches(root(paths))).saucers.ticks, 2); +}); + +test("no tick is started for a library while a read or capture of it waits its turn", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const h = harness(paths, ["lib"]); + h.state.busy.add("lib"); + assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); + assert.equal((await readXTrendingWatches(root(paths))).kettles.paused, undefined); + h.state.busy.clear(); + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); +}); + +test("a stale jar PAUSES the watches, raises X's jar-age alert and enqueues nothing; they resume at the first scan after a Refresh", async () => { + const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } }); + await on(paths, "Kettles"); + await on(paths, "Saucers"); + const h = harness(paths, ["lib"]); + h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 61 min ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again." }; + const scan = await scanXTrendingWatches(h.deps); + assert.deepEqual(h.ticks, []); + assert.deepEqual(scan.paused.map((p) => [p.topic, p.reason]).sort(), [["kettles", "jar"], ["saucers", "jar"]]); + assert.equal(h.state.jar.length, 1); + assert.match(h.state.jar[0], /2 watched topics of lib paused: X cookies were last refreshed 61 min ago.*A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on \/cookies\./); + let w = (await readXTrendingWatches(root(paths))).kettles; + assert.deepEqual(w.paused && [w.paused.reason, w.paused.since], ["jar", "2026-11-18T10:00:00.000Z"]); + assert.match(describeXTrendingWatch(w, T0), /PAUSED since 2026-11-18 10:00 UTC: X cookies were last refreshed 61 min ago/); + // /review's rows: the paused watches, by library and topic, each with its sentence. + assert.deepEqual( + (await pausedXTrendingWatches(paths)).map((r) => [r.slug, r.topic, r.title, r.reason, r.since, r.until]), + [ + ["lib", "kettles", "Kettles", "jar", "2026-11-18T10:00:00.000Z", "2026-11-20T10:00:00.000Z"], + ["lib", "saucers", "Saucers", "jar", "2026-11-18T10:00:00.000Z", "2026-11-20T10:00:00.000Z"], + ], + ); + // Still stale ten minutes later: paused since the same moment, said once more to the alert, nothing enqueued. + h.state.now = T0 + 10 * MIN; + const still = await scanXTrendingWatches(h.deps); + assert.deepEqual(still.paused, []); + assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.since, "2026-11-18T10:00:00.000Z"); + assert.deepEqual(h.ticks, []); + // Review 1 S4: the same reason with another age in its sentence changes + // nothing — watch.json is not rewritten, and the alert is not raised again + // (a banner the operator dismissed stays dismissed). + const before = readFileSync(xTrendingWatchPath(root(paths)), "utf8"); + h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 72 min ago (limit 60 min for a watch): press Refresh cookies." }; + h.state.now = T0 + 11 * MIN; + await scanXTrendingWatches(h.deps); + assert.equal(readFileSync(xTrendingWatchPath(root(paths)), "utf8"), before); + assert.equal(h.state.jar.length, 1); + // Refreshed: resumed at this scan, and the overdue tick is taken. + h.state.refusal = null; + h.state.now = T0 + 12 * MIN; + const resumed = await scanXTrendingWatches(h.deps); + assert.deepEqual(resumed.resumed.map((r) => r.topic).sort(), ["kettles", "saucers"]); + assert.equal(h.ticks.length, 1); + w = (await readXTrendingWatches(root(paths))).kettles; + assert.equal(w.paused, undefined); + assert.deepEqual(await pausedXTrendingWatches(paths), []); +}); + +test("the X alert, a cooldown and a missing profile pause too, each by its reason; only the jar raises the jar alert", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const h = harness(paths, ["lib"]); + for (const reason of ["alert", "cooldown", "no-profile"] as const) { + h.state.refusal = { reason, sentence: `why: ${reason}` }; + const scan = await scanXTrendingWatches(h.deps); + assert.deepEqual(scan.paused, [{ slug: "lib", topic: "kettles", reason }]); + assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.sentence, `why: ${reason}`); + } + assert.deepEqual(h.ticks, []); + assert.deepEqual(h.state.jar, []); +}); + +test("a read refused at its enqueue pauses that watch and is not asked again for an interval", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const h = harness(paths, ["lib"]); + h.state.refuse = "X's Refresh is running and holds the connected profile."; + const scan = await scanXTrendingWatches(h.deps); + assert.equal(scan.refused?.error, "X's Refresh is running and holds the connected profile."); + let w = (await readXTrendingWatches(root(paths))).kettles; + assert.equal(w.paused?.reason, "refused"); + assert.equal(w.nextTickAt, "2026-11-18T10:30:00.000Z"); + assert.equal(w.ticks, 0); + // A minute later nothing is asked; the pause stands. + h.state.refuse = null; + h.state.now = T0 + MIN; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); + assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.reason, "refused"); + // An interval later it is taken, and the pause is over. + h.state.now = T0 + 30 * MIN; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); + w = (await readXTrendingWatches(root(paths))).kettles; + assert.equal(w.paused, undefined); +}); + +test("a watch ends at its end time, with a sentence, and is not ticked again", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles", { hours: 1 }); + const h = harness(paths, ["lib"]); + await scanXTrendingWatches(h.deps); + h.state.now = T0 + 60 * MIN; + const scan = await scanXTrendingWatches(h.deps); + assert.deepEqual(scan.ended, [{ slug: "lib", topic: "kettles", sentence: 'The watch of "Kettles" ended at its end time (2026-11-18 11:00 UTC), after 1 tick.' }]); + assert.equal(scan.live, 0); + assert.equal(h.ticks.length, 1); + h.state.now = T0 + 120 * MIN; + await scanXTrendingWatches(h.deps); + assert.equal(h.ticks.length, 1); +}); + +test("a topic of several pages reads one page per tick, in turn; a page X retired is skipped, and the last one gone ends the watch", async () => { + const paths = await corpus({ lib: { Kettles: [1, 2] } }); + await on(paths, "Kettles"); + const h = harness(paths, ["lib"]); + for (let i = 0; i < 3; i++) { + h.state.now = T0 + i * 30 * MIN; + await scanXTrendingWatches(h.deps); + } + assert.deepEqual(h.ticks.map((t) => t.trendId), [trend(1).trendId, trend(2).trendId, trend(1).trendId]); + // Page 1 is gone: the watch goes on with page 2 alone. + assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(1).trendId, outcome: "gone", now: h.state.now }), null); + assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "read" }), null); + h.state.now = T0 + 90 * MIN; + await scanXTrendingWatches(h.deps); + h.state.now = T0 + 120 * MIN; + await scanXTrendingWatches(h.deps); + assert.deepEqual(h.ticks.slice(3).map((t) => t.trendId), [trend(2).trendId, trend(2).trendId]); + // Page 2 gone as well: the watch ends, saying so. + const sentence = await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "gone", now: h.state.now }); + assert.equal(sentence, 'X no longer has the trending page of "Kettles" (trending pages expire): the watch ended.'); + const w = (await readXTrendingWatches(root(paths))).kettles; + assert.deepEqual([w.on, w.ended?.reason], [false, "gone"]); + h.state.now = T0 + 150 * MIN; + await scanXTrendingWatches(h.deps); + assert.equal(h.ticks.length, 5); +}); + +test("after a read into a watched topic one capture takes its new posts with media, then what a capture left owed to a later one", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + const dir = root(paths); + const ids = ["7001", "7002", "7003", "7004", "7005"]; + await writeXTrendingPosts(dir, ids.map(post)); + await recordXTrendingRead(dir, { + readId: readId(20), + at: new Date(T0).toISOString(), + ref: trend(1), + topic: "Kettles", + postIds: ids, + added: 5, + media: { "7001": { count: 1, kinds: ["image"] }, "7003": { count: 1, kinds: ["video"] }, "7004": { count: 2, kinds: ["image"] }, "7005": { count: 1, kinds: ["image"] } }, + }); + // Not watched: nothing follows a read. + assert.equal(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), null); + await on(paths, "Kettles"); + const capture = (id: string, rec: Record<string, unknown>) => { + mkdirSync(path.join(dir, "trending", "posts-media", id), { recursive: true }); + writeFileSync(path.join(dir, "trending", "posts-media", id, "capture.json"), JSON.stringify({ version: 1, id, capturedAt: "2026-11-18T09:00:00.000Z", state: "captured", media: [], ...rec })); + }; + capture("7003", { mediaState: "error", mediaOwed: "next" }); + capture("7004", { mediaState: "error", mediaOwed: "kept" }); + capture("7005", { mediaState: "error", error: "7005_1.jpg: the CDN answered 404" }); + // 7002 has no media: not captured by a media-only watch. 7003 is owed to a + // later capture: taken. 7004 (owed until kept) and 7005 (failed) are not. + // (The topic's first post, read before the watch and never captured, carries no media: not taken.) + assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7003"], shots: false, fresh: 1, owed: 1, uncaptured: 0 }); + // "Screenshot everything new": the post without media is taken too. + await on(paths, "Kettles", { shots: true }); + assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7002", "7003"], shots: true, fresh: 2, owed: 1, uncaptured: 0 }); + // A read into another topic's posts takes nothing of this one's new ids. + // ...but (review 1 S7) 7001, which has media and was never captured — the + // new post of an earlier tick whose capture was refused — is asked for again. + assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["424242"] }), { ids: ["7003", "7001"], shots: true, fresh: 0, owed: 1, uncaptured: 1 }); + // Once it has a record, whatever the record says, it is not "never captured". + capture("7001", { mediaState: "none" }); + assert.deepEqual((await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: [] }))?.ids, ["7003"]); +}); + +test("the scan is not armed on an idle boot; armed, it is one timer, and disarms", () => { + const deps = { paths: {} as Paths, busy: () => false, enqueue: async () => ({ ok: false as const, error: "never" }) }; + disarmXTrendingWatch(); + assert.equal(armXTrendingWatch(deps, { env: { ARCHILYZER_IDLE_BOOT: "1" }, everyMs: 0 }), false); + assert.equal(isXTrendingWatchArmed(), false); + assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true); + assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true); + assert.equal(isXTrendingWatchArmed(), true); + disarmXTrendingWatch(); + assert.equal(isXTrendingWatchArmed(), false); +}); + +// Review 1 M1: the watch's own jar rule, whatever the guard would let a person's job do. +test("M1: the watch asks a jar under its limit whatever the source, the setting or the settings file say", async () => { + const now = T0; + type Report = Awaited<ReturnType<typeof import("../jobs/networkGuard").xSessionReport>>; + const report = (over: Partial<Report>): (() => Promise<Report>) => async () => + ({ + source: "profile", + sourceChosen: true, + profileDir: "p", + cookieFile: "c", + hasProfile: true, + hasCookies: true, + looksAuthenticated: true, + cookiesUpdatedAt: new Date(now - 10 * MIN).toISOString(), + ageMinutes: 10, + maxAgeMinutes: 60, + ageChecked: true, + alert: null, + // What the guard says of a person's job: allowed, in every case below. + allowed: true, + reason: null, + ...over, + }) as Report; + const ask = (over: Partial<Report>, settingsReadable = true) => + watchRefusal({} as Paths, "lib", now, { report: report(over) as never, settingsReadable: () => settingsReadable, held: async () => null }); + const old = new Date(now - 3 * 60 * MIN).toISOString(); + // The control: a fresh jar ticks. + assert.equal(await ask({}), null); + // Exemption 1: the login comes from the browser — the guard cannot read its age and lets a job through. + const browser = await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 }); + assert.equal(browser?.reason, "jar"); + assert.match(browser?.sentence ?? "", /last refreshed 3 h ago \(limit 60 min for a watch\)/); + // ...and with no exported jar at all. + assert.equal((await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: null, ageMinutes: null, hasCookies: false }))?.reason, "jar"); + // Exemption 2: the setting is 0 (the rule off for a person's jobs): a watch still asks 60 minutes. + const off = await ask({ maxAgeMinutes: 0, ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 }); + assert.match(off?.sentence ?? "", /limit 60 min for a watch/); + assert.equal(await ask({ maxAgeMinutes: 0, ageChecked: false }), null); + // A stricter setting is kept. + assert.match((await ask({ maxAgeMinutes: 5 }))?.sentence ?? "", /10 min ago \(limit 5 min for a watch\)/); + // Exemption 3: settings cannot be read. + const unreadable = await ask({}, false); + assert.equal(unreadable?.reason, "jar"); + assert.match(unreadable?.sentence ?? "", /settings\.json cannot be read/); + // A clock set back: the jar is dated after now. + const future = await ask({ cookiesUpdatedAt: new Date(now + 5 * MIN).toISOString(), ageMinutes: 0 }); + assert.match(future?.sentence ?? "", /dated in the future/); + // A jar with no login. + assert.equal((await ask({ looksAuthenticated: false }))?.reason, "jar"); + // The alert and the profile, as before. + assert.equal((await ask({ alert: { raisedAt: "x", line: "l" }, allowed: false, reason: "alert up" }))?.reason, "alert"); + assert.equal((await ask({ hasProfile: false }))?.reason, "no-profile"); +}); + +test("the watch's file sits where the library's other files do", () => { + assert.equal(xTrendingWatchPath("/x"), path.join("/x", TRENDING_DIRNAME, "watch.json")); +}); + +// Review 1 M3: the libraries share ONE stream of ticks. +test("M3: a trending job of any library waiting its turn stops every library's tick; two libraries never stack two reads", async () => { + const paths = await corpus({ lib: { Kettles: [1] }, other: { Lids: [3] } }); + await on(paths, "Kettles"); + await on(paths, "Lids", {}, "other"); + const h = harness(paths, ["lib", "other"]); + // As the editor's registry answers: busy once a read has been enqueued. + h.deps.busy = () => h.ticks.length > 0 || h.state.busy.size > 0; + await scanXTrendingWatches(h.deps); + assert.deepEqual(h.ticks.map((t) => t.slug), ["lib"]); + // The other library is due, and its tick waits: the first read is still queued. + h.state.now = T0 + MIN; + const second = await scanXTrendingWatches(h.deps); + assert.equal(second.enqueued, undefined); + assert.equal(h.ticks.length, 1); + assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.ticks, 0); + // Not a pause: nothing is wrong, it is only not its turn. + assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.paused, undefined); + // The first read (and its capture) done: now the other library's turn. + h.deps.busy = () => false; + h.state.now = T0 + 2 * MIN; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.slug, "other"); +}); + +// Review 1 S1. +test("S1: three reads in a row that do not end \"read\" pause the watch until a person switches it on again", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const h = harness(paths, ["lib"]); + const dir = root(paths); + const fail = (outcome: string) => noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome, now: h.state.now, sentence: "X answered 429 (rate limit)." }); + assert.equal(await fail("rate-limit"), null); + assert.equal(await fail("error"), null); + // A clean read between failures starts the count again. + assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "read" }), null); + assert.equal((await readXTrendingWatches(dir)).kettles.failures, 0); + assert.equal(await fail("forbidden"), null); + assert.equal(await fail("rate-limit"), null); + // A probe is nobody's failure. + assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "probe" }), null); + const third = await fail("rate-limit"); + assert.match(third ?? "", /^The last 3 reads of "Kettles" failed \(the last: rate-limit — X answered 429 \(rate limit\)\.\): its watch is paused until someone switches it on again/); + let w = (await readXTrendingWatches(dir)).kettles; + assert.deepEqual([w.on, w.paused?.reason, w.failures], [true, "failing", 3]); + assert.match(describeXTrendingWatch(w, T0), /PAUSED since .* UTC, until someone switches it on again: The last 3 reads/); + // No scan resumes it — not with X fine, not an interval later — and none ticks it. + for (const at of [T0 + MIN, T0 + 31 * MIN, T0 + 5 * 60 * MIN]) { + h.state.now = at; + const scan = await scanXTrendingWatches(h.deps); + assert.deepEqual([scan.enqueued, scan.resumed], [undefined, []]); + } + // Nor does a refusal overwrite the reason. + h.state.refusal = { reason: "jar", sentence: "stale" }; + await scanXTrendingWatches(h.deps); + assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); + h.state.refusal = null; + assert.deepEqual(h.ticks, []); + // /review lists it. + assert.deepEqual((await pausedXTrendingWatches(paths)).map((r) => [r.topic, r.reason]), [["kettles", "failing"]]); + // A person switches it on again: the count starts over and it ticks. + await on(paths, "Kettles", { now: h.state.now, by: "operator" }); + w = (await readXTrendingWatches(dir)).kettles; + assert.deepEqual([w.paused, w.failures], [undefined, 0]); + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); +}); + +// Review 1 S6. +test("S6: two asks for a scan at once are one scan and one read", async () => { + const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } }); + await on(paths, "Kettles"); + await on(paths, "Saucers"); + const h = harness(paths, ["lib"]); + let built = 0; + const deps = () => (built++, h.deps); + const [a, b] = await Promise.all([runXTrendingWatchScan(deps), runXTrendingWatchScan(deps)]); + assert.equal(a, b); + assert.equal(built, 1); + assert.equal(h.ticks.length, 1); + // A later ask is a scan of its own. + h.state.now = T0 + MIN; + await runXTrendingWatchScan(deps); + assert.equal(h.ticks.length, 2); +}); + +// Review 2 N5. +test("N5: only the operator starts a failing watch again; an enqueue does not erase a failing pause set meanwhile", async () => { + const paths = await corpus({ lib: { Kettles: [1] } }); + await on(paths, "Kettles"); + const dir = root(paths); + const h = harness(paths, ["lib"]); + // While the tick is being enqueued, three reads end badly: the watch is failing. + const enqueue = h.deps.enqueue; + h.deps.enqueue = async (tick) => { + for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); + return enqueue(tick); + }; + assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); + let w = (await readXTrendingWatches(dir)).kettles; + assert.equal(w.paused?.reason, "failing"); + assert.equal(w.ticks, 1); + // The same when the enqueue is refused: the failing pause is not overwritten. + h.deps.enqueue = async () => ({ ok: false, error: "refused for another reason" }); + await on(paths, "Kettles", { by: "operator", now: h.state.now }); + h.deps.enqueue = async () => { + for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); + return { ok: false, error: "refused for another reason" }; + }; + h.state.now = T0 + 31 * MIN; + await scanXTrendingWatches(h.deps); + assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); + // An agent cannot switch it on again... + const agent = await on(paths, "Kettles", { by: "agent", now: h.state.now }); + assert.equal(agent.ok, false); + assert.match(agent.ok ? "" : agent.error, /is paused because its reads kept failing .* Only the operator starts it again/); + assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); + // ...the operator can. + const op = await on(paths, "Kettles", { by: "operator", now: h.state.now }); + assert.equal(op.ok, true); + w = (await readXTrendingWatches(dir)).kettles; + assert.deepEqual([w.paused, w.failures], [undefined, 0]); +}); diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -0,0 +1,553 @@ +// THE WATCH OF A LIBRARY'S TOPICS (lane x-trending-2): the scan that turns a +// watched topic (lib/xTrending/watch.ts) into reads. +// +// Armed by the editor's instrumentation BELOW the idle gate +// (ARCHILYZER_IDLE_BOOT arms nothing, and armXTrendingWatch refuses an idle +// boot itself), not on the e2e test server — a tick is a request to X. Once +// armed, a scan runs every CHECK_MS on an unref'd timer of its own (NOT the +// sync heartbeat, which can be switched off), and: +// +// - a watch past its end time ENDS, with a sentence; +// - ONE SCAN STARTS AT MOST ONE READ, across every library: the watch +// longest overdue. A tick is the same single `read-x-trending` job a +// person starts, on X's queue (one job at a time, X's gap between jobs); +// a missed window is one catch-up tick, never several; +// - no tick is started while a trending read, a reparse or a capture of +// ANY library is queued or running: the libraries share one stream of +// ticks (the cap on watched topics is per library); +// - three reads of a watched topic in a row that did not end "read" PAUSE +// its watch ("failing") until a person switches it on again; +// - WHEN X WOULD REFUSE THE READ the watches PAUSE instead of queueing jobs +// to be refused: X's cookie jar is past its limit ("jar": X's jar-age +// alert goes up, on the dashboard and /cookies, and /review lists the +// paused watches), the X alert is up, X is cooling down after a rate +// limit, or there is no connected profile. The pause ends at the first +// scan that finds the reason gone; +// - a topic with several trending pages reads ONE page per tick, in turn; +// - a page X no longer has is not read again, and a topic with no page +// left ENDS its watch with a sentence (noteXTrendingWatchRead, called at +// the end of every read of a library). +// +// THE JAR IS NEVER REFRESHED HERE. A refresh is a person's press on /cookies +// (jobs/networkGuard.ts): a watch runs only while the jar is fresh, so it +// does not cover a night nobody presses Refresh in. +// +// After a read into a watched topic, its NEW posts get their media at once +// (xTrendingWatchFollowUp says which posts one capture job takes). + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { isIdleBoot } from "../lib/idleBoot"; +import { jitterMs } from "../lib/jitter"; +import { noteXJarStale } from "../lib/serviceCookies-server"; +import { ageText, xSessionReport } from "../jobs/networkGuard"; +import { getSettings } from "../lib/settings"; +import { isXTrendingChannel } from "../lib/xTrending/config"; +import { + readXTrendingMembership, + readXTrendingTopics, + xTrendingCaptureSummary, + type XTrendingTopic, +} from "../lib/xTrending/store"; +import { + mutateXTrendingWatches, + X_TRENDING_WATCH_MAX_FAILURES, + pausedWatchRows, + readXTrendingWatches, + watchIsLive, + type PausedWatchRow, + type XTrendingWatch, + type XTrendingWatchPauseReason, +} from "../lib/xTrending/watch"; +import { listChannelConfigs } from "./channels"; +import { xTrendingHeld } from "./readXTrending"; + +export const X_TRENDING_WATCH_CHECK_MS = 60_000; +// One capture after a tick takes at most this many posts. +export const X_TRENDING_WATCH_CAPTURE_MAX = 80; + +export type WatchRefusal = { reason: XTrendingWatchPauseReason; sentence: string }; + +export type WatchTick = { slug: string; topic: string; url: string; trendId: string }; + +export type WatchScanDeps = { + paths: Paths; + now?: () => number; + log?: (line: string) => void; + // The libraries (default: every channel carrying the marker). + libraries?: () => Promise<string[]>; + // A trending read, a reparse or a capture of ANY library is queued or + // running (review 1 M3): the libraries share one stream of ticks, so two + // libraries never have two reads waiting on X's queue behind each other. + busy: () => boolean; + // Why X would refuse a read now, or null (default: watchRefusal below). + refusal?: (slug: string) => Promise<WatchRefusal | null>; + // One read, enqueued (the editor's readXTrendingAction). + enqueue: (tick: WatchTick) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; + noteJarStale?: (line: string, slug: string) => Promise<unknown>; + // The stretch added to an interval (never a shortening). + jitter?: (ms: number) => number; +}; + +export type WatchScanResult = { + libraries: number; + // Watches switched on and not ended, after this scan. + live: number; + enqueued?: WatchTick & { jobId: string }; + refused?: WatchTick & { error: string }; + paused: Array<{ slug: string; topic: string; reason: XTrendingWatchPauseReason }>; + resumed: Array<{ slug: string; topic: string }>; + ended: Array<{ slug: string; topic: string; sentence: string }>; +}; + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " "); + +// The age a watch asks of X's exported jar when the setting says nothing +// usable (0 turns the fresh-jar rule off for a person's jobs — never for a +// watch). +export const WATCH_MAX_JAR_AGE_MINUTES = 60; + +export type WatchRefusalDeps = { + report?: typeof xSessionReport; + // Whether settings.json can be read at all. + settingsReadable?: () => boolean; + held?: (paths: Paths, now: number) => Promise<string | null>; +}; + +function settingsCanBeRead(): boolean { + try { + getSettings(); + return true; + } catch { + return false; + } +} + +// WHY X WOULD REFUSE A READ NOW — read from disk, never from X: the X alert, +// the connected profile, the jar's age, X's cooldown or hold. +// +// THE WATCH HAS ITS OWN JAR RULE, STRICTER THAN THE GUARD'S (review 1 M1). The +// fresh-jar rule a person's job meets (jobs/networkGuard.ts) lets a job +// through when the login comes from the browser (its age cannot be read), +// when `social.x.maxCookieAgeMinutes` is 0, and when settings cannot be read. +// Those are a person's choices about a job a person started. A watch starts +// jobs with nobody there, so none of them applies to it: WHATEVER THE SOURCE +// AND THE SETTING, a watch ticks only when the profile's exported jar was +// written between 0 and the limit ago (the setting when it is above 0, else +// 60 minutes) — an age that cannot be read, or is negative (a clock set +// back), refuses — and never when settings cannot be read. +export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { + const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now }); + if (!report.hasProfile) { + return { + reason: "no-profile", + sentence: "There is no connected X profile to read a trending page with: connect an X account on /cookies.", + }; + } + if (report.alert) { + return { reason: "alert", sentence: report.reason ?? "X's cookie alert is up." }; + } + if (!(deps.settingsReadable ?? settingsCanBeRead)()) { + return { reason: "jar", sentence: "settings.json cannot be read, so the limit on X's cookie age is not known: a watch does not tick without it." }; + } + const limit = report.maxAgeMinutes > 0 ? report.maxAgeMinutes : WATCH_MAX_JAR_AGE_MINUTES; + const written = report.cookiesUpdatedAt ? Date.parse(report.cookiesUpdatedAt) : NaN; + // Not the report's `ageMinutes`: that one never goes below zero. + const ageMinutes = Number.isFinite(written) ? (now - written) / 60_000 : null; + if (ageMinutes === null || !report.hasCookies) { + return { reason: "jar", sentence: "No X cookie jar has been exported from the connected profile: press Refresh cookies (or Connect X account) on /cookies." }; + } + if (!report.looksAuthenticated) { + return { reason: "jar", sentence: "The X cookie jar holds no login (no auth_token): press Connect X account on /cookies." }; + } + if (ageMinutes < 0) { + return { reason: "jar", sentence: "X's cookie jar is dated in the future (the clock was set back?): press Refresh cookies on /cookies." }; + } + if (ageMinutes > limit) { + return { + reason: "jar", + sentence: `X cookies were last refreshed ${ageText(now - written)} ago (limit ${limit} min for a watch): press Refresh cookies (or Connect X account) on /cookies.`, + }; + } + // Whatever else the guard would refuse a person's job for. + if (!report.allowed) return { reason: "jar", sentence: report.reason ?? "X's cookie jar is past its limit." }; + const held = await (deps.held ?? xTrendingHeld)(paths, now); + return held ? { reason: "cooldown", sentence: held } : null; +} + +// THE LIVE WATCHES OF A LIBRARY, PAUSED for a refusal met outside the scan (a +// watch's job at its start). A watch paused for failing keeps that pause. +// Answers how many it paused. +export async function pauseXTrendingWatches(channelRoot: string, refusal: WatchRefusal, now: number): Promise<number> { + const at = new Date(now).toISOString(); + return mutateXTrendingWatches(channelRoot, (watches) => { + let n = 0; + for (const w of Object.values(watches)) { + if (!watchIsLive(w) || w.paused?.reason === "failing" || w.paused?.reason === refusal.reason) continue; + w.paused = { reason: refusal.reason, since: at, sentence: refusal.sentence }; + n++; + } + return { write: n > 0, result: n }; + }); +} + +// A WATCH'S JOB, AT ITS START (review 2 N1) — its tick's read, and the capture +// that follows a read into a watched topic. The scan asks the watch's jar rule +// when it queues a tick, but a job starts when its turn on X's queue comes: a +// tick queued on a 58-minute jar behind another X job starts on a 78-minute +// one, and the guard every X job meets at its start lets that through when +// the cookie-age setting is 0 or the login comes from the browser. So the +// watch's own rule is asked AGAIN here, at the moment the job would touch X. +// A refusal pauses the library's watches (as the scan would have) and is +// answered; the caller then starts nothing. +export async function refuseWatchJob(paths: Paths, slug: string, now: number = Date.now(), deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { + const refusal = await watchRefusal(paths, slug, now, deps); + if (refusal) await pauseXTrendingWatches(path.join(paths.channelsDir, slug), refusal, now).catch(() => 0); + return refusal; +} + +export const WATCH_JAR_NOTE = + "A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on /cookies."; + +async function defaultLibraries(paths: Paths): Promise<string[]> { + return (await listChannelConfigs(paths)).filter((c) => isXTrendingChannel(c.config)).map((c) => c.slug); +} + +type Due = { slug: string; root: string; topic: XTrendingTopic; watch: XTrendingWatch; dueAt: number }; + +// ONE SCAN. Never throws for one library's sake: a library whose files +// cannot be read is skipped and said. +export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchScanResult> { + const now = (deps.now ?? Date.now)(); + const at = new Date(now).toISOString(); + const log = deps.log ?? (() => {}); + const out: WatchScanResult = { libraries: 0, live: 0, paused: [], resumed: [], ended: [] }; + const slugs = await (deps.libraries ?? (() => defaultLibraries(deps.paths)))(); + out.libraries = slugs.length; + const due: Due[] = []; + for (const slug of slugs) { + const root = path.join(deps.paths.channelsDir, slug); + try { + if (!Object.values(await readXTrendingWatches(root)).some(watchIsLive)) continue; + const topics = new Map((await readXTrendingTopics(root)).map((t) => [t.id, t])); + // 1. End what is past its end time (or whose topic is no more). + await mutateXTrendingWatches(root, (watches) => { + let write = false; + for (const [id, w] of Object.entries(watches)) { + if (!watchIsLive(w)) continue; + const title = topics.get(id)?.title; + const sentence = !title + ? `The watch ended: this library no longer has the topic "${id}".` + : now >= Date.parse(w.until) + ? `The watch of "${title}" ended at its end time (${hhmm(Date.parse(w.until))} UTC), after ${w.ticks} tick${w.ticks === 1 ? "" : "s"}.` + : null; + if (!sentence) continue; + w.on = false; + delete w.paused; + w.ended = { at, reason: title ? "until" : "off", sentence }; + out.ended.push({ slug, topic: id, sentence }); + write = true; + } + return { write, result: null }; + }); + // 2. Would X refuse a read? Then the live watches pause; else they resume. + const refusal = await (deps.refusal ?? ((s) => watchRefusal(deps.paths, s, now)))(slug); + const watches = await mutateXTrendingWatches(root, (all) => { + let write = false; + for (const [id, w] of Object.entries(all)) { + if (!watchIsLive(w)) continue; + // Paused for failing: only a person ends that (review 1 S1). + if (w.paused?.reason === "failing") continue; + if (refusal) { + // BY THE REASON ONLY (review 1 S4): the sentence carries the + // jar's age in minutes, and a watch.json rewritten every scan for + // it is churn. The sentence is the one the pause began with. + if (w.paused?.reason !== refusal.reason) { + out.paused.push({ slug, topic: id, reason: refusal.reason }); + w.paused = { reason: refusal.reason, since: at, sentence: refusal.sentence }; + write = true; + } + } else if (w.paused && w.paused.reason !== "refused") { + // A read that was refused at its enqueue stays paused until one is taken. + delete w.paused; + out.resumed.push({ slug, topic: id }); + write = true; + } + } + return { write, result: all }; + }); + for (const p of out.paused.filter((p) => p.slug === slug)) { + log(`x-trending watch: ${slug}/${p.topic}: paused (${p.reason}): ${refusal?.sentence ?? ""}`); + } + for (const r of out.resumed.filter((r) => r.slug === slug)) log(`x-trending watch: ${slug}/${r.topic}: resumed`); + const live = Object.entries(watches).filter(([, w]) => watchIsLive(w)); + out.live += live.length; + if (refusal) { + // The alert is raised when the watches GO stale, not at every scan + // after (review 1 S4): a banner the operator dismissed stays dismissed. + const went = out.paused.filter((p) => p.slug === slug && p.reason === "jar").length; + if (refusal.reason === "jar" && went > 0) { + const line = `${live.length} watched topic${live.length === 1 ? "" : "s"} of ${slug} paused: ${refusal.sentence} ${WATCH_JAR_NOTE}`; + await (deps.noteJarStale ?? ((l, s) => noteXJarStale(deps.paths, { line: l, channel: s }, now)))(line, slug).catch(() => {}); + } + continue; + } + // 3. What is due. + for (const [id, w] of live) { + const topic = topics.get(id); + if (!topic || w.paused?.reason === "failing") continue; + const dueAt = w.nextTickAt ? Date.parse(w.nextTickAt) : Date.parse(w.startedAt); + if (dueAt <= now) due.push({ slug, root, topic, watch: w, dueAt }); + } + } catch (err) { + log(`x-trending watch: ${slug}: the scan could not read this library: ${(err as Error).message}`); + } + } + // Nothing is started while a trending job of any library waits its turn. + if (due.length === 0 || deps.busy()) return out; + // The longest overdue, and only it. + due.sort((a, b) => a.dueAt - b.dueAt || a.slug.localeCompare(b.slug) || a.topic.id.localeCompare(b.topic.id)); + const pick = due[0]; + const pages = pick.topic.sources.filter((s) => !pick.watch.goneSources.includes(s.trendId)); + if (pages.length === 0) { + const sentence = goneSentence(pick.topic.title); + await mutateXTrendingWatches(pick.root, (watches) => { + const w = watches[pick.topic.id]; + if (!watchIsLive(w)) return { write: false, result: null }; + w.on = false; + delete w.paused; + w.ended = { at, reason: "gone", sentence }; + return { write: true, result: null }; + }); + out.ended.push({ slug: pick.slug, topic: pick.topic.id, sentence }); + out.live--; + return out; + } + const page = pages[pick.watch.nextSource % pages.length]; + const tick: WatchTick = { slug: pick.slug, topic: pick.topic.id, url: page.url, trendId: page.trendId }; + const interval = pick.watch.intervalMinutes * 60_000; + const started = await deps.enqueue(tick).catch((err) => ({ ok: false as const, error: (err as Error).message })); + await mutateXTrendingWatches(pick.root, (watches) => { + const w = watches[pick.topic.id]; + if (!watchIsLive(w)) return { write: false, result: null }; + if (started.ok) { + w.lastTickAt = at; + w.lastJobId = started.jobId; + // Stretched, never shortened. + w.nextTickAt = new Date(now + interval + Math.max(0, (deps.jitter ?? ((ms) => jitterMs(ms) - ms))(interval))).toISOString(); + w.ticks++; + w.nextSource = (w.nextSource + 1) % 1_000_000; + // ONLY THE PAUSE THIS ENQUEUE RESOLVES (review 2 N5): a read that was + // refused before is taken now. The file is read again under the lock + // here, and a pause set meanwhile for another reason — "failing", by a + // read that ended while this one was being queued — is not this scan's + // to erase. + if (w.paused?.reason === "refused") delete w.paused; + } else { + // Not asked again every minute: the next try is an interval away. + w.nextTickAt = new Date(now + interval).toISOString(); + if (w.paused?.reason !== "failing") { + w.paused = { reason: "refused", since: w.paused?.reason === "refused" ? w.paused.since : at, sentence: started.error }; + } + } + return { write: true, result: null }; + }); + if (started.ok) { + out.enqueued = { ...tick, jobId: started.jobId }; + log(`x-trending watch: ${tick.slug}/${tick.topic}: tick → job ${started.jobId} (${tick.url})`); + } else { + out.refused = { ...tick, error: started.error }; + out.paused.push({ slug: tick.slug, topic: tick.topic, reason: "refused" }); + log(`x-trending watch: ${tick.slug}/${tick.topic}: not ticked: ${started.error}`); + } + return out; +} + +const goneSentence = (title: string) => + `X no longer has the trending page of "${title}" (trending pages expire): the watch ended.`; + +// THE END OF A READ, told to the watch (every read of a library, a person's +// too): +// - a page X answered "gone" for is not read again; when the topic has no +// page left, its watch ends with a sentence; +// - a read that ended "read" clears the count of failures; +// - any other end (a rate limit, a 403, a login wall, a page that would not +// load, nothing recognised) is a failure, and the third in a row PAUSES +// the watch, "failing", until a person switches it on again (review 1 +// S1). A 429's 15-minute cooldown is recorded by the read as before. +// Answers the sentence of what it did to a watch, or null. +export async function noteXTrendingWatchRead( + channelRoot: string, + read: { trendId: string; outcome: string; now?: number; sentence?: string }, +): Promise<string | null> { + if (read.outcome === "probe") return null; + const topics = await readXTrendingTopics(channelRoot); + const at = new Date(read.now ?? Date.now()).toISOString(); + return mutateXTrendingWatches(channelRoot, (watches) => { + let write = false; + let sentence: string | null = null; + for (const topic of topics) { + const w = watches[topic.id]; + if (!watchIsLive(w) || !topic.sources.some((s) => s.trendId === read.trendId)) continue; + if (read.outcome === "read") { + if (w.failures !== 0) { + w.failures = 0; + write = true; + } + continue; + } + if (read.outcome === "gone") { + if (!w.goneSources.includes(read.trendId)) w.goneSources.push(read.trendId); + write = true; + if (topic.sources.every((s) => w.goneSources.includes(s.trendId))) { + sentence = goneSentence(topic.title); + w.on = false; + delete w.paused; + w.ended = { at, reason: "gone", sentence }; + } + continue; + } + w.failures++; + write = true; + if (w.failures >= X_TRENDING_WATCH_MAX_FAILURES && w.paused?.reason !== "failing") { + sentence = + `The last ${w.failures} reads of "${topic.title}" failed (the last: ${read.outcome}` + + `${read.sentence ? ` — ${read.sentence}` : ""}): its watch is paused until someone switches it on again ` + + `(Watch on its page, or watch-trending {"topic": "${topic.id}", "on": true}).`; + w.paused = { reason: "failing", since: at, sentence }; + } + } + return { write, result: sentence }; + }); +} + +export type WatchFollowUp = { ids: string[]; shots: boolean; fresh: number; owed: number; uncaptured: number }; + +// WHAT ONE CAPTURE TAKES AFTER A READ INTO A WATCHED TOPIC: the read's new +// posts (their media at once; a screenshot too when the topic says so), then +// the topic's posts a capture left OWED to a later one (the job's budget, X's +// cooldown), then its posts with media that were never captured at all — +// never one whose capture failed, and never one owed until it is kept. +// Null when the topic is not watched or there is nothing to take. +export async function xTrendingWatchFollowUp( + channelRoot: string, + o: { topic: string; newIds: ReadonlyArray<string> }, +): Promise<WatchFollowUp | null> { + const watch = (await readXTrendingWatches(channelRoot))[o.topic]; + if (!watchIsLive(watch)) return null; + const membership = await readXTrendingMembership(channelRoot); + // Media only: a post with none is not captured (nothing to fetch, no page). + const fresh = o.newIds.filter((id) => membership[id]?.topic === o.topic && (watch.shots || (membership[id]?.media?.count ?? 0) > 0)); + const ids = fresh.slice(0, X_TRENDING_WATCH_CAPTURE_MAX); + let owed = 0; + const taken = new Set(ids); + // Then what is owed to a later capture; then (review 1 S7) the topic's + // posts with media that have NO capture record at all — the new posts of an + // earlier tick whose capture was refused before it was a job (a stale jar, + // the cooldown), which nothing would otherwise ask for again. + const never: string[] = []; + for (const [id, m] of Object.entries(membership)) { + if (m.topic !== o.topic || taken.has(id)) continue; + const capture = await xTrendingCaptureSummary(channelRoot, id); + if (capture?.mediaOwed === "next") { + if (ids.length < X_TRENDING_WATCH_CAPTURE_MAX) { + ids.push(id); + owed++; + } + } else if (!capture && (m.media?.count ?? 0) > 0) never.push(id); + } + let uncaptured = 0; + for (const id of never) { + if (ids.length >= X_TRENDING_WATCH_CAPTURE_MAX) break; + ids.push(id); + uncaptured++; + } + return ids.length > 0 ? { ids, shots: watch.shots, fresh: ids.length - owed - uncaptured, owed, uncaptured } : null; +} + +// The watches that are paused now, across every library — /review's section. +export async function pausedXTrendingWatches(paths: Paths): Promise<PausedWatchRow[]> { + const libraries = []; + for (const slug of await defaultLibraries(paths)) { + const root = path.join(paths.channelsDir, slug); + const watches = await readXTrendingWatches(root); + if (!Object.values(watches).some((w) => watchIsLive(w) && w.paused)) continue; + libraries.push({ slug, watches, topics: await readXTrendingTopics(root) }); + } + return pausedWatchRows(libraries); +} + +// ─── arming (the editor's instrumentation, below the idle gate) ─── + +type Armed = { deps: WatchScanDeps; timer: ReturnType<typeof setInterval> | null; scanning: Promise<WatchScanResult> | null }; + +declare global { + // eslint-disable-next-line no-var + var __yttXTrendingWatch__: Armed | undefined; +} + +// One scan at a time: a second caller shares the one going. Null when unarmed. +export function xTrendingWatchTick(): Promise<WatchScanResult> | null { + const a = globalThis.__yttXTrendingWatch__; + if (!a) return null; + if (!a.scanning) { + a.scanning = scanXTrendingWatches(a.deps).finally(() => { + a.scanning = null; + }); + } + return a.scanning; +} + +// ONE SCAN AT A TIME, ARMED OR NOT (review 1 S6): `watch-trending {"tick": +// true}` goes through the armed scan's own in-flight promise when the timer +// is armed, and through this one when it is not (the e2e test server) — two +// asks at once are one scan, never two reads. +declare global { + // eslint-disable-next-line no-var + var __yttXTrendingWatchScan__: Promise<WatchScanResult> | null | undefined; +} + +export function runXTrendingWatchScan(deps: () => WatchScanDeps): Promise<WatchScanResult> { + const armed = xTrendingWatchTick(); + if (armed) return armed; + if (!globalThis.__yttXTrendingWatchScan__) { + globalThis.__yttXTrendingWatchScan__ = scanXTrendingWatches(deps()).finally(() => { + globalThis.__yttXTrendingWatchScan__ = null; + }); + } + return globalThis.__yttXTrendingWatchScan__; +} + +// Arm the scan: every `everyMs` (default CHECK_MS). Refused (false) on an idle +// boot. Idempotent: a second call only replaces the deps. +export function armXTrendingWatch( + deps: WatchScanDeps, + opts: { env?: Record<string, string | undefined>; everyMs?: number } = {}, +): boolean { + if (isIdleBoot(opts.env ?? process.env)) return false; + const armed = globalThis.__yttXTrendingWatch__; + if (armed) { + armed.deps = deps; + return true; + } + const state: Armed = { deps, timer: null, scanning: null }; + globalThis.__yttXTrendingWatch__ = state; + const every = opts.everyMs ?? X_TRENDING_WATCH_CHECK_MS; + if (every > 0) { + state.timer = setInterval(() => { + void xTrendingWatchTick()?.catch((e) => state.deps.log?.(`x-trending watch: the scan failed: ${(e as Error).message}`)); + }, every); + state.timer.unref?.(); + } + return true; +} + +export function disarmXTrendingWatch(): void { + const a = globalThis.__yttXTrendingWatch__; + if (a?.timer) clearInterval(a.timer); + globalThis.__yttXTrendingWatch__ = undefined; +} + +export function isXTrendingWatchArmed(): boolean { + return globalThis.__yttXTrendingWatch__ !== undefined; +} diff --git a/common/controller/xTrendingWatchJob.test.ts b/common/controller/xTrendingWatchJob.test.ts @@ -0,0 +1,165 @@ +// Review 2 N1: a watch's job asks the watch's own jar rule AT ITS START, over a +// real settings file and a real (made-up) exported jar — the two cases the +// guard every X job meets lets through: a cookie-age setting of 0, and the +// browser as the login source. No browser opens and nothing is asked of X. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatchJob.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-watch-job-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { guardNetworkJob } = await import("../jobs/networkGuard"); +const { recordXTrendingRead, readXTrendingTopics, writeXTrendingPosts } = await import("../lib/xTrending/store"); +const { readXTrendingWatches, setXTrendingWatch } = await import("../lib/xTrending/watch"); +const { refuseWatchJob, noteXTrendingWatchRead } = await import("./xTrendingWatch"); +const { planReadXTrending, runXTrendingRead } = await import("./readXTrending"); +const { FIXTURE_TREND_ID, FIXTURE_TREND_URL } = await import("../social/__fixtures__/xTrendingCapture"); + +const paths = getPaths(); +const SLUG = "trending"; +const root = path.join(paths.channelsDir, SLUG); +const jar = path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); +const MIN = 60_000; + +mkdirSync(root, { recursive: true }); +writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: "Trending", xTrending: {} })); +mkdirSync(path.join(paths.transcriptsDir, ".x-session", "profile"), { recursive: true }); +writeFileSync(jar, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfixture-not-a-real-token\n"); +await writeXTrendingPosts(root, [ + { id: "9001", slug: `${SLUG}/9001`, channelSlug: SLUG, author: "a", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "t", url: "https://x.com/a/status/9001", platform: "twitter", isReply: false, isRepost: false, links: [] }, +]); +await recordXTrendingRead(root, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL }, topic: "Kettles", postIds: ["9001"], added: 1 }); + +// The two settings under which the guard's own start check lets an old jar through. +const EXEMPT: Record<string, unknown> = { + "the cookie-age setting is 0": { social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 0 } } }, + "the login comes from the browser": { social: { x: { cookieSource: "browser", maxCookieAgeMinutes: 60 } }, cookiesFromBrowser: "firefox" }, +}; + +async function watchOn(): Promise<void> { + const set = await setXTrendingWatch(root, { topics: await readXTrendingTopics(root), topic: "kettles", on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.now() }); + assert.equal(set.ok, true); +} + +const jarAged = (minutes: number) => { + const at = new Date(Date.now() - minutes * MIN); + utimesSync(jar, at, at); +}; + +for (const [name, settings] of Object.entries(EXEMPT)) { + test(`N1: a watch tick whose turn comes on a 78-minute jar is not read, though the guard would start it — ${name}`, async () => { + writeFileSync(paths.settingsFile, JSON.stringify(settings)); + await watchOn(); + // Queued on a 58-minute jar: the watch's rule lets it be queued. + jarAged(58); + assert.equal(await refuseWatchJob(paths, SLUG), null); + const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); + assert.equal(planned.ok, true); + if (!planned.ok || planned.plan.mode !== "read") return; + assert.equal(planned.plan.watch, true); + // Twenty minutes behind another X job: 78 minutes. The guard an X job meets at its start still says yes... + jarAged(78); + const guard = await guardNetworkJob({ kind: "read-x-trending", queueKey: "platform:twitter", paths, channelSlug: SLUG, job: { id: "j1" } }); + assert.equal(guard.ok, true, "the control: the guard alone would start this job"); + // ...and the watch's own rule, asked at the job's start, says no: no browser opens. + let opened = 0; + const log: string[] = []; + const result = await runXTrendingRead({ + paths, + plan: planned.plan, + onLog: (l) => log.push(l), + deps: { + openPage: async () => { + opened++; + throw new Error("no browser may open"); + }, + held: async () => null, + watchRefusal: () => refuseWatchJob(paths, SLUG), + }, + }); + assert.equal(opened, 0); + assert.equal(result.ok, false); + assert.equal(result.watchRefused?.reason, "jar"); + assert.match(result.sentence, /^This watch tick was not read \(no browser was opened, X was asked nothing\): X cookies were last refreshed 78 min ago \(limit 60 min for a watch\)/); + // The watch is paused for the jar, and it is no strike against it. + const w = (await readXTrendingWatches(root)).kettles; + assert.deepEqual([w.paused?.reason, w.failures], ["jar", 0]); + + // THE FOLLOW-UP CAPTURE asks the same question before it is queued and when it starts. + await watchOn(); + assert.equal((await readXTrendingWatches(root)).kettles.paused?.reason, "jar"); + const followUp = await refuseWatchJob(paths, SLUG); + assert.equal(followUp?.reason, "jar"); + assert.match(followUp?.sentence ?? "", /78 min ago \(limit 60 min for a watch\)/); + // Refreshed: both go ahead. + jarAged(1); + assert.equal(await refuseWatchJob(paths, SLUG), null); + }); +} + +test("N1: a read marked as a watch's with no check at its start does not run; a person's read is not asked the watch's rule", async () => { + writeFileSync(paths.settingsFile, JSON.stringify(EXEMPT["the cookie-age setting is 0"])); + jarAged(78); + const plan = async (watch: boolean) => { + const p = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, ...(watch ? { watch: true } : {}) }, { hasProfile: async () => true, held: async () => null }); + assert.equal(p.ok, true); + return (p as { plan: Parameters<typeof runXTrendingRead>[0]["plan"] }).plan; + }; + let opened = 0; + const openPage = async () => { + opened++; + throw new Error("stop here"); + }; + const unchecked = await runXTrendingRead({ paths, plan: await plan(true), deps: { openPage, held: async () => null } }); + assert.equal(opened, 0); + assert.match(unchecked.sentence, /started with no check of X's cookie jar, so it is not run/); + // A person's read (no `watch`) goes on to open the page: the setting is the person's choice. + const person = await runXTrendingRead({ paths, plan: await plan(false), deps: { openPage, held: async () => null, noteOutcome: async () => null } }); + assert.equal(opened, 1); + assert.equal(person.watchRefused, undefined); + // (That failed read is told to the watch as any read is.) + await noteXTrendingWatchRead(root, { trendId: FIXTURE_TREND_ID, outcome: person.outcome }); +}); + +test("N1: a watch's tick on a fresh jar is read as any read, and its record and log say it was a watch's", async () => { + const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser"); + const { fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture"); + const { readXTrendingReadRecord } = await import("../lib/xTrending/store"); + writeFileSync(paths.settingsFile, JSON.stringify({ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } })); + jarAged(5); + const planned = await planReadXTrending(paths, { slug: SLUG, url: FIXTURE_TREND_URL, watch: true }, { hasProfile: async () => true, held: async () => null }); + assert.equal(planned.ok, true); + if (!planned.ok || planned.plan.mode !== "read") return; + const page = fakeTrendingPage(() => ({ trending: fixtureTrendingResponses() })); + const log: string[] = []; + let asked = 0; + const READ = "tr-01JW0000000000000000000000"; + const result = await runXTrendingRead({ + paths, + plan: planned.plan, + onLog: (l) => log.push(l), + deps: { + openPage: async () => ({ page, close: async () => {} }), + held: async () => null, + pauseMs: () => 0, + pause: async () => {}, + readId: READ, + noteOutcome: async () => null, + watchRefusal: async () => (asked++, refuseWatchJob(paths, SLUG)), + }, + }); + assert.equal(asked, 1); + assert.equal(result.outcome, "read"); + assert.equal(result.watchRefused, undefined); + assert.equal((await readXTrendingReadRecord(root, READ))?.watch, true); + assert.ok(log.some((l) => / A watch's tick\.$/.test(l)), log[0]); +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -689,8 +689,11 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // 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. + // repeats one unasked; started by a person (or an agent's ask), or by the + // watch's scan for a topic someone switched a watch on for + // (controller/xTrendingWatch.ts) — never by a boot: a tick left queued + // across a restart is cancelled, and the scan re-derives it, which it does + // only while X's cookie jar is fresh. "read-x-trending": { kind: "read-x-trending", label: "Read X trending page", diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -402,7 +402,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { 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.', + '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?, maxVideoMb?, watchIntervalMinutes?, watchHours?, watchMaxTopics?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); and the defaults of the watch: how often a watched topic is read (15–1440 minutes, default 30), for how long (1–168 hours, default 48) and how many topics may be watched at once (1–12, default 4) — `pnpm ops watch-trending` sets these three and `maxVideoMb`; `{}` 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.", }; diff --git a/common/lib/xTrending/__fixtures__/slice2Library.ts b/common/lib/xTrending/__fixtures__/slice2Library.ts @@ -0,0 +1,66 @@ +// WHAT LANE x-trending-2 ADDS TO A LIBRARY, PLANTED FOR THE PRIVACY PINS: a +// judgement with a note, a watch, a captured post (its record, a shot, a +// media file taken into the store with its address) and an availability +// sidecar — each carrying a marker the pin then looks for in everything a +// build, a report or a tool gives out. Written through the real writers, so +// the layout is the one the editor leaves. Invented words throughout. + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { writePostAvailability } from "../../posts-server"; +import { judgeXTrending } from "../judgements"; +import { adoptXTrendingMedia, ensureXTrendingMediaIgnore } from "../mediaStore"; +import { readXTrendingTopics, trendingDir, xTrendingPostsMediaDir } from "../store"; +import { setXTrendingWatch } from "../watch"; + +export const SLICE2_MARKS = { + note: "trendjudgenotemarkerh3v", + media: "trendmediabytesmarkerk8d", + address: "trendmediaaddressmarkerp5s", + context: "trendcapturecontextmarkern2c", + shot: "trendshotbytesmarkert6b", +} as const; + +export const SLICE2_MARK_LIST: readonly string[] = Object.values(SLICE2_MARKS); + +// The names a build or a report must never carry a file of. +// A library's captures directory (`trending/<this>/<id>/`), named here so the +// pins under publish/ and bin/ need not spell it (postCapture.test.ts holds +// every source there to naming it nowhere but the cited-capture copier). +export const SLICE2_CAPTURES_DIRNAME = path.basename(xTrendingPostsMediaDir(".")); + +export const SLICE2_FILE_NAMES: readonly string[] = [ + "judgements.json", + "media-index.json", + "watch.json", + "media-store", + "posts-availability.json", + SLICE2_CAPTURES_DIRNAME, +]; + +// `postId` must be a post of the library, in a topic `topicId` that holds a page. +export async function plantSlice2Library(libRoot: string, o: { postId: string; topicId: string }): Promise<void> { + await judgeXTrending(libRoot, { by: "operator", set: [{ id: o.postId, state: "keep", note: `kept ${SLICE2_MARKS.note}` }] }); + await setXTrendingWatch(libRoot, { topics: await readXTrendingTopics(libRoot), topic: o.topicId, on: true, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 4, now: Date.parse("2026-11-18T10:00:00.000Z") }); + const dir = path.join(xTrendingPostsMediaDir(libRoot), o.postId); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, `${o.postId}_1.jpg`), `picture ${SLICE2_MARKS.media}`); + writeFileSync(path.join(dir, "shot.png"), `shot ${SLICE2_MARKS.shot}`); + writeFileSync( + path.join(dir, "capture.json"), + JSON.stringify({ + version: 1, + id: o.postId, + url: `https://x.com/i/status/${o.postId}`, + capturedAt: "2026-11-18T10:05:00.000Z", + state: "captured", + shot: { name: "shot.png", bytes: 1, sha256: "0".repeat(64) }, + mediaState: "ok", + media: [{ name: `${o.postId}_1.jpg`, bytes: 1, sha256: "0".repeat(64), url: `https://pbs.twimg.com/media/${SLICE2_MARKS.address}.jpg` }], + context: { readAt: "2026-11-18T10:05:00.000Z", quoted: { text: `quoted ${SLICE2_MARKS.context}`, media: [] } }, + }), + ); + await adoptXTrendingMedia(libRoot, { postId: o.postId, name: `${o.postId}_1.jpg`, url: `https://pbs.twimg.com/media/${SLICE2_MARKS.address}.jpg` }); + await ensureXTrendingMediaIgnore(libRoot); + await writePostAvailability(trendingDir(libRoot), { [o.postId]: { availability: "available", checkedAt: "2026-11-18T10:05:00.000Z" } }); +} diff --git a/common/lib/xTrending/config.test.ts b/common/lib/xTrending/config.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { + xTrendingMaxVideoBytes, coerceXTrendingConfig, isXTrendingChannel, parseXTrendingUrl, @@ -76,3 +77,11 @@ test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; o 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' }); }); + +test("the per-file media cap: 100 MB unless the library says otherwise, kept only in range", () => { + assert.equal(xTrendingMaxVideoBytes(undefined), 100 * 1024 * 1024); + assert.equal(xTrendingMaxVideoBytes({ maxVideoMb: 20 }), 20 * 1024 * 1024); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 250 }), { maxVideoMb: 250 }); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 0 }), {}); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 2001 }), {}); +}); diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts @@ -21,6 +21,16 @@ export type XTrendingConfig = { // A read stops scrolling once it has seen this many posts. Absent: // X_TRENDING_DEFAULT_POSTS. maxPosts?: number; + // A media file larger than this many MB is not fetched for a post nobody + // has kept (a watched topic's new posts): it is owed until the post is + // kept. Absent: X_TRENDING_DEFAULT_VIDEO_MB. + maxVideoMb?: number; + // THE WATCH's defaults for this library (lib/xTrending/watch.ts): how often + // a watched topic is read (minutes), for how long (hours), and how many + // topics may be watched at once. Absent: 30, 48 and 4. + watchIntervalMinutes?: number; + watchHours?: number; + watchMaxTopics?: number; }; // The two job kinds, and X's platform queue they run on: one browser on the @@ -49,6 +59,17 @@ 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; +export const X_TRENDING_DEFAULT_VIDEO_MB = 100; +export const X_TRENDING_MAX_VIDEO_MB = 2000; +// The watch: X's gap between two jobs is 5 minutes and a tick is a read and +// then a capture, so nothing shorter than 15 minutes is a real interval. +export const X_TRENDING_WATCH_DEFAULT_INTERVAL_MINUTES = 30; +export const X_TRENDING_WATCH_MIN_INTERVAL_MINUTES = 15; +export const X_TRENDING_WATCH_MAX_INTERVAL_MINUTES = 24 * 60; +export const X_TRENDING_WATCH_DEFAULT_HOURS = 48; +export const X_TRENDING_WATCH_MAX_HOURS = 7 * 24; +export const X_TRENDING_WATCH_DEFAULT_TOPICS = 4; +export const X_TRENDING_WATCH_MAX_TOPICS = 12; // A read ends after this many scrolls in a row that brought no new post. export const X_TRENDING_IDLE_SCROLLS = 2; @@ -66,6 +87,14 @@ export function coerceXTrendingConfig(v: unknown): XTrendingConfig | undefined { const posts = capOf(r.maxPosts, X_TRENDING_MAX_POSTS); if (scrolls !== undefined) out.maxScrolls = scrolls; if (posts !== undefined) out.maxPosts = posts; + const videoMb = capOf(r.maxVideoMb, X_TRENDING_MAX_VIDEO_MB); + if (videoMb !== undefined) out.maxVideoMb = videoMb; + const interval = capOf(r.watchIntervalMinutes, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES); + if (interval !== undefined && interval >= X_TRENDING_WATCH_MIN_INTERVAL_MINUTES) out.watchIntervalMinutes = interval; + const hours = capOf(r.watchHours, X_TRENDING_WATCH_MAX_HOURS); + if (hours !== undefined) out.watchHours = hours; + const topics = capOf(r.watchMaxTopics, X_TRENDING_WATCH_MAX_TOPICS); + if (topics !== undefined) out.watchMaxTopics = topics; return out; } @@ -138,3 +167,42 @@ export function xTrendingLimits( if (typeof posts === "string") return { ok: false, error: posts }; return { ok: true, limits: { scrolls, posts } }; } + +// The per-file cap, in bytes, for media fetched before a post is kept. +export function xTrendingMaxVideoBytes(config: XTrendingConfig | undefined): number { + return (config?.maxVideoMb ?? X_TRENDING_DEFAULT_VIDEO_MB) * 1024 * 1024; +} + +export type XTrendingWatchTerms = { intervalMinutes: number; hours: number }; + +// One watch's interval and length: the ask's, else the library's, else the +// defaults. A value out of range is refused with a sentence, never clamped. +export function xTrendingWatchTerms( + config: XTrendingConfig | undefined, + ask: { intervalMinutes?: unknown; hours?: unknown } = {}, +): { ok: true; terms: XTrendingWatchTerms } | { ok: false; error: string } { + let intervalMinutes = config?.watchIntervalMinutes ?? X_TRENDING_WATCH_DEFAULT_INTERVAL_MINUTES; + if (ask.intervalMinutes !== undefined && ask.intervalMinutes !== null) { + const n = capOf(ask.intervalMinutes, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES); + if (n === undefined || n < X_TRENDING_WATCH_MIN_INTERVAL_MINUTES) { + return { + ok: false, + error: + `"intervalMinutes" is a whole number, ${X_TRENDING_WATCH_MIN_INTERVAL_MINUTES}–${X_TRENDING_WATCH_MAX_INTERVAL_MINUTES} ` + + `(X's jobs are 5 minutes apart, and a tick is a read and then a capture)`, + }; + } + intervalMinutes = n; + } + let hours = config?.watchHours ?? X_TRENDING_WATCH_DEFAULT_HOURS; + if (ask.hours !== undefined && ask.hours !== null) { + const n = capOf(ask.hours, X_TRENDING_WATCH_MAX_HOURS); + if (n === undefined) return { ok: false, error: `"hours" is a whole number, 1–${X_TRENDING_WATCH_MAX_HOURS}` }; + hours = n; + } + return { ok: true, terms: { intervalMinutes, hours } }; +} + +export function xTrendingWatchMaxTopics(config: XTrendingConfig | undefined): number { + return config?.watchMaxTopics ?? X_TRENDING_WATCH_DEFAULT_TOPICS; +} diff --git a/common/lib/xTrending/judgements.test.ts b/common/lib/xTrending/judgements.test.ts @@ -0,0 +1,227 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { judgeXTrending, JUDGED_BY_OPERATOR, NOT_IN_THE_LIBRARY, readXTrendingKeptIds, xTrendingJudgeProblem } from "./judgements"; +import { listXTrending, readXTrendingJudgementsFile, recordXTrendingRead, writeXTrendingPosts } from "./store"; +import type { Post } from "../posts"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-judge-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const READ = "tr-01JA0000000000000000000000"; +const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }; + +function post(id: string, extra: Partial<Post> = {}): Post { + return { + id, + slug: `lib/${id}`, + channelSlug: "lib", + author: "kettle_fan", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: `post ${id}`, + url: `https://x.com/kettle_fan/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + ...extra, + }; +} + +// 501 a root; 502 answers 501; 503 answers 502; 504 alone; 505 answers a post +// the library does not hold (900). +async function library(name: string): Promise<string> { + const dir = path.join(TMP, name); + const posts = [ + post("501"), + post("502", { isReply: true, replyTo: { platform: "twitter", id: "501" } }), + post("503", { isReply: true, replyTo: { platform: "twitter", id: "502" } }), + post("504"), + post("505", { isReply: true, replyTo: { platform: "twitter", id: "900" } }), + ]; + await writeXTrendingPosts(dir, posts); + await recordXTrendingRead(dir, { readId: READ, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: posts.map((p) => p.id), added: posts.length }); + return dir; +} + +const clock = (iso: string) => () => Date.parse(iso); + +test("a judgement is written with who decided and when, and the listing carries it", async () => { + const dir = await library("write"); + const r = await judgeXTrending( + dir, + { by: "agent", set: [{ id: "504", state: "keep", note: " the opening " }, { id: "501", state: "later" }] }, + { now: clock("2026-11-17T11:00:00.000Z") }, + ); + assert.deepEqual(r.written, [{ id: "504", state: "keep" }, { id: "501", state: "later" }]); + assert.deepEqual(r.skipped, []); + assert.deepEqual(r.kept, ["504"]); + const file = JSON.parse(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8")); + assert.deepEqual(file, { + version: 1, + posts: { + "504": { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" }, + "501": { state: "later", by: "agent", at: "2026-11-17T11:00:00.000Z" }, + }, + threads: {}, + }); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.equal(rows["504"].judgement?.state, "keep"); + assert.equal(rows["502"].judgement, undefined); +}); + +test("an agent never replaces the operator's judgement: skipped per id, the rest written", async () => { + const dir = await library("agent"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "501", state: "drop" }] }, { now: clock("2026-11-17T11:00:00.000Z") }); + const r = await judgeXTrending( + dir, + { by: "agent", set: [{ id: "501", state: "keep" }, { id: "504", state: "keep" }] }, + { now: clock("2026-11-17T12:00:00.000Z") }, + ); + assert.deepEqual(r.written, [{ id: "504", state: "keep" }]); + assert.deepEqual(r.skipped, [{ id: "501", reason: JUDGED_BY_OPERATOR }]); + // Nor may an agent clear it. + const cleared = await judgeXTrending(dir, { by: "agent", set: [{ id: "501", state: "undecided" }] }); + assert.deepEqual(cleared.skipped, [{ id: "501", reason: JUDGED_BY_OPERATOR }]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["501"].state, "drop"); + // The operator overturns the agent. + const over = await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "drop" }] }, { now: clock("2026-11-17T13:00:00.000Z") }); + assert.deepEqual(over.written, [{ id: "504", state: "drop" }]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["504"].by, "operator"); +}); + +test("drop is reversible, and undecided removes the entry", async () => { + const dir = await library("reverse"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "drop" }] }); + const back = await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "keep" }] }); + assert.deepEqual(back.kept, ["504"]); + // Keep again: nothing BECAME keep. + assert.deepEqual((await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "keep", note: "still" }] })).kept, []); + await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "undecided" }] }); + assert.deepEqual((await readXTrendingJudgementsFile(dir)).posts, {}); +}); + +test("a thread is judged by its root post's id; a post's own judgement comes first", async () => { + const dir = await library("thread"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "503", state: "drop" }] }); + const r = await judgeXTrending(dir, { by: "agent", set: [{ thread: "501", state: "keep", note: "the whole exchange" }] }); + assert.deepEqual(r.written, [{ thread: "501", state: "keep" }]); + // 501 and 502 became keep through the thread; 503 has its own (drop). + assert.deepEqual(r.kept, ["501", "502"]); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.equal(rows["501"].thread, "501"); + assert.equal(rows["503"].thread, "501"); + assert.deepEqual(rows["502"].judgement && { state: rows["502"].judgement.state, from: rows["502"].judgement.from }, { state: "keep", from: "thread" }); + assert.equal(rows["503"].judgement?.state, "drop"); + assert.equal(rows["503"].judgement?.from, undefined); + // A thread whose root the library lacks is keyed by that root all the same. + assert.equal(rows["505"].thread, "900"); + const t = await judgeXTrending(dir, { by: "agent", set: [{ thread: "900", state: "later" }] }); + assert.deepEqual(t.written, [{ thread: "900", state: "later" }]); +}); + +test("an id the library does not hold is skipped by name, and nothing is written for it", async () => { + const dir = await library("stray"); + const r = await judgeXTrending(dir, { by: "agent", set: [{ id: "999", state: "keep" }, { thread: "998", state: "keep" }] }); + assert.deepEqual(r.written, []); + assert.deepEqual(r.skipped, [ + { id: "999", reason: NOT_IN_THE_LIBRARY }, + { thread: "998", reason: NOT_IN_THE_LIBRARY }, + ]); + assert.equal(existsSync(path.join(dir, "trending", "judgements.json")), false); +}); + +test("the ask's shape is refused with a sentence", () => { + const ok = { by: "agent", set: [{ id: "1", state: "keep" }] }; + assert.equal(xTrendingJudgeProblem(ok), null); + assert.match(xTrendingJudgeProblem({ ...ok, by: "someone" })!, /"by" is who decided/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [] })!, /"set" is a list/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", thread: "1", state: "keep" }] })!, /one of them/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "../x", state: "keep" }] })!, /not a post id/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "maybe" }] })!, /keep, drop, later or undecided/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "undecided", note: "x" }] })!, /carries no note/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep", topic: "t" }] })!, /unknown key/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep" }, { id: "1", state: "drop" }] })!, /judged twice/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep", note: "n".repeat(2001) }] })!, /at most 2000/); +}); + +// Review 1 M2: no way round the operator through the post-over-thread precedence. +test("M2: an agent cannot override the operator's thread judgement with a post-level one, nor the operator's post with a thread-level one", async () => { + const dir = await library("precedence"); + // The operator drops the thread; an agent then tries to keep one post of it. + await judgeXTrending(dir, { by: "operator", set: [{ thread: "501", state: "drop" }] }); + const sneak = await judgeXTrending(dir, { by: "agent", set: [{ id: "502", state: "keep" }, { id: "504", state: "keep" }] }); + assert.deepEqual(sneak.skipped, [{ id: "502", reason: JUDGED_BY_OPERATOR }]); + assert.deepEqual(sneak.written, [{ id: "504", state: "keep" }]); + // Nothing of the dropped thread became keep: nothing of it would be archived. + assert.deepEqual(sneak.kept, ["504"]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["502"], undefined); + let rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.deepEqual([rows["502"].judgement?.state, rows["502"].judgement?.by], ["drop", "operator"]); + // Nor may the agent clear it at post level. + assert.deepEqual((await judgeXTrending(dir, { by: "agent", set: [{ id: "503", state: "undecided" }] })).skipped, [{ id: "503", reason: JUDGED_BY_OPERATOR }]); + // The operator may, of course. + assert.deepEqual((await judgeXTrending(dir, { by: "operator", set: [{ id: "502", state: "keep" }] })).kept, ["502"]); + + // The other direction: the operator drops ONE post; an agent keeps its thread. + const other = await library("precedence-2"); + await judgeXTrending(other, { by: "operator", set: [{ id: "502", state: "drop" }] }); + const thread = await judgeXTrending(other, { by: "agent", set: [{ thread: "501", state: "keep" }] }); + assert.deepEqual(thread.written, [{ thread: "501", state: "keep" }]); + // 502 keeps the operator's drop and is not among the kept. + assert.deepEqual(thread.kept, ["501", "503"]); + rows = Object.fromEntries((await listXTrending(other)).posts.map((p) => [p.id, p])); + assert.deepEqual([rows["502"].judgement?.state, rows["502"].judgement?.by], ["drop", "operator"]); + // And an agent's thread-level write over the operator's thread entry is skipped. + await judgeXTrending(other, { by: "operator", set: [{ thread: "501", state: "later" }] }); + assert.deepEqual((await judgeXTrending(other, { by: "agent", set: [{ thread: "501", state: "keep" }] })).skipped, [{ thread: "501", reason: JUDGED_BY_OPERATOR }]); +}); + +// Review 2 N2: the operator outranks an agent about the same post, whatever the order. +test("N2: an agent's own post entry never outranks the operator's thread entry — not by a later write, not by an older one", async () => { + // The three steps: agent {P, later}; operator {thread, drop}; agent {P, keep}. + const dir = await library("n2-three-steps"); + await judgeXTrending(dir, { by: "agent", set: [{ id: "502", state: "later" }] }); + await judgeXTrending(dir, { by: "operator", set: [{ thread: "501", state: "drop" }] }); + const third = await judgeXTrending(dir, { by: "agent", set: [{ id: "502", state: "keep" }] }); + assert.deepEqual(third.written, []); + assert.deepEqual(third.skipped, [{ id: "502", reason: JUDGED_BY_OPERATOR }]); + assert.deepEqual(third.kept, []); + // The agent's older entry is still in the file, and decides nothing. + assert.equal((await readXTrendingJudgementsFile(dir)).posts["502"].state, "later"); + let row = (await listXTrending(dir)).posts.find((p) => p.id === "502"); + assert.deepEqual([row?.judgement?.state, row?.judgement?.by, row?.judgement?.from], ["drop", "operator", "thread"]); + assert.deepEqual([...(await readXTrendingKeptIds(dir))], []); + + // An OLDER agent keep does not survive the operator's later thread drop. + const older = await library("n2-older-keep"); + assert.deepEqual((await judgeXTrending(older, { by: "agent", set: [{ id: "502", state: "keep" }, { id: "504", state: "keep" }] })).kept, ["502", "504"]); + assert.deepEqual([...(await readXTrendingKeptIds(older))].sort(), ["502", "504"]); + await judgeXTrending(older, { by: "operator", set: [{ thread: "501", state: "drop" }] }); + assert.deepEqual([...(await readXTrendingKeptIds(older))], ["504"]); + row = (await listXTrending(older)).posts.find((p) => p.id === "502"); + assert.deepEqual([row?.judgement?.state, row?.judgement?.by], ["drop", "operator"]); + // The operator lifting the thread judgement lets the agent's suggestion show again. + await judgeXTrending(older, { by: "operator", set: [{ thread: "501", state: "undecided" }] }); + assert.deepEqual([...(await readXTrendingKeptIds(older))].sort(), ["502", "504"]); + + // Two entries of the operator's: the post's own still outranks the thread's, later or not. + const both = await library("n2-operator-both"); + await judgeXTrending(both, { by: "operator", set: [{ id: "502", state: "keep" }] }); + const later = await judgeXTrending(both, { by: "operator", set: [{ thread: "501", state: "drop" }] }); + assert.deepEqual(later.kept, []); + assert.deepEqual([...(await readXTrendingKeptIds(both))], ["502"]); + row = (await listXTrending(both)).posts.find((p) => p.id === "502"); + assert.deepEqual([row?.judgement?.state, row?.judgement?.from], ["keep", undefined]); + // Two of an agent's: the post's own outranks the thread's. + const agents = await library("n2-agent-both"); + await judgeXTrending(agents, { by: "agent", set: [{ thread: "501", state: "drop" }, { id: "503", state: "keep" }] }); + assert.deepEqual([...(await readXTrendingKeptIds(agents))], ["503"]); + // And an agent's thread entry never outranks the operator's entry for a post. + await judgeXTrending(agents, { by: "operator", set: [{ id: "502", state: "keep" }] }); + await judgeXTrending(agents, { by: "agent", set: [{ thread: "501", state: "later" }] }); + assert.deepEqual([...(await readXTrendingKeptIds(agents))].sort(), ["502", "503"]); +}); diff --git a/common/lib/xTrending/judgements.ts b/common/lib/xTrending/judgements.ts @@ -0,0 +1,189 @@ +// THE ONE WRITER OF A LIBRARY'S judgements.json (lane x-trending-2) — the +// editor's `judge-trending`, for an agent and for the operator alike. +// +// keep | drop | later written as the post's (or the thread's) judgement, +// with who decided and when, and a note; +// undecided the entry is REMOVED: no entry is undecided. +// +// AN AGENT'S JUDGEMENT IS A SUGGESTION. A write `by: "agent"` over an entry the +// operator made is SKIPPED for that id and reported; nothing forces it. +// +// THE PRECEDENCE IS ONE RULE (store.ts xTrendingEffectiveJudgement): the +// operator's entry, for the post or for its thread, always outranks an +// agent's about the same post, whatever the order in time; between two +// entries of the same hand the post's own outranks its thread's. So an +// agent's post-level write is skipped whenever the post's thread is the +// operator's, and an operator's thread judgement makes an OLDER agent entry +// for one of its posts ineffective at once (it stays in the file as history +// and decides nothing). The operator overturns anything. `by` is the caller's +// word: an agent is trusted to say "agent". +// +// A THREAD is judged by its root post's id (store.ts xTrendingThreadKey): a +// post of it with no judgement of its own is taken to be the thread's. +// +// DROP DELETES NOTHING. A dropped post keeps its record, its capture and its +// media, and a later keep puts it back. (Removing a capture is +// mediaStore.ts removeXTrendingPostCapture, asked for by nobody in this +// slice.) +// +// Every write is under the file's lock and atomic. SERVER-ONLY (node:fs). + +import { withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; +import type { Post } from "../posts"; +import { + readXTrendingJudgementsFile, + readXTrendingMembership, + readXTrendingPosts, + X_TRENDING_JUDGEMENT_STATES, + xTrendingJudgementsPath, + xTrendingEffectiveJudgement, + xTrendingThreadOf, + type XTrendingJudgement, + type XTrendingJudgementState, +} from "./store"; + +export const X_TRENDING_NOTE_MAX = 2000; +export const X_TRENDING_JUDGE_MAX = 500; + +export type XTrendingJudgeBy = "agent" | "operator"; +export type XTrendingJudgeState = XTrendingJudgementState | "undecided"; + +export type XTrendingJudgeItem = { + // A post's id, or a thread's root post id: one of them. + id?: string; + thread?: string; + state: XTrendingJudgeState; + note?: string; +}; + +export type XTrendingJudgeAsk = { by: XTrendingJudgeBy; set: ReadonlyArray<XTrendingJudgeItem> }; + +// Why this is not a judge ask, or null. Shape only: whether each id is in the +// library is asked of the disk, per id, by the writer. +export function xTrendingJudgeProblem(ask: { by?: unknown; set?: unknown }): string | null { + if (ask.by !== "agent" && ask.by !== "operator") return `"by" is who decided: "agent" or "operator"`; + if (!Array.isArray(ask.set) || ask.set.length === 0) { + return `"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`; + } + if (ask.set.length > X_TRENDING_JUDGE_MAX) return `"set" holds at most ${X_TRENDING_JUDGE_MAX} judgements`; + const seen = new Set<string>(); + for (const [i, raw] of ask.set.entries()) { + const at = `set[${i}]`; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${at} is not an object`; + const item = raw as Record<string, unknown>; + const unknown = Object.keys(item).filter((k) => !["id", "thread", "state", "note"].includes(k)); + if (unknown.length) return `${at}: unknown key(s) ${unknown.join(", ")} (id, thread, state, note)`; + const hasId = item.id !== undefined; + const hasThread = item.thread !== undefined; + if (hasId === hasThread) return `${at}: give "id" (a post) or "thread" (a thread's root post id), one of them`; + const key = hasId ? item.id : item.thread; + if (typeof key !== "string" || !/^\d{1,25}$/.test(key)) return `${at}: "${String(key)}" is not a post id`; + const state = item.state; + if (state !== "undecided" && !X_TRENDING_JUDGEMENT_STATES.includes(state as XTrendingJudgementState)) { + return `${at}: "state" is keep, drop, later or undecided`; + } + if (item.note !== undefined) { + if (typeof item.note !== "string") return `${at}: "note" is text`; + if (item.note.length > X_TRENDING_NOTE_MAX) return `${at}: a note is at most ${X_TRENDING_NOTE_MAX} characters`; + if (state === "undecided" && item.note.trim()) return `${at}: "undecided" removes the judgement, so it carries no note`; + } + const mark = `${hasId ? "p" : "t"}:${key}`; + if (seen.has(mark)) return `${at}: ${hasId ? "post" : "thread"} ${key} is judged twice in one ask`; + seen.add(mark); + } + return null; +} + +export type XTrendingJudged = { id?: string; thread?: string; state: XTrendingJudgeState }; +export type XTrendingJudgeSkipped = { id?: string; thread?: string; reason: string }; + +export type XTrendingJudgeResult = { + written: XTrendingJudged[]; + skipped: XTrendingJudgeSkipped[]; + // Posts whose judgement BECAME keep by this ask (their own, or their + // thread's): what a keep archives. + kept: string[]; +}; + +export const JUDGED_BY_OPERATOR = "judged by the operator: an agent's judgement does not replace it"; +export const NOT_IN_THE_LIBRARY = "not in this library"; + +// The ask applied. `posts` is the library's posts when the caller has them. +export async function judgeXTrending( + channelRoot: string, + ask: XTrendingJudgeAsk, + opts: { now?: () => number; posts?: ReadonlyArray<Post> } = {}, +): Promise<XTrendingJudgeResult> { + const problem = xTrendingJudgeProblem(ask); + if (problem) throw new Error(problem); + const at = new Date((opts.now ?? Date.now)()).toISOString(); + const [membership, posts] = await Promise.all([ + readXTrendingMembership(channelRoot), + opts.posts ?? readXTrendingPosts(channelRoot), + ]); + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + const threadOf = new Map<string, string>(); + const members = new Map<string, string[]>(); + for (const p of byId.values()) { + const key = xTrendingThreadOf(p, membership, byId); + threadOf.set(p.id, key); + members.set(key, [...(members.get(key) ?? []), p.id]); + } + return withJsonFileLock(xTrendingJudgementsPath(channelRoot), async () => { + const file = await readXTrendingJudgementsFile(channelRoot); + const effective = (id: string) => xTrendingEffectiveJudgement(file.posts[id], file.threads[threadOf.get(id) ?? ""])?.state; + const before = new Map([...byId.keys()].map((id) => [id, effective(id)])); + const written: XTrendingJudged[] = []; + const skipped: XTrendingJudgeSkipped[] = []; + for (const item of ask.set) { + const isThread = item.thread !== undefined; + const key = (isThread ? item.thread : item.id) as string; + const name = isThread ? { thread: key } : { id: key }; + if (isThread ? !members.has(key) : !byId.has(key)) { + skipped.push({ ...name, reason: NOT_IN_THE_LIBRARY }); + continue; + } + const map = isThread ? file.threads : file.posts; + const have: XTrendingJudgement | undefined = map[key]; + // AN AGENT NEVER WRITES WHERE THE OPERATOR HAS DECIDED (review 2 N2): not + // over the operator's entry for this key, and not a post-level entry + // for a post whose THREAD the operator judged — whether or not the post + // has an (agent's) entry of its own already. The operator's judgement + // is the one in force there (xTrendingEffectiveJudgement), and an + // agent's write would only be noise beside it. + const threads = isThread ? undefined : file.threads[threadOf.get(key) ?? ""]; + if (ask.by === "agent" && (have?.by === "operator" || threads?.by === "operator")) { + skipped.push({ ...name, reason: JUDGED_BY_OPERATOR }); + continue; + } + if (item.state === "undecided") { + if (have) delete map[key]; + } else { + const note = item.note?.trim(); + map[key] = { state: item.state, ...(note ? { note } : {}), by: ask.by, at }; + } + written.push({ ...name, state: item.state }); + } + if (written.length > 0) { + await writeJsonAtomic(xTrendingJudgementsPath(channelRoot), file, { mkdir: true }); + } + const kept = [...byId.keys()].filter((id) => effective(id) === "keep" && before.get(id) !== "keep").sort(); + return { written, skipped, kept }; + }); +} + +// The posts whose judgement is keep — their own, or their thread's. +export async function readXTrendingKeptIds(channelRoot: string): Promise<Set<string>> { + const [membership, posts, file] = await Promise.all([ + readXTrendingMembership(channelRoot), + readXTrendingPosts(channelRoot), + readXTrendingJudgementsFile(channelRoot), + ]); + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + const kept = new Set<string>(); + for (const p of byId.values()) { + const state = xTrendingEffectiveJudgement(file.posts[p.id], file.threads[xTrendingThreadOf(p, membership, byId)])?.state; + if (state === "keep") kept.add(p.id); + } + return kept; +} diff --git a/common/lib/xTrending/mediaStore.test.ts b/common/lib/xTrending/mediaStore.test.ts @@ -0,0 +1,211 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + adoptXTrendingMedia, + CAPTURE_IN_FLIGHT, + ensureXTrendingMediaIgnore, + noteXTrendingOversize, + xTrendingMediaIndexPath, + linkXTrendingMedia, + readXTrendingMediaIndex, + removeXTrendingPostCapture, + xTrendingBlobByUrl, + xTrendingMediaStoreDir, +} from "./mediaStore"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-media-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +// No capture of the library is queued or running. +const IDLE = { captureInFlight: () => false }; +const sha = (s: string) => createHash("sha256").update(s).digest("hex"); +const root = (name: string) => path.join(TMP, name); +const postDir = (dir: string, id: string) => path.join(dir, "trending", "posts-media", id); + +function put(dir: string, id: string, name: string, bytes: string): string { + mkdirSync(postDir(dir, id), { recursive: true }); + const file = path.join(postDir(dir, id), name); + writeFileSync(file, bytes); + return file; +} + +const blobOf = (dir: string, bytes: string, ext: string) => path.join(xTrendingMediaStoreDir(dir), sha(bytes).slice(0, 2), `${sha(bytes)}.${ext}`); + +test("a captured file becomes the blob; the same bytes under another post are one file", async () => { + const dir = root("dedupe"); + const a = put(dir, "601", "601_1.jpg", "PICTURE-ONE"); + const first = await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg", url: "https://pbs.twimg.com/media/One.jpg", now: () => Date.parse("2026-11-18T10:00:00Z") }); + assert.deepEqual(first, { sha256: sha("PICTURE-ONE"), bytes: 11, deduped: false, linked: true }); + const blob = blobOf(dir, "PICTURE-ONE", "jpg"); + assert.equal(statSync(blob).ino, statSync(a).ino); + assert.equal(statSync(blob).nlink, 2); + + // The same picture on another post, in another topic: fetched again, kept once. + const b = put(dir, "602", "602_1.jpg", "PICTURE-ONE"); + assert.notEqual(statSync(b).ino, statSync(blob).ino); + const second = await adoptXTrendingMedia(dir, { postId: "602", name: "602_1.jpg", url: "https://pbs.twimg.com/media/OneAgain.jpg" }); + assert.equal(second.deduped, true); + assert.equal(statSync(b).ino, statSync(blob).ino); + assert.equal(statSync(blob).nlink, 3); + assert.equal(readFileSync(b, "utf8"), "PICTURE-ONE"); + + // Other bytes are another blob: exact duplicates only. + put(dir, "602", "602_2.jpg", "PICTURE-ONE."); + assert.equal((await adoptXTrendingMedia(dir, { postId: "602", name: "602_2.jpg" })).deduped, false); + + const index = await readXTrendingMediaIndex(dir); + assert.deepEqual(index.blobs[sha("PICTURE-ONE")], { + bytes: 11, + ext: "jpg", + addedAt: "2026-11-18T10:00:00.000Z", + urls: ["https://pbs.twimg.com/media/One.jpg", "https://pbs.twimg.com/media/OneAgain.jpg"], + posts: { "601": ["601_1.jpg"], "602": ["602_1.jpg"] }, + }); + assert.equal(Object.keys(index.blobs).length, 2); + // Adopting the same name again changes nothing. + assert.equal((await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg" })).linked, true); + assert.equal(statSync(blob).nlink, 3); + // No leftover link temp in the capture directory. + assert.deepEqual(readdirSync(postDir(dir, "602")).sort(), ["602_1.jpg", "602_2.jpg"]); +}); + +test("a known address is linked with no fetch; an unknown blob is not", async () => { + const dir = root("link"); + put(dir, "611", "611_1.mp4", "VIDEO-BYTES"); + await adoptXTrendingMedia(dir, { postId: "611", name: "611_1.mp4", url: "https://video.twimg.com/v/high.mp4" }); + const index = await readXTrendingMediaIndex(dir); + const known = xTrendingBlobByUrl(index, "https://video.twimg.com/v/high.mp4"); + assert.equal(known, sha("VIDEO-BYTES")); + assert.equal(xTrendingBlobByUrl(index, "https://video.twimg.com/v/other.mp4"), undefined); + // The post's directory does not exist yet: it is made. + assert.deepEqual(await linkXTrendingMedia(dir, { postId: "612", name: "612_1.mp4", sha256: known! }), { bytes: 11 }); + assert.equal(readFileSync(path.join(postDir(dir, "612"), "612_1.mp4"), "utf8"), "VIDEO-BYTES"); + assert.equal(statSync(blobOf(dir, "VIDEO-BYTES", "mp4")).nlink, 3); + assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs[known!].posts, { "611": ["611_1.mp4"], "612": ["612_1.mp4"] }); + assert.equal(await linkXTrendingMedia(dir, { postId: "613", name: "613_1.mp4", sha256: sha("nothing") }), null); + // A blob removed from the store under the index: not linked (the caller fetches). + rmSync(blobOf(dir, "VIDEO-BYTES", "mp4")); + assert.equal(await linkXTrendingMedia(dir, { postId: "614", name: "614_1.mp4", sha256: known! }), null); + // ...and adopting a file with those bytes puts the blob back. + put(dir, "614", "614_1.mp4", "VIDEO-BYTES"); + await adoptXTrendingMedia(dir, { postId: "614", name: "614_1.mp4" }); + assert.equal(existsSync(blobOf(dir, "VIDEO-BYTES", "mp4")), true); +}); + +test("deleting a post never deletes media another post still uses", async () => { + const dir = root("remove"); + put(dir, "621", "621_1.jpg", "SHARED"); + put(dir, "621", "621_2.jpg", "ONLY-621"); + put(dir, "621", "shot.png", "SHOT"); + put(dir, "621", "capture.json", "{}"); + put(dir, "622", "622_1.jpg", "SHARED"); + await adoptXTrendingMedia(dir, { postId: "621", name: "621_1.jpg" }); + await adoptXTrendingMedia(dir, { postId: "621", name: "621_2.jpg" }); + await adoptXTrendingMedia(dir, { postId: "622", name: "622_1.jpg" }); + const shared = blobOf(dir, "SHARED", "jpg"); + const only = blobOf(dir, "ONLY-621", "jpg"); + assert.equal(statSync(shared).nlink, 3); + + const removed = await removeXTrendingPostCapture(dir, "621", IDLE); + assert.deepEqual(removed, { files: 4, blobsFreed: 1, bytesFreed: 8, blobsKept: 1 }); + assert.equal(existsSync(postDir(dir, "621")), false); + // 622's picture is whole, and so is the store's copy of it. + assert.equal(readFileSync(path.join(postDir(dir, "622"), "622_1.jpg"), "utf8"), "SHARED"); + assert.equal(statSync(shared).nlink, 2); + assert.equal(existsSync(only), false); + const index = await readXTrendingMediaIndex(dir); + assert.deepEqual(Object.keys(index.blobs), [sha("SHARED")]); + assert.deepEqual(index.blobs[sha("SHARED")].posts, { "622": ["622_1.jpg"] }); + + // The last post that carries it takes the blob with it. + assert.deepEqual(await removeXTrendingPostCapture(dir, "622", IDLE), { files: 1, blobsFreed: 1, bytesFreed: 6, blobsKept: 0 }); + assert.equal(existsSync(shared), false); + assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs, {}); + // A post with no capture: nothing to remove, nothing thrown. + assert.deepEqual(await removeXTrendingPostCapture(dir, "629", IDLE), { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }); +}); + +test("a blob something else still links to is kept, even when the index names no post for it", async () => { + const dir = root("stray-link"); + put(dir, "631", "631_1.jpg", "KEPT-ELSEWHERE"); + await adoptXTrendingMedia(dir, { postId: "631", name: "631_1.jpg" }); + // A second name the index never heard of (a file linked by hand). + const { linkSync } = await import("node:fs"); + mkdirSync(postDir(dir, "632"), { recursive: true }); + linkSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg"), path.join(postDir(dir, "632"), "632_1.jpg")); + const removed = await removeXTrendingPostCapture(dir, "631", IDLE); + assert.equal(removed.blobsFreed, 0); + assert.equal(removed.blobsKept, 1); + assert.equal(readFileSync(path.join(postDir(dir, "632"), "632_1.jpg"), "utf8"), "KEPT-ELSEWHERE"); + assert.equal(existsSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg")), true); +}); + +test("ids and names are checked where they become paths; the media is ignored by the corpus repo", async () => { + const dir = root("checks"); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "../x", name: "a.jpg" }), /not a post id/); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: "../a.jpg" }), /not a media file's name/); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: ".hidden" }), /not a media file's name/); + await assert.rejects(removeXTrendingPostCapture(dir, "_avatars", IDLE), /not a post id/); + await ensureXTrendingMediaIgnore(dir); + const ignore = readFileSync(path.join(dir, "trending", ".gitignore"), "utf8"); + assert.match(ignore, /^posts-media\/$/m); + assert.match(ignore, /^media-store\/$/m); +}); + +// Review 1 S8. +test("S8: a media index that is there and cannot be read is never taken for an empty one: nothing is written over it", async () => { + const dir = root("broken-index"); + put(dir, "641", "641_1.jpg", "FIRST"); + await adoptXTrendingMedia(dir, { postId: "641", name: "641_1.jpg" }); + const file = xTrendingMediaIndexPath(dir); + // No file at all IS an empty index. + assert.deepEqual((await readXTrendingMediaIndex(root("no-index-yet"))).blobs, {}); + for (const broken of ['{"version":1,"blobs":{"ab', "[]", ""]) { + writeFileSync(file, broken); + await assert.rejects(readXTrendingMediaIndex(dir), (e: Error) => { + assert.match(e.message, /The library's media index \(.*media-index\.json\) is not (JSON|a media index)/); + assert.match(e.message, /Nothing was written/); + return true; + }); + put(dir, "642", "642_1.jpg", "SECOND"); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "642", name: "642_1.jpg" }), /media index/); + await assert.rejects(linkXTrendingMedia(dir, { postId: "643", name: "643_1.jpg", sha256: sha("FIRST") }), /media index/); + await assert.rejects(noteXTrendingOversize(dir, { url: "https://video.twimg.com/v.mp4", bytes: 9 }), /media index/); + await assert.rejects(removeXTrendingPostCapture(dir, "641", IDLE), /media index/); + assert.equal(readFileSync(path.join(postDir(dir, "641"), "641_1.jpg"), "utf8"), "FIRST"); + // The broken file is as it was: not replaced by a one-entry index. + assert.equal(readFileSync(file, "utf8"), broken); + } +}); + +test("a blob that is not the size of the bytes it is named for is never linked onto; link temps a crash left are swept", async () => { + const dir = root("size"); + put(dir, "651", "651_1.jpg", "WHOLE-PICTURE"); + await adoptXTrendingMedia(dir, { postId: "651", name: "651_1.jpg", url: "https://pbs.twimg.com/media/W.jpg" }); + // The store's copy is cut short under it (and no longer shares the post's bytes). + const blob = blobOf(dir, "WHOLE-PICTURE", "jpg"); + rmSync(blob); + writeFileSync(blob, "WHOLE"); + const b = put(dir, "652", "652_1.jpg", "WHOLE-PICTURE"); + // A crash's leftover link temp beside it. + writeFileSync(path.join(postDir(dir, "652"), ".652_1.jpg.link-99999"), "x"); + const got = await adoptXTrendingMedia(dir, { postId: "652", name: "652_1.jpg" }); + assert.deepEqual([got.deduped, got.linked], [false, false]); + assert.equal(readFileSync(b, "utf8"), "WHOLE-PICTURE"); + assert.deepEqual(readdirSync(postDir(dir, "652")), ["652_1.jpg"]); + // Nor is a known address linked from a blob of the wrong size. + assert.equal(await linkXTrendingMedia(dir, { postId: "653", name: "653_1.jpg", sha256: sha("WHOLE-PICTURE") }), null); +}); + +test("a post's capture is not removed while a capture of the library is queued or running", async () => { + const dir = root("in-flight"); + put(dir, "661", "661_1.jpg", "BYTES"); + await adoptXTrendingMedia(dir, { postId: "661", name: "661_1.jpg" }); + await assert.rejects(removeXTrendingPostCapture(dir, "661", { captureInFlight: async () => true }), (e: Error) => e.message === CAPTURE_IN_FLIGHT); + assert.equal(existsSync(path.join(postDir(dir, "661"), "661_1.jpg")), true); + assert.equal((await removeXTrendingPostCapture(dir, "661", IDLE)).files, 1); +}); diff --git a/common/lib/xTrending/mediaStore.ts b/common/lib/xTrending/mediaStore.ts @@ -0,0 +1,376 @@ +// A LIBRARY'S MEDIA, KEPT ONCE (lane x-trending-2). +// +// channels/<lib>/trending/media-store/<aa>/<sha256>.<ext> the bytes, once +// per content hash +// channels/<lib>/trending/posts-media/<id>/<name> a HARDLINK to +// its blob +// channels/<lib>/trending/media-index.json hash → bytes, +// the addresses it came from, and the posts (and file names) that carry it +// +// EXACT DUPLICATES ONLY: two files are one when their SHA-256 is. The same +// video at another quality, or a picture re-encoded, is another file. +// +// WHY HARDLINKS. Every reader of a capture directory (the listing's +// thumbnail, the capture's own file list, umtool) opens a plain file and +// needs to know nothing. Unlinking one post's name cannot touch another +// post's bytes: the file system counts the links, and the bytes go when the +// last one does. A file system that refuses a link (another device, a link +// limit) leaves the file where it was, an ordinary copy: nothing is lost, +// that file is simply not shared. +// +// KNOWN ADDRESS, NO FETCH. The index remembers the address each blob came +// from, so a post carrying a file the library already holds is linked to it +// without asking the CDN (linkXTrendingMedia). +// +// NOT IN THE MEDIA TIER. The tier (lib/mediaTier.ts) is by name over a video +// dir, `data/<id>/`; no posts channel's `posts-media/` is in it, and a +// library's is not either: it stays on the corpus disk beside the library's +// text, like `clips/`. So nothing here is a link out of the channel, and +// removeMediaFile (the one `rm` of a media file) removes these names as the +// plain files they are. +// +// NEVER COMMITTED. `trending/.gitignore` keeps `posts-media/` and +// `media-store/` out of the corpus's own git repo: hardlinks do not survive +// git, and the bytes are big. The index is small text and is not ignored. +// +// THIS MODULE IS THE ONE WRITER of media-index.json and of the store; every +// write is under the index's lock. SERVER-ONLY (node:fs). + +import path from "node:path"; +import { link, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat } from "node:fs/promises"; +import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; +import { removeMediaFile } from "../mediaTier-server"; +import { fileDigest, postCaptureDir } from "../../social/postCapture"; +import { trendingDir, xTrendingPostsMediaDir } from "./store"; + +export const X_TRENDING_MEDIA_STORE_DIRNAME = "media-store"; +export const X_TRENDING_MEDIA_INDEX_FILENAME = "media-index.json"; + +export function xTrendingMediaStoreDir(channelRoot: string): string { + return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_STORE_DIRNAME); +} + +export function xTrendingMediaIndexPath(channelRoot: string): string { + return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_INDEX_FILENAME); +} + +export const TRENDING_MEDIA_GITIGNORE = + "# A library's captured media: hardlinked, big, never committed.\nposts-media/\nmedia-store/\n"; + +// trending/, with the .gitignore that keeps the media out of the corpus repo. +export async function ensureXTrendingMediaIgnore(channelRoot: string): Promise<void> { + const dir = trendingDir(channelRoot); + await mkdir(dir, { recursive: true }); + const file = path.join(dir, ".gitignore"); + const have = await readFile(file, "utf8").catch(() => null); + if (have !== TRENDING_MEDIA_GITIGNORE) await writeFileAtomic(file, TRENDING_MEDIA_GITIGNORE); +} + +export type XTrendingMediaBlob = { + bytes: number; + ext: string; + addedAt: string; + // The addresses this content came from (a file's identity address, as the + // capture names it), oldest first. + urls: string[]; + // Post id → its file names that are this blob. + posts: Record<string, string[]>; +}; + +export type XTrendingMediaIndex = { + version: 1; + blobs: Record<string, XTrendingMediaBlob>; + // Addresses whose file was found larger than a cap, and how large (the + // cap + 1 when it was cut off mid-stream): not asked for again while the + // cap stands, so a watch does not start the same big download every tick. + oversize: Record<string, { bytes: number; at: string }>; +}; + +const SHA = /^[0-9a-f]{64}$/; +const POST_ID = /^\d{1,25}$/; +// A media file's name inside a capture directory: no path, no dotfile. +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/; + +function parseIndex(raw: unknown): XTrendingMediaIndex { + const blobs = (raw as { blobs?: unknown } | null)?.blobs; + const out: XTrendingMediaIndex = { version: 1, blobs: {}, oversize: {} }; + const oversize = (raw as { oversize?: unknown } | null)?.oversize; + if (oversize && typeof oversize === "object" && !Array.isArray(oversize)) { + for (const [url, o] of Object.entries(oversize as Record<string, { bytes?: unknown; at?: unknown } | null>)) { + if (!o || typeof o !== "object" || !(Number(o.bytes) > 0)) continue; + out.oversize[url] = { bytes: Number(o.bytes), at: typeof o.at === "string" ? o.at : "" }; + } + } + if (!blobs || typeof blobs !== "object" || Array.isArray(blobs)) return out; + for (const [sha, b] of Object.entries(blobs as Record<string, Partial<XTrendingMediaBlob> | null>)) { + if (!SHA.test(sha) || !b || typeof b !== "object") continue; + const posts: Record<string, string[]> = {}; + for (const [id, names] of Object.entries(b.posts && typeof b.posts === "object" ? b.posts : {})) { + if (!POST_ID.test(id) || !Array.isArray(names)) continue; + const kept = names.filter((n): n is string => typeof n === "string" && NAME.test(n)); + if (kept.length > 0) posts[id] = kept; + } + out.blobs[sha] = { + bytes: Number(b.bytes) || 0, + ext: typeof b.ext === "string" && /^[a-z0-9]{1,5}$/.test(b.ext) ? b.ext : "bin", + addedAt: typeof b.addedAt === "string" ? b.addedAt : "", + urls: Array.isArray(b.urls) ? b.urls.filter((u): u is string => typeof u === "string" && u !== "") : [], + posts, + }; + } + return out; +} + +// The index exists and cannot be read as one. +export class XTrendingMediaIndexError extends Error { + constructor(file: string, why: string) { + super( + `The library's media index (${file}) ${why}. Nothing was written: an index read as empty would be written back over the record of ` + + "every file the library holds. Repair the file, or move it away (the store's files stay; captures made after that are indexed afresh).", + ); + this.name = "XTrendingMediaIndexError"; + } +} + +// The index — an EMPTY one only when there is no file yet. A file that is +// there and cannot be read or parsed THROWS (review 1 S8): every writer here +// reads, changes and writes back, and "unreadable" taken for "empty" would +// replace the whole record with the one entry being added. The capture job +// fails with the sentence, naming the file. +export async function readXTrendingMediaIndex(channelRoot: string): Promise<XTrendingMediaIndex> { + const file = xTrendingMediaIndexPath(channelRoot); + const read = await readJsonFile(file); + if (!read.ok) { + if (read.reason === "absent") return { version: 1, blobs: {}, oversize: {} }; + throw new XTrendingMediaIndexError(file, read.reason === "unparseable" ? "is not JSON (cut short, or edited by hand)" : "cannot be read"); + } + if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) { + throw new XTrendingMediaIndexError(file, "is not a media index (not an object)"); + } + return parseIndex(read.value); +} + +// The blob that came from this address, or undefined. +export function xTrendingBlobByUrl(index: XTrendingMediaIndex, url: string): string | undefined { + for (const [sha, b] of Object.entries(index.blobs)) if (b.urls.includes(url)) return sha; + return undefined; +} + +function extOf(name: string): string { + const ext = path.extname(name).slice(1).toLowerCase(); + return /^[a-z0-9]{1,5}$/.test(ext) ? ext : "bin"; +} + +function blobPath(channelRoot: string, sha: string, ext: string): string { + return path.join(xTrendingMediaStoreDir(channelRoot), sha.slice(0, 2), `${sha}.${ext}`); +} + +function checked(postId: string, name: string): void { + if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); + if (!NAME.test(name)) throw new Error(`"${name}" is not a media file's name`); +} + +// `target` linked at `file`, replacing what is there, atomically (a link +// beside it, renamed over it). False when the file system refuses the link. +async function linkOver(target: string, file: string): Promise<boolean> { + const tmp = path.join(path.dirname(file), `.${path.basename(file)}.link-${process.pid}`); + await rm(tmp, { force: true }); + try { + await link(target, tmp); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === "EXDEV" || code === "EPERM" || code === "EMLINK" || code === "ENOTSUP") return false; + throw err; + } + await rename(tmp, file); + return true; +} + +// Link temps a crash left in a capture directory (`.<name>.link-<pid>`): +// removed under the index's lock, where no link of this process is in flight. +async function sweepLinkTemps(dir: string): Promise<void> { + const names = await readdir(dir).catch(() => [] as string[]); + for (const name of names) if (/^\..+\.link-\d+$/.test(name)) await rm(path.join(dir, name), { force: true }); +} + +const sameFile = (a: { dev: number; ino: number }, b: { dev: number; ino: number }) => a.dev === b.dev && a.ino === b.ino; + +function note(blob: XTrendingMediaBlob, postId: string, name: string, url?: string): void { + const names = (blob.posts[postId] ??= []); + if (!names.includes(name)) names.push(name); + if (url && !blob.urls.includes(url)) blob.urls.push(url); +} + +// An address whose file is larger than a cap, remembered with its size. +export async function noteXTrendingOversize( + channelRoot: string, + o: { url: string; bytes: number; now?: () => number }, +): Promise<void> { + await withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const index = await readXTrendingMediaIndex(channelRoot); + index.oversize[o.url] = { bytes: o.bytes, at: new Date((o.now ?? Date.now)()).toISOString() }; + await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + }); +} + +export type AdoptedMedia = { + sha256: string; + bytes: number; + // The library already held these bytes: this name is now a link to them. + deduped: boolean; + // The name shares its bytes with the store (false: the file system refused + // the link, and the file stays an ordinary copy). + linked: boolean; +}; + +// A FILE JUST CAPTURED, TAKEN INTO THE STORE: hashed, and either linked to the +// blob the library already holds for that content (its own bytes dropped) or +// made the blob. `url` is the address it came from, when known. +export async function adoptXTrendingMedia( + channelRoot: string, + o: { postId: string; name: string; url?: string; now?: () => number }, +): Promise<AdoptedMedia> { + checked(o.postId, o.name); + const file = path.join(postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId), o.name); + const { sha256, bytes } = await fileDigest(file); + await ensureXTrendingMediaIgnore(channelRoot); + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const index = await readXTrendingMediaIndex(channelRoot); + const have = index.blobs[sha256]; + const ext = have?.ext ?? extOf(o.name); + const blob = blobPath(channelRoot, sha256, ext); + await mkdir(path.dirname(blob), { recursive: true }); + await sweepLinkTemps(path.dirname(file)); + const [fileStat, blobStat] = await Promise.all([stat(file), stat(blob).catch(() => null)]); + let deduped = false; + let linked: boolean; + if (blobStat && sameFile(fileStat, blobStat)) { + linked = true; + } else if (blobStat && blobStat.size !== bytes) { + // A blob under this hash's name that is not this size is not these + // bytes (cut short, or changed under the store): never linked onto. + // The file stays its own copy, and the index does not claim it. + return { sha256, bytes, deduped: false, linked: false }; + } else if (blobStat) { + // The library holds these bytes: this name becomes a link to them. + linked = await linkOver(blob, file); + deduped = linked; + } else { + // New content (or a blob somebody removed): this file is the blob. + linked = await linkOver(file, blob); + } + const entry = (index.blobs[sha256] ??= { + bytes, + ext, + addedAt: new Date((o.now ?? Date.now)()).toISOString(), + urls: [], + posts: {}, + }); + note(entry, o.postId, o.name, o.url); + if (o.url) delete index.oversize[o.url]; + await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return { sha256, bytes, deduped, linked }; + }); +} + +// A BLOB THE LIBRARY HOLDS, GIVEN TO ANOTHER POST: `name` in the post's +// capture directory becomes a link to it — no fetch, no copy. Null when the +// store no longer has the blob (the caller fetches), or the link is refused. +export async function linkXTrendingMedia( + channelRoot: string, + o: { postId: string; name: string; sha256: string; url?: string }, +): Promise<{ bytes: number } | null> { + checked(o.postId, o.name); + if (!SHA.test(o.sha256)) return null; + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const index = await readXTrendingMediaIndex(channelRoot); + const entry = index.blobs[o.sha256]; + if (!entry) return null; + const blob = blobPath(channelRoot, o.sha256, entry.ext); + const blobStat = await stat(blob).catch(() => null); + if (!blobStat?.isFile()) return null; + // The index's size for it, or it is not the file the index means. + if (entry.bytes > 0 && blobStat.size !== entry.bytes) return null; + const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId); + await mkdir(dir, { recursive: true }); + await sweepLinkTemps(dir); + if (!(await linkOver(blob, path.join(dir, o.name)))) return null; + note(entry, o.postId, o.name, o.url); + await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return { bytes: blobStat.size }; + }); +} + +export type RemovedCapture = { + // Names removed from the post's capture directory. + files: number; + // Blobs no other post carried, removed with it, and their size. + blobsFreed: number; + bytesFreed: number; + // Blobs this post carried that another post still does: left alone. + blobsKept: number; +}; + +// ONE POST'S CAPTURE, REMOVED: its directory's files (through removeMediaFile) +// and the directory; and each blob it carried, ONLY when no other post carries +// it and nothing else links to it. Media another post still uses is never +// deleted: its bytes stay under that post's name and in the store. +// (No door calls this in this slice; the purge button and its ops twin are a +// later one's.) +// +// REFUSED WHILE A CAPTURE OF THE LIBRARY IS QUEUED OR RUNNING (`captureInFlight`, +// which the caller answers from its job registry — required, so no door can +// forget it): a capture writes these same directories outside the lock. +export const CAPTURE_IN_FLIGHT = + "A capture of this library is queued or running: remove a post's capture once it has finished (its job is on /jobs)."; + +export async function removeXTrendingPostCapture( + channelRoot: string, + postId: string, + o: { captureInFlight: () => boolean | Promise<boolean> }, +): Promise<RemovedCapture> { + if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); + if (await o.captureInFlight()) throw new Error(CAPTURE_IN_FLIGHT); + const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId); + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const out: RemovedCapture = { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }; + // The index FIRST: one that cannot be read stops this before a file goes. + const index = await readXTrendingMediaIndex(channelRoot); + const names = await readdir(dir).catch(() => [] as string[]); + for (const name of names) { + const st = await lstat(path.join(dir, name)).catch(() => null); + if (!st) continue; + if (st.isDirectory()) await rm(path.join(dir, name), { recursive: true, force: true }); + else await removeMediaFile(dir, name); + out.files++; + } + await rmdir(dir).catch(() => {}); + let changed = false; + for (const [sha, entry] of Object.entries(index.blobs)) { + if (!entry.posts[postId]) continue; + delete entry.posts[postId]; + changed = true; + if (Object.keys(entry.posts).length > 0) { + out.blobsKept++; + continue; + } + const blob = blobPath(channelRoot, sha, entry.ext); + const st = await stat(blob).catch(() => null); + // A link the index does not know of (a name copied by hand, an index + // that lost a post): the bytes are still somebody's, so the blob stays. + if (st && st.nlink > 1) { + out.blobsKept++; + continue; + } + if (st) { + await rm(blob, { force: true }); + await rmdir(path.dirname(blob)).catch(() => {}); + out.bytesFreed += st.size; + } + delete index.blobs[sha]; + out.blobsFreed++; + } + if (changed) await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return out; + }); +} diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import path from "node:path"; import { + xTrendingThreadKey, listXTrending, readXTrendingMembership, readXTrendingTopics, @@ -77,6 +78,8 @@ test("the first read of a page makes a topic named for it; a re-read adds posts, topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: true }, placed: 2, kept: 0, + gone: [], + back: [], }); await writeXTrendingPosts(dir, [post("103", "lid_watch", "three")]); const second = await recordXTrendingRead(dir, { @@ -90,6 +93,9 @@ test("the first read of a page makes a topic named for it; a re-read adds posts, topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: false }, placed: 1, kept: 1, + // 102 was not shown, but this read did not say it reached the page's end. + gone: [], + back: [], }); const topics = await readXTrendingTopics(dir); assert.equal(topics.length, 1); @@ -148,7 +154,7 @@ test("a named topic is found by id or title, else made; a second page merges int postIds: ["201", "203"], added: 1, }); - assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1 }); + assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1, gone: [], back: [] }); const members = await readXTrendingMembership(dir); assert.equal(members["201"].topic, "kettle-festival"); assert.equal(members["203"].topic, "saucers"); @@ -192,6 +198,7 @@ test("the listing gives each post's words, author, media, reads and topic — an media: { count: 2, kinds: ["image"] }, topic: "kettles", reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }], + thread: "301", }, { id: "302", @@ -202,6 +209,7 @@ test("the listing gives each post's words, author, media, reads and topic — an media: { count: 0, kinds: [] }, topic: "kettles", reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }], + thread: "302", }, ]); assert.equal(all.total, 2); @@ -286,3 +294,78 @@ test("no module of the lane reaches the channel's own posts-media: a library's m const { xTrendingPostsMediaDir } = await import("./store"); assert.equal(xTrendingPostsMediaDir("/c/lib"), "/c/lib/trending/posts-media"); }); + +// Lane x-trending-2. +test("gone from the page: only a read that reached the page's end says so, only of posts that page showed, and a post shown again is back", async () => { + const dir = root("gone"); + await writeXTrendingPosts(dir, [post("801", "a", "one"), post("802", "b", "two"), post("803", "c", "three"), post("804", "d", "four")]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["801", "802"], added: 2, complete: true }); + // Another page of the same topic showed 803; it is never judged by REF's reads. + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T10:30:00.000Z", ref: REF_2, topic: "T", postIds: ["803"], added: 1, complete: true }); + // A read that stopped at its cap asserts nothing. + const capped = await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0 }); + assert.deepEqual(capped.gone, []); + assert.equal((await readXTrendingMembership(dir))["802"].gone, undefined); + // A complete one does: 802 is gone from the page; 803 (the other page's) and 804 (new) are not. + const READ_D = "tr-01JD0000000000000000000000"; + const done = await recordXTrendingRead(dir, { readId: READ_D, at: "2026-11-17T11:30:00.000Z", ref: REF, topic: "T", postIds: ["801", "804"], added: 1, complete: true }); + assert.deepEqual(done.gone, ["802"]); + let members = await readXTrendingMembership(dir); + assert.deepEqual(members["802"].gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId }); + assert.equal(members["803"].gone, undefined); + assert.equal(members["804"].gone, undefined); + const row = (await listXTrending(dir)).posts.find((p) => p.id === "802"); + assert.deepEqual(row?.gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId }); + // Recorded once: a later complete read without it does not move the time. + const READ_E = "tr-01JE0000000000000000000000"; + assert.deepEqual((await recordXTrendingRead(dir, { readId: READ_E, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0, complete: true })).gone, ["804"]); + assert.equal((await readXTrendingMembership(dir))["802"].gone?.at, "2026-11-17T11:30:00.000Z"); + // Shown again: back, with the absence kept as history. + const READ_F = "tr-01JF0000000000000000000000"; + const back = await recordXTrendingRead(dir, { readId: READ_F, at: "2026-11-17T12:30:00.000Z", ref: REF, topic: "T", postIds: ["802", "801"], added: 0, complete: true }); + assert.deepEqual(back.back, ["802"]); + members = await readXTrendingMembership(dir); + assert.equal(members["802"].gone, undefined); + assert.deepEqual(members["802"].wasGone, [{ from: "2026-11-17T11:30:00.000Z", to: "2026-11-17T12:30:00.000Z" }]); +}); + +test("a captured post's row says what its capture holds and what it is owed", async () => { + const dir = root("capture-summary"); + await writeXTrendingPosts(dir, [post("811", "a", "one"), post("812", "b", "two")]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["811", "812"], added: 2 }); + mkdirSync(path.join(dir, "trending", "posts-media", "811"), { recursive: true }); + writeFileSync( + path.join(dir, "trending", "posts-media", "811", "capture.json"), + JSON.stringify({ version: 1, id: "811", capturedAt: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "error", mediaOwed: "kept", media: [{ name: "811_1.jpg" }] }), + ); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.deepEqual(rows["811"].capture, { at: "2026-11-17T10:05:00.000Z", state: "captured", shot: false, files: 1, mediaState: "error", mediaOwed: "kept" }); + assert.equal(rows["812"].capture, undefined); +}); + +// Review 1: a thread's key is decided once. +test("a thread's key ignores a threadId that only repeats the post's id, and does not move as ancestors arrive", async () => { + // Raw X posts whose answer carried no conversation id: the normalizer sets threadId = id. + const reply = (id: string, to?: string): Post => ({ ...post(id, "a", `post ${id}`), threadId: id, ...(to ? { isReply: true, replyTo: { platform: "twitter" as const, id: to } } : {}) }); + const byId = (...posts: Post[]) => new Map(posts.map((p) => [p.id, p])); + const c = reply("903", "902"); + // Its own id as threadId says nothing: the chain it answers decides. + assert.equal(xTrendingThreadKey(c, byId(c)), "902"); + assert.equal(xTrendingThreadKey(reply("901"), byId()), "901"); + // A real conversation id (another post's) is the key. + assert.equal(xTrendingThreadKey({ ...c, threadId: "900" }, byId(c)), "900"); + + const dir = root("thread-stable"); + await writeXTrendingPosts(dir, [c]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["903"], added: 1, threads: { "903": xTrendingThreadKey(c, byId(c)) } }); + assert.equal((await listXTrending(dir)).posts[0].thread, "902"); + // Its parent arrives later, itself a reply to 901: computed afresh the key would now be 901. + const b = reply("902", "901"); + await writeXTrendingPosts(dir, [b]); + assert.equal(xTrendingThreadKey(c, byId(c, b)), "901"); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "T", postIds: ["902", "903"], added: 1, threads: { "902": "901", "903": "901" } }); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p.thread])); + // 903 keeps the key it was placed with; 902 gets its own, decided now. + assert.deepEqual(rows, { "902": "901", "903": "902" }); + assert.equal((await readXTrendingMembership(dir))["903"].thread, "902"); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -28,12 +28,17 @@ // 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. +// channels/<lib>/trending/judgements.json post id → {state: "keep" | +// "drop" | "later", note?, by: "agent" | "operator", at}, and the same +// per THREAD (keyed by its root post's id). No entry = undecided. +// Written by ONE writer, lib/xTrending/judgements.ts (the editor's +// `judge-trending`); read here, so a row carries its judgement. +// channels/<lib>/trending/watch.json the watched topics +// (lib/xTrending/watch.ts is its one writer) +// channels/<lib>/trending/posts-media/<id>/ a captured post: its shot, its +// capture.json and its media, each media file a HARDLINK to +// channels/<lib>/trending/media-store/ the library's media, once per +// content hash, with media-index.json (lib/xTrending/mediaStore.ts) // // SERVER-ONLY (node:fs). @@ -43,6 +48,8 @@ import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; import type { Post } from "../posts"; import type { XTrendingRef } from "./config"; +// (./watch imports only TYPES of this module: no cycle.) +import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch"; export const TRENDING_DIRNAME = "trending"; export const TRENDING_READS_DIRNAME = "reads"; @@ -121,10 +128,11 @@ 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"]; +// "later" is a decision put off by someone; no entry is a post nobody has +// judged (undecided). Clearing a judgement removes the entry. +export type XTrendingJudgementState = "keep" | "drop" | "later"; +export const X_TRENDING_JUDGEMENT_STATES: readonly XTrendingJudgementState[] = ["keep", "drop", "later"]; -// A post's judgement (slice 3 writes it; this slice only reads it). export type XTrendingJudgement = { state: XTrendingJudgementState; note?: string; @@ -132,13 +140,22 @@ export type XTrendingJudgement = { 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 {}; +export type XTrendingJudgementsFile = { + version: 1; + posts: Record<string, XTrendingJudgement>; + // A thread's judgement, keyed by its root post's id: what a post of the + // thread with no judgement of its own is taken to be. + threads: Record<string, XTrendingJudgement>; +}; + +export function xTrendingJudgementsPath(channelRoot: string): string { + return judgementsPath(channelRoot); +} + +function parseJudgements(raw: unknown): Record<string, XTrendingJudgement> { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const out: Record<string, XTrendingJudgement> = {}; - for (const [id, j] of Object.entries(posts as Record<string, Partial<XTrendingJudgement> | null>)) { + for (const [id, j] of Object.entries(raw 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; @@ -152,6 +169,81 @@ export async function readXTrendingJudgements(channelRoot: string): Promise<Reco return out; } +// judgements.json whole, or an empty one while there is none. Ill-shaped +// entries are dropped. +export async function readXTrendingJudgementsFile(channelRoot: string): Promise<XTrendingJudgementsFile> { + const read = await readJsonFile(judgementsPath(channelRoot)); + const value = read.ok ? (read.value as { posts?: unknown; threads?: unknown } | null) : null; + return { version: 1, posts: parseJudgements(value?.posts), threads: parseJudgements(value?.threads) }; +} + +// The posts' own judgements. +export async function readXTrendingJudgements(channelRoot: string): Promise<Record<string, XTrendingJudgement>> { + return (await readXTrendingJudgementsFile(channelRoot)).posts; +} + +// WHICH JUDGEMENT IS IN FORCE FOR A POST — the ONE rule (review 2 N2), used by +// the writer, the listing and everything that asks whether a post is kept: +// +// - the OPERATOR's entry always outranks an agent's about the same post, +// whichever was written first and whichever is the post's own: an +// operator's judgement of the thread stands over an agent's entry for one +// of its posts; +// - between two entries of the same hand (two of the operator's, or two of +// an agent's), the post's own entry outranks its thread's. +// +// An agent's entry the operator's outranks stays in the file, as history; it +// decides nothing. +export function xTrendingEffectiveJudgement( + own: XTrendingJudgement | undefined, + thread: XTrendingJudgement | undefined, +): (XTrendingJudgement & { from?: "thread" }) | undefined { + if (own && thread && own.by === "agent" && thread.by === "operator") return { ...thread, from: "thread" }; + if (own) return own; + return thread ? { ...thread, from: "thread" } : undefined; +} + +// A THREAD'S KEY is its root post's id. The source's own `threadId` when it +// names ANOTHER post (X's conversation id) — a normalized X post always has +// one, and when the answer gave no conversation id it is the post's own id, +// which says nothing (review 1). Then the chain of posts it answers, followed +// through the library's posts as far as they go: the first ancestor the +// library lacks is the root as far as anyone here knows. A post that answers +// nothing is its own thread. +// +// DECIDED ONCE PER POST. The walk's answer moves as ancestors arrive, so a +// post's key is computed when the post is first placed in a topic and kept in +// its membership record (`thread`); everything that asks a post's thread asks +// xTrendingThreadOf, which reads that record. +export function xTrendingThreadKey(post: Post, byId: ReadonlyMap<string, Post>): string { + const named = (p: Post) => (p.threadId && /^\d+$/.test(p.threadId) && p.threadId !== p.id ? p.threadId : undefined); + const own = named(post); + if (own) return own; + let at = post; + const walked = new Set<string>([post.id]); + for (let hops = 0; hops < 64; hops++) { + const parent = at.replyTo?.id; + if (!parent || !/^\d+$/.test(parent)) return at.id; + const next = byId.get(parent); + if (!next || walked.has(parent)) return parent; + const theirs = named(next); + if (theirs) return theirs; + walked.add(parent); + at = next; + } + return at.id; +} + +// A post's thread: the key its membership record holds, else (a member placed +// before keys were kept) the walk's answer now. +export function xTrendingThreadOf( + post: Post, + membership: Readonly<Record<string, { thread?: string } | undefined>>, + byId: ReadonlyMap<string, Post>, +): string { + return membership[post.id]?.thread ?? xTrendingThreadKey(post, byId); +} + const IMAGE_FILE = /\.(?:jpe?g|png|webp|gif)$/i; // WHERE A LIBRARY'S CAPTURED MEDIA LIVES (review 2 N9): under trending/, as @@ -181,6 +273,36 @@ export async function firstCapturedThumbnail(channelRoot: string, id: string): P return pick ? `${TRENDING_DIRNAME}/${LIBRARY_MEDIA_DIRNAME}/${id}/${pick}` : undefined; } +// A captured post, as the listing says it: whether it was shot, how many media +// files it holds, how its media half stands ("ok", "none", "skipped", +// "error") and what it is owed ("next": a later capture asks again; "kept": +// once the post is marked keep). +export type XTrendingCaptureSummary = { + at: string; + state: string; + shot: boolean; + files: number; + mediaState: string; + mediaOwed?: "next" | "kept"; +}; + +// capture.json of a library post, read as plain JSON (its writer is +// social/postCapture.ts; this module imports nothing of social/). +export async function xTrendingCaptureSummary(channelRoot: string, id: string): Promise<XTrendingCaptureSummary | undefined> { + if (!/^\d+$/.test(id)) return undefined; + const read = await readJsonFile(path.join(xTrendingPostsMediaDir(channelRoot), id, "capture.json")); + const r = read.ok ? (read.value as Record<string, unknown> | null) : null; + if (!r || typeof r !== "object" || typeof r.capturedAt !== "string" || typeof r.state !== "string") return undefined; + return { + at: r.capturedAt, + state: r.state, + shot: !!r.shot, + files: Array.isArray(r.media) ? r.media.length : 0, + mediaState: typeof r.mediaState === "string" ? r.mediaState : "skipped", + ...(r.mediaOwed === "next" || r.mediaOwed === "kept" ? { mediaOwed: r.mediaOwed } : {}), + }; +} + 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. @@ -210,10 +332,22 @@ export type XTrendingTopic = { export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number }; +// GONE FROM THE PAGE (lane x-trending-2): a post a page showed before, absent +// from a later read of that page that reached the page's end. It says what +// the page showed and NOTHING about the post — a trending page is a ranked +// list, and a post leaves it by being outranked as well as by being deleted. +// A read that stopped at a cap, was cancelled or failed asserts nothing. +export type XTrendingGone = { at: string; read: string; trendId: string }; + export type XTrendingMember = { topic: string; + // Its thread's key, decided when it was placed (xTrendingThreadKey). + thread?: string; seen: XTrendingSeen[]; media?: XTrendingMedia; + gone?: XTrendingGone; + // Earlier absences that ended: gone from `from`, shown again at `to`. + wasGone?: Array<{ from: string; to: string }>; }; type TopicsFile = { version: 1; topics: XTrendingTopic[] }; @@ -270,7 +404,19 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { ), } : undefined; - out[id] = { topic: m.topic, seen, ...(media ? { media } : {}) }; + const g = m.gone as Partial<XTrendingGone> | undefined; + const gone = g && typeof g === "object" && str(g.at) && isXTrendingReadId(g.read) && str(g.trendId) ? { at: g.at, read: g.read, trendId: g.trendId } : undefined; + const wasGone = (Array.isArray(m.wasGone) ? m.wasGone : []).filter( + (w): w is { from: string; to: string } => !!w && typeof w === "object" && str(w.from) && str(w.to), + ); + out[id] = { + topic: m.topic, + ...(typeof m.thread === "string" && /^\d+$/.test(m.thread) ? { thread: m.thread } : {}), + seen, + ...(media ? { media } : {}), + ...(gone ? { gone } : {}), + ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}), + }; } return out; } @@ -321,6 +467,12 @@ export type RecordReadInput = { // How many of them the library did not hold before this read. added: number; media?: Readonly<Record<string, XTrendingMedia>>; + // Post id → its thread's key, for posts this read places (a member that + // has a key keeps it). + threads?: Readonly<Record<string, string>>; + // The read reached the page's end (it stopped because the page had no more + // to show): only then is a post it did not show marked gone from the page. + complete?: boolean; }; export type RecordReadResult = { @@ -329,6 +481,10 @@ export type RecordReadResult = { placed: number; // Posts the library already had, left in the topic they were in. kept: number; + // Posts this page showed before and did not show now (a complete read + // only), and posts that were gone and are shown again. + gone: string[]; + back: string[]; }; // One read, recorded: its topic found or made, the page added to the topic's @@ -378,6 +534,8 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const posts = await readXTrendingMembership(channelRoot); let placed = 0; let kept = 0; + const gone: string[] = []; + const back: string[] = []; 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]; @@ -385,13 +543,35 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead 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]; + if (!have.thread && input.threads?.[id]) have.thread = input.threads[id]; + // Shown again, by a read later than the one that missed it. + if (have.gone && input.at > have.gone.at) { + (have.wasGone ??= []).push({ from: have.gone.at, to: input.at }); + delete have.gone; + back.push(id); + } } else { placed++; - posts[id] = { topic: topic.id, seen: [seen], ...(input.media?.[id] ? { media: input.media[id] } : {}) }; + posts[id] = { + topic: topic.id, + ...(input.threads?.[id] ? { thread: input.threads[id] } : {}), + seen: [seen], + ...(input.media?.[id] ? { media: input.media[id] } : {}), + }; } }); + if (input.complete) { + const shown = new Set(input.postIds); + for (const [id, m] of Object.entries(posts)) { + if (shown.has(id) || m.gone) continue; + // Only a post THIS page showed, in a read before this one. + if (!m.seen.some((s) => s.trendId === input.ref.trendId && s.read !== input.readId && s.at < input.at)) continue; + m.gone = { at: input.at, read: input.readId, trendId: input.ref.trendId }; + gone.push(id); + } + } await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true }); - return { placed, kept }; + return { placed, kept, gone, back }; }); return { topic, ...counts }; } @@ -433,6 +613,8 @@ export type XTrendingReadRecord = { endedAt: string; probe: boolean; headed: boolean; + // The read was a watch's tick, not a person's ask. + watch?: true; limits: { scrolls: number; posts: number }; scrolls: number; // Why the scrolling stopped (xTrendingRead.ts TrendingReadStop). @@ -482,6 +664,9 @@ export type XTrendingTopicRow = { id: string; title: string; posts: number; + // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it + // is doing as one sentence. + watch?: XTrendingWatch & { sentence: string }; sources: Array<{ trendId: string; url: string; @@ -506,7 +691,16 @@ export type XTrendingPostRow = { media: XTrendingMedia & { thumbnail?: string }; topic: string; reads: Array<{ read: string; trendId: string; at: string }>; - judgement?: XTrendingJudgement; + // Gone from the page: a page that showed it before did not show it at + // `at` (a read that reached the page's end). Never "deleted". + gone?: XTrendingGone; + // What its capture holds: the files beside its record, and what is owed. + capture?: XTrendingCaptureSummary; + // The thread it belongs to: its root post's id (xTrendingThreadKey). + thread: string; + // The judgement in force (xTrendingEffectiveJudgement): its own, or its + // thread's (`from: "thread"`). Absent: undecided. + judgement?: XTrendingJudgement & { from?: "thread" }; }; export type XTrendingListing = { @@ -536,13 +730,15 @@ const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.a // 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> } = {}, + opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post>; now?: number } = {}, ): Promise<XTrendingListing> { + const now = opts.now ?? Date.now(); + const watches = await readXTrendingWatches(channelRoot); const [topics, membership, reads, judgements] = await Promise.all([ readXTrendingTopics(channelRoot), readXTrendingMembership(channelRoot), listXTrendingReadIds(channelRoot), - readXTrendingJudgements(channelRoot), + readXTrendingJudgementsFile(channelRoot), ]); const archived = new Map((opts.posts ?? (await readXTrendingPosts(channelRoot))).map((p) => [p.id, p])); const count = new Map<string, number>(); @@ -554,6 +750,7 @@ export async function listXTrending( if (opts.topic && m.topic !== opts.topic) continue; const post = archived.get(id); if (!post) continue; + const thread = xTrendingThreadOf(post, membership, archived); rows.push({ id, author: post.author, @@ -564,7 +761,12 @@ export async function listXTrending( 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] } : {}), + ...(m.gone ? { gone: m.gone } : {}), + thread, + ...(() => { + const judgement = xTrendingEffectiveJudgement(judgements.posts[id], judgements.threads[thread]); + return judgement ? { judgement } : {}; + })(), }); } const rank = (id: string) => { @@ -583,6 +785,7 @@ export async function listXTrending( id: t.id, title: t.title, posts: count.get(t.id) ?? 0, + ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}), sources: t.sources.map((s) => ({ trendId: s.trendId, url: s.url, @@ -595,8 +798,15 @@ export async function listXTrending( // 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; + const [thumbnail, capture] = await Promise.all([ + firstCapturedThumbnail(channelRoot, row.id), + xTrendingCaptureSummary(channelRoot, row.id), + ]); + return { + ...row, + ...(thumbnail ? { media: { ...row.media, thumbnail } } : {}), + ...(capture ? { capture } : {}), + }; }), ), total: rows.length, diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts @@ -0,0 +1,283 @@ +// A LIBRARY'S WATCHED TOPICS (lane x-trending-2): `trending/watch.json`. +// +// A watch is a per-topic switch: while it is on, the topic's trending page is +// read again every `intervalMinutes` until `until`, by the same single +// `read-x-trending` job a person starts (controller/xTrendingWatch.ts is the +// scan that enqueues it; this module is the state and its ONE writer). +// +// on the switch +// shots also screenshot every new post (default: only their media) +// paused the scan could not start a tick, and why — X's cookie jar is +// older than the limit ("jar"), the X alert is up ("alert"), X is +// cooling down after a rate limit ("cooldown"), there is no +// connected profile ("no-profile"), or the read was refused +// ("refused"). A PAUSE ENDS BY ITSELF at the first scan that finds +// the reason gone: a watch resumes after a Refresh on /cookies. +// EXCEPT "failing" (review 1 S1): three reads in a row that did +// not end "read" (a rate limit, a 403, a page that will not +// load). A watch does not read into failure for two days: it +// stays paused until a PERSON switches it on again. +// ended the watch is over, with a sentence: its end time came, X no +// longer has its page(s), or it was switched off +// +// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS FRESH (the fresh-jar rule, +// jobs/networkGuard.ts): the editor never refreshes the jar by itself, so a +// watch does not cover a night nobody presses Refresh in. +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; +// TYPES ONLY from store.ts (which reads the watches for its listing): this +// module imports nothing of it at run time, so the two do not form a cycle. +import type { XTrendingTopic } from "./store"; + +// store.ts TRENDING_DIRNAME (watch.test.ts holds the two together). +const TRENDING_DIRNAME = "trending"; + +export type XTrendingWatchPauseReason = "jar" | "alert" | "cooldown" | "no-profile" | "refused" | "failing"; +export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[] = ["jar", "alert", "cooldown", "no-profile", "refused", "failing"]; +// This many reads of a watched topic in a row that did not end "read", and +// the watch pauses ("failing") until a person switches it on again. +export const X_TRENDING_WATCH_MAX_FAILURES = 3; + +export type XTrendingWatch = { + on: boolean; + intervalMinutes: number; + // When the watch began and when it ends (ISO). + startedAt: string; + until: string; + shots: boolean; + by: "agent" | "operator"; + // The last tick the scan enqueued: when, its job, and when the next is due. + lastTickAt?: string; + lastJobId?: string; + nextTickAt?: string; + ticks: number; + // Reads of its pages in a row that did not end "read". + failures: number; + // Which of the topic's pages the next tick reads (round-robin). + nextSource: number; + // Pages X answered "gone" for: not read again. + goneSources: string[]; + paused?: { reason: XTrendingWatchPauseReason; since: string; sentence: string }; + ended?: { at: string; reason: "until" | "gone" | "off"; sentence: string }; +}; + +type WatchFile = { version: 1; topics: Record<string, XTrendingWatch> }; + +export function xTrendingWatchPath(channelRoot: string): string { + return path.join(channelRoot, TRENDING_DIRNAME, "watch.json"); +} + +const str = (v: unknown): v is string => typeof v === "string" && v !== ""; +const iso = (v: unknown): v is string => str(v) && Number.isFinite(Date.parse(v)); + +function parseWatch(raw: unknown): XTrendingWatch | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record<string, unknown>; + if (typeof r.on !== "boolean" || !iso(r.startedAt) || !iso(r.until)) return null; + const interval = Number(r.intervalMinutes); + if (!Number.isInteger(interval) || interval < 1) return null; + const paused = r.paused as XTrendingWatch["paused"] | undefined; + const ended = r.ended as XTrendingWatch["ended"] | undefined; + return { + on: r.on, + intervalMinutes: interval, + startedAt: r.startedAt, + until: r.until, + shots: r.shots === true, + by: r.by === "operator" ? "operator" : "agent", + ...(iso(r.lastTickAt) ? { lastTickAt: r.lastTickAt } : {}), + ...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}), + ...(iso(r.nextTickAt) ? { nextTickAt: r.nextTickAt } : {}), + ticks: Number.isInteger(r.ticks) && (r.ticks as number) > 0 ? (r.ticks as number) : 0, + failures: Number.isInteger(r.failures) && (r.failures as number) > 0 ? (r.failures as number) : 0, + nextSource: Number.isInteger(r.nextSource) && (r.nextSource as number) > 0 ? (r.nextSource as number) : 0, + goneSources: Array.isArray(r.goneSources) ? r.goneSources.filter((t): t is string => typeof t === "string" && /^\d+$/.test(t)) : [], + ...(paused && typeof paused === "object" && X_TRENDING_WATCH_PAUSE_REASONS.includes(paused.reason) && iso(paused.since) && str(paused.sentence) + ? { paused: { reason: paused.reason, since: paused.since, sentence: paused.sentence } } + : {}), + ...(ended && typeof ended === "object" && iso(ended.at) && str(ended.sentence) && (ended.reason === "until" || ended.reason === "gone" || ended.reason === "off") + ? { ended: { at: ended.at, reason: ended.reason, sentence: ended.sentence } } + : {}), + }; +} + +// The watches by topic id ({} while there is no file). Ill-shaped entries are dropped. +export async function readXTrendingWatches(channelRoot: string): Promise<Record<string, XTrendingWatch>> { + const read = await readJsonFile(xTrendingWatchPath(channelRoot)); + const topics = read.ok ? (read.value as { topics?: unknown } | null)?.topics : null; + const out: Record<string, XTrendingWatch> = {}; + if (!topics || typeof topics !== "object" || Array.isArray(topics)) return out; + for (const [id, raw] of Object.entries(topics as Record<string, unknown>)) { + const w = parseWatch(raw); + if (w && id) out[id] = w; + } + return out; +} + +// A watch the scan still ticks: switched on and not ended. +export const watchIsLive = (w: XTrendingWatch | undefined): w is XTrendingWatch => !!w && w.on && !w.ended; + +// Every write of watch.json: the file read under its lock, changed, written. +// `change` answers false to write nothing. +export async function mutateXTrendingWatches<T>( + channelRoot: string, + change: (topics: Record<string, XTrendingWatch>) => { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(xTrendingWatchPath(channelRoot), async () => { + const topics = await readXTrendingWatches(channelRoot); + const { write, result } = change(topics); + if (write) await writeJsonAtomic(xTrendingWatchPath(channelRoot), { version: 1, topics } satisfies WatchFile, { mkdir: true }); + return result; + }); +} + +export type SetWatchAsk = { + // The library's topics (store.ts readXTrendingTopics), read by the caller. + topics: ReadonlyArray<XTrendingTopic>; + topic: string; + on: boolean; + intervalMinutes: number; + hours: number; + shots?: boolean; + by: "agent" | "operator"; + maxTopics: number; + now: number; +}; + +export type SetWatchResult = { ok: true; topic: string; watch: XTrendingWatch } | { ok: false; error: string }; + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " "); + +// The switch. ON: the topic must exist and hold at least one trending page, +// and the library may not already watch `maxTopics` others; switching a live +// watch on again changes its interval, end time and shots and keeps its +// history. OFF: the watch ends ("switched off"); a watch that is not on is +// left as it is. +export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): Promise<SetWatchResult> { + const topics = ask.topics; + const topic = topics.find((t) => t.id === ask.topic) ?? topics.find((t) => t.title.toLowerCase() === ask.topic.trim().toLowerCase()); + if (!topic) { + return { ok: false, error: `This library has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"}).` }; + } + const at = new Date(ask.now).toISOString(); + return mutateXTrendingWatches<SetWatchResult>(channelRoot, (watches) => { + const have = watches[topic.id]; + if (!ask.on) { + if (!watchIsLive(have)) { + return { write: false, result: { ok: false, error: `Topic "${topic.title}" is not being watched.` } }; + } + have.on = false; + delete have.paused; + have.ended = { at, reason: "off", sentence: `The watch of "${topic.title}" was switched off.` }; + return { write: true, result: { ok: true, topic: topic.id, watch: have } }; + } + if (topic.sources.length === 0) { + return { write: false, result: { ok: false, error: `Topic "${topic.title}" holds no trending page to watch: read one into it first.` } }; + } + const others = Object.entries(watches).filter(([id, w]) => id !== topic.id && watchIsLive(w)).length; + if (!watchIsLive(have) && others >= ask.maxTopics) { + return { + write: false, + result: { + ok: false, + error: + `This library already watches ${others} topic${others === 1 ? "" : "s"} (at most ${ask.maxTopics}): ` + + `switch one off first, or raise the limit (watch-trending {"settings": {"maxTopics": …}}).`, + }, + }; + } + const until = new Date(ask.now + ask.hours * 3_600_000).toISOString(); + const live = watchIsLive(have) ? have : undefined; + // A watch paused for FAILING is the operator's to start again (review 2 + // N5): an agent switching it "on" would be the watch reading into failure + // with nobody having looked. + if (live?.paused?.reason === "failing" && ask.by !== "operator") { + return { + write: false, + result: { + ok: false, + error: + `The watch of "${topic.title}" is paused because its reads kept failing (${live.paused.sentence}) ` + + `Only the operator starts it again: Watch on the topic's page, or watch-trending with "by": "operator".`, + }, + }; + } + const watch: XTrendingWatch = { + on: true, + intervalMinutes: ask.intervalMinutes, + startedAt: live?.startedAt ?? at, + until, + shots: ask.shots ?? live?.shots ?? false, + by: ask.by, + ...(live?.lastTickAt ? { lastTickAt: live.lastTickAt } : {}), + ...(live?.lastJobId ? { lastJobId: live.lastJobId } : {}), + // A changed interval counts from the last tick; a new watch ticks at the next scan. + ...(live?.lastTickAt ? { nextTickAt: new Date(Date.parse(live.lastTickAt) + ask.intervalMinutes * 60_000).toISOString() } : {}), + ticks: live?.ticks ?? 0, + // Switched on by a person: a watch paused for failing starts again. + failures: 0, + nextSource: live?.nextSource ?? 0, + goneSources: live?.goneSources ?? [], + ...(live?.paused && live.paused.reason !== "failing" ? { paused: live.paused } : {}), + }; + watches[topic.id] = watch; + return { write: true, result: { ok: true, topic: topic.id, watch } }; + }); +} + +// What a watch is doing, in one sentence (the panel, `get trending`, the MCP). +export function describeXTrendingWatch(w: XTrendingWatch, now: number): string { + if (w.ended) return w.ended.sentence; + if (!w.on) return "Not watched."; + const every = `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}`; + if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until someone switches it on again: ${w.paused.sentence}`; + if (w.paused) return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC: ${w.paused.sentence}`; + const next = w.nextTickAt ? Date.parse(w.nextTickAt) : now; + return `Watched ${every}; ${w.ticks} tick${w.ticks === 1 ? "" : "s"} so far, next ${next <= now ? "at the next scan" : `at ${hhmm(next)} UTC`}.`; +} + +// PAUSED WATCHES, AS /review LISTS THEM: topics someone switched a watch on +// for, which the watch's scan cannot tick now — X's cookie +// jar is past its limit, the X alert is up, X is cooling down, there is no +// connected profile. It is here because what ends the pause is a PERSON's +// press (Refresh cookies on /cookies; the editor never refreshes X's jar by +// itself), and until someone makes it the watch reads nothing. +export type PausedWatchRow = { + slug: string; + topic: string; + title: string; + reason: string; + // ISO: when the pause began, and when the watch ends whether or not it resumes. + since: string; + until: string; + sentence: string; +}; + +export function pausedWatchRows( + libraries: ReadonlyArray<{ + slug: string; + topics: ReadonlyArray<{ id: string; title: string }>; + watches: Readonly<Record<string, { on: boolean; until: string; ended?: unknown; paused?: { reason: string; since: string; sentence: string } }>>; + }>, +): PausedWatchRow[] { + const rows: PausedWatchRow[] = []; + for (const lib of libraries) { + for (const [topic, w] of Object.entries(lib.watches)) { + if (!w.on || w.ended || !w.paused) continue; + rows.push({ + slug: lib.slug, + topic, + title: lib.topics.find((t) => t.id === topic)?.title ?? topic, + reason: w.paused.reason, + since: w.paused.since, + until: w.until, + sentence: w.paused.sentence, + }); + } + } + // Stable across renders. + return rows.sort((a, b) => a.slug.localeCompare(b.slug) || a.topic.localeCompare(b.topic)); +} diff --git a/common/publish/xTrendingReportDoor.test.ts b/common/publish/xTrendingReportDoor.test.ts @@ -89,6 +89,29 @@ writeJson(path.join(accountRoot, "config.json"), { }); await writePosts(accountRoot, [post(ACCOUNT, SHARED_ID, "kettle_org", "the account's own copy")]); +// Lane x-trending-2: the library's first post is KEPT and CAPTURED (a note, +// a shot, a media file in the store, its context) and its topic watched. No +// report door may give out any of it either. +const { recordXTrendingRead, readXTrendingTopics } = await import("../lib/xTrending/store"); +const { plantSlice2Library, SLICE2_CAPTURES_DIRNAME, SLICE2_FILE_NAMES, SLICE2_MARK_LIST } = await import("../lib/xTrending/__fixtures__/slice2Library"); +await recordXTrendingRead(libRoot, { + readId: "tr-01JA0000000000000000000000", + at: "2026-11-17T10:00:00.000Z", + ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }, + topic: "Kettles", + postIds: [LIB_ID, SHARED_ID], + added: 2, +}); +await plantSlice2Library(libRoot, { postId: LIB_ID, topicId: (await readXTrendingTopics(libRoot))[0].id }); + +// Nothing lane x-trending-2 leaves in a library is in what a report door wrote. +function assertNoSlice2(files: { rel: string; text: string }[], where: string): void { + for (const f of files) { + for (const mark of SLICE2_MARK_LIST) assert.ok(!f.text.includes(mark), `${where}: ${f.rel} holds ${mark}`); + for (const name of SLICE2_FILE_NAMES) assert.ok(!f.rel.split(path.sep).includes(name), `${where}: wrote ${f.rel}`); + } +} + function filesUnder(dir: string): { rel: string; text: string }[] { const out: { rel: string; text: string }[] = []; const walk = (d: string) => { @@ -209,6 +232,7 @@ test("N8a: behind a host that lets it through, compose still refuses a library's 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`); + assertNoSlice2(filesUnder(OUT), "compose"); }); test("N8a: behind such a host, preparing media refuses a library's post, and no window of a library is planned", async () => { @@ -219,6 +243,11 @@ test("N8a: behind such a host, preparing media refuses a library's post, and no [["not-visible", `${LIB}/${LIB_ID}`, X_TRENDING_NOT_CITABLE(LIB)]], ); assert.deepEqual(Object.keys(index.moments), []); + // The post is CAPTURED now (a shot and a media file under trending/): no + // report media is prepared from it all the same, and nothing of it is written. + assert.ok(!JSON.stringify(index).includes(SLICE2_CAPTURES_DIRNAME), "the media index names a capture"); + for (const mark of SLICE2_MARK_LIST) assert.ok(!JSON.stringify(index).includes(mark), `the media index holds ${mark}`); + assertNoSlice2(filesUnder(OUT), "report media"); // A span cited on a library (a config edited by hand could carry videos). writeJson(path.join(articleDir(paths, "art-lib-span"), "report.json"), { diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -51,6 +51,18 @@ export function fixtureTweetResult(t: FixtureTweet): Record<string, unknown> { type, media_key: `3_${t.id}${i}`, media_url_https: `https://pbs.twimg.com/media/Fixture${t.id.slice(-4)}${i}.jpg`, + // A video or a GIF: two progressive mp4s and a playlist, as X lists them. + ...(type === "photo" + ? {} + : { + video_info: { + variants: [ + { content_type: "application/x-mpegURL", url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/pl/list.m3u8` }, + { content_type: "video/mp4", bitrate: 632000, url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/vid/320x180/low.mp4?tag=12` }, + { content_type: "video/mp4", bitrate: 2176000, url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/vid/1280x720/high.mp4?tag=12` }, + ], + }, + }), })), }, } @@ -83,7 +95,7 @@ export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unkn data: { timeline: { instructions: [ - { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", value: "fixture-cursor" } }] }, + { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: FIXTURE_BOTTOM_CURSOR } }] }, ], }, }, @@ -108,8 +120,20 @@ export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [ { 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`; +// The bottom cursor every fixture timeline answer ends with, and which the +// page's next request for that timeline carries. +export const FIXTURE_BOTTOM_CURSOR = "fixture-cursor"; + +const graphqlUrl = (op: string, n: number, cursor?: string) => + `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=${encodeURIComponent( + JSON.stringify({ rest_id: FIXTURE_TREND_ID, ...(cursor ? { cursor } : {}) }), + )}`; + +// The page asking its timeline for MORE: the request carries the bottom cursor +// of the answer before it. With no post it is how a page's end looks. +export function fixtureContinuation(tweets: FixtureTweet[] = [], n = 9, cursor: string = FIXTURE_BOTTOM_CURSOR): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, cursor), status: 200, body: fixtureTimelineBody(tweets) }; +} export type FixtureResponse = { url: string; status: number; body?: unknown; text?: string }; @@ -124,6 +148,6 @@ export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: // 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) }], [], []], + scrolls: [[fixtureContinuation(FIXTURE_SECOND_PAGE, 4)], [], []], }; } diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -29,6 +29,7 @@ import { readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; +import type { MediaFetch } from "./xTrendingMedia"; export type FakeTrendingResponse = { url: string; status: number; body?: unknown; text?: string }; @@ -47,6 +48,8 @@ type FixtureFile = { fail?: string; cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>; trending?: FakeTrendingPage; + // What X's media CDN answers, by address ({status?, text?}; absent: 404). + media?: Record<string, { status?: number; text?: string }>; }; // The smallest PNG there is (1×1, transparent): the fake page's "screenshot". @@ -127,6 +130,34 @@ function readFixture(file: string): FixtureFile { return JSON.parse(readFileSync(file, "utf8")) as FixtureFile; } +// X'S MEDIA CDN, PLAYED BACK (lane x-trending-2): the stand-in for the fetch a +// library's capture asks its media of (xTrendingMedia.ts MediaFetch). Under +// the e2e test server it is ALWAYS this, fixture or no fixture, so no test +// server ever opens a socket to the CDN: an address the fixture's `media` map +// does not name is answered 404. Null outside the test server. +export function fakeXMediaFetch( + transcriptsDir: string, + env: Readonly<Record<string, string | undefined>> = process.env, +): MediaFetch | null { + if (env.E2E_TEST_ROUTES !== "1") return null; + return async (url) => { + const file = fakeXProfileCookiesFile(transcriptsDir, env); + const answer = file ? readFixture(file).media?.[url] : undefined; + const status = answer?.status ?? (answer ? 200 : 404); + const bytes = Buffer.from(answer?.text ?? ""); + return { + status, + headers: { get: (name: string) => (name.toLowerCase() === "content-length" ? String(bytes.length) : null) }, + body: + status >= 200 && status < 300 + ? (async function* () { + yield new Uint8Array(bytes); + })() + : null, + }; + }; +} + // The fake, or null when the gate above says no. export function fakeXProfileChromium( transcriptsDir: string, diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -20,6 +20,7 @@ import type { XCookieSource } from "./xCookieSource"; import type { PostCaptureState } from "./postCapture"; import type { XAvatarRunSummary } from "./xAvatarCapture"; import type { XContextRunSummary } from "./xPostContext"; +import type { ChromiumLike } from "./playwrightRuntime"; export type PostFetchInput = { // The account's canonical URL as configured on the channel. @@ -235,6 +236,30 @@ export type PostAvailabilityInput = { // archived posts. The login fields are a normal fetch's; `outDir` is the // channel's `posts-media/`, one directory per post id beneath it // (postCapture.ts owns the layout). +// How one post's media download went (X). A failure may still name the files +// it did land (`files`), say the post is merely OWED the rest — not an error +// of the post — and until when (`owed`: "next" = a later capture asks again, +// the job's budget or X's cooldown having stopped this one; "kept" = only once +// the post is marked keep, a file being over the cap), and may stop the whole +// run with a sentence (`stop`: a rate limit). +export type PostMediaDownload = + | { ok: true; files: { name: string; url?: string }[] } + | { + ok: false; + error: string; + needsCookies?: boolean; + files?: { name: string; url?: string }[]; + owed?: "next" | "kept"; + stop?: string; + }; + +export type PostMediaDownloadArgs = { + id: string; + dir: string; + signal: AbortSignal; + onLog?: (line: string) => void; +}; + export type PostCaptureInput = Pick< PostFetchInput, "cookies" | "cookieSource" | "browserCookies" | "signal" | "onLog" | "pagePauseMs" @@ -277,6 +302,18 @@ export type PostCaptureInput = Pick< // capture.json and the avatars the page shows saved; no shot, no media, no // article, no thread shot, no availability observation. Defaults to false. contextOnly?: boolean; + // X: the media half done by the CALLER instead of the fetcher's own + // logged-in download (an X trending library: the media CDN addresses in its + // saved captures, each file kept once — controller/capturePosts.ts). `login` + // is the fetcher's own download of that post, for the caller to fall back + // on when it may. + downloadMedia?: ( + args: PostMediaDownloadArgs, + login: (args: PostMediaDownloadArgs) => Promise<PostMediaDownload>, + ) => Promise<PostMediaDownload>; + // X: the browser the profile is opened with (the e2e suite's fake; absent: + // Playwright's). + chromium?: ChromiumLike; // What the posts archive holds for each id — its text and expanded links — // for the links a capture follows (an X Article's). Ids absent are read // from the page alone. diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -229,6 +229,10 @@ export type PostCaptureRecord = { trimmed?: boolean; mediaState: CaptureMediaState; media: CapturedFile[]; + // The media half is not settled because the post is OWED the rest, not + // because it failed (an X trending library): "next" = a later capture asks + // again; "kept" = only once the post is marked keep. + mediaOwed?: "next" | "kept"; // The X Article the post links to, when one was captured or tried. article?: ArticleCaptureRecord; // The thread shot (X replies, asked for with `thread`), when one was taken. diff --git a/common/social/profileBrowserPid.test.ts b/common/social/profileBrowserPid.test.ts @@ -0,0 +1,114 @@ +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/profileBrowserPid.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs"; +import { hostname, tmpdir } from "node:os"; +import path from "node:path"; +import { killProfileBrowser, profileBrowserPid } from "./profileBrowserPid"; + +const TMP = mkdtempSync(path.join(tmpdir(), "profile-pid-")); +const children: ChildProcess[] = []; +after(() => { + for (const c of children) if (c.pid !== undefined && c.exitCode === null) c.kill("SIGKILL"); + rmSync(TMP, { recursive: true, force: true }); +}); + +function profile(name: string, lock?: string): string { + const dir = path.join(TMP, name); + mkdirSync(dir, { recursive: true }); + if (lock) symlinkSync(lock, path.join(dir, "SingletonLock")); + return dir; +} + +// A process that stands in for a browser: it sleeps, with `arg` on its command line. +// `argv0` is what /proc shows as its name: "chrome" for the stand-in browser. +function sleeper(arg: string, argv0 = "chrome"): Promise<ChildProcess> { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000); console.log('up')", "--", arg], { argv0, stdio: ["ignore", "pipe", "ignore"] }); + children.push(child); + return new Promise((resolve, reject) => { + child.once("error", reject); + child.stdout!.once("data", () => resolve(child)); + }); +} + +const exited = (c: ChildProcess) => new Promise<NodeJS.Signals | null>((resolve) => c.once("exit", (_code, signal) => resolve(signal))); + +const linux = process.platform === "linux"; + +test("the pid comes from the profile's own lock, and only when that process names this exact profile", async () => { + const none = profile("none"); + assert.deepEqual(await profileBrowserPid(none, { platform: "linux" }), { pid: null, why: "the profile has no browser lock (no browser holds it)" }); + const dir = profile("exact", "host-4242"); + const deps = (cmdline: string) => ({ platform: "linux", hostname: "host", cmdline: async () => cmdline }); + assert.deepEqual(await profileBrowserPid(dir, deps(`chrome\0--headless\0--user-data-dir=${dir}\0`)), { pid: 4242 }); + // Another profile whose path merely starts the same: left alone. + const other = await profileBrowserPid(dir, deps(`chrome\0--user-data-dir=${dir}-other\0`)); + assert.equal(other.pid, null); + assert.match(other.pid === null ? other.why : "", /process 4242 does not name this profile on its command line \(a stale lock\): it is left alone/); + // The directory mentioned, but not as the profile argument. + assert.equal((await profileBrowserPid(dir, deps(`vim\0${dir}\0`))).pid, null); + // Review 1: another program that carries the very argument is not a browser... + const notChrome = await profileBrowserPid(dir, deps(`/usr/bin/python3\0--user-data-dir=${dir}\0`)); + assert.match(notChrome.pid === null ? notChrome.why : "", /process 4242 is not a Chromium browser \(python3\): it is left alone/); + // ...a browser's child process (a renderer) is not the browser... + const child = await profileBrowserPid(dir, deps(`/opt/chromium/chrome\0--type=renderer\0--user-data-dir=${dir}\0`)); + assert.match(child.pid === null ? child.why : "", /one of a browser's child processes/); + // ...and a lock written on another machine names a pid of that machine. + const elsewhere = await profileBrowserPid(dir, { platform: "linux", hostname: "another-host", cmdline: async () => `chrome\0--user-data-dir=${dir}\0` }); + assert.match(elsewhere.pid === null ? elsewhere.why : "", /written on another machine/); + // The headless shell, by its full path, is a browser. + assert.deepEqual(await profileBrowserPid(dir, deps(`/opt/pw/chromium_headless_shell-1/chrome-linux/headless_shell\0--user-data-dir=${dir}\0`)), { pid: 4242 }); + // A lock whose process is gone. + const gone = await profileBrowserPid(dir, { platform: "linux", hostname: "host", cmdline: async () => { throw new Error("ENOENT"); } }); + assert.match(gone.pid === null ? gone.why : "", /\(4242\) is gone/); + // A lock that names no usable pid: 0, 1, this process, no number. + for (const lock of ["host-0", "host-1", `host-${process.pid}`, "nonsense"]) { + const d = profile(`bad-${lock}`, lock); + assert.equal((await profileBrowserPid(d, deps(`x\0--user-data-dir=${d}\0`))).pid, null, lock); + } + // Off Linux nothing is looked for. + assert.deepEqual(await profileBrowserPid(dir, { platform: "darwin" }), { pid: null, why: "finding the browser's process is Linux-only" }); +}); + +test("a kill signals the checked pid and nothing else", async () => { + const dir = profile("kill", "host-777"); + const sent: Array<[number, string]> = []; + const kill = (pid: number, signal: NodeJS.Signals) => void sent.push([pid, signal]); + assert.deepEqual(await killProfileBrowser(dir, { platform: "linux", hostname: "host", cmdline: async () => `chrome\0--user-data-dir=${dir}\0`, kill }), { killed: true, pid: 777 }); + assert.deepEqual(sent, [[777, "SIGKILL"]]); + // A stale lock: no signal at all. + const stale = await killProfileBrowser(dir, { platform: "linux", hostname: "host", cmdline: async () => "bash\0", kill }); + assert.equal(stale.killed, false); + assert.equal(sent.length, 1); + // Off Linux: no signal, and why. + assert.deepEqual(await killProfileBrowser(dir, { platform: "win32", kill }), { killed: false, why: "finding the browser's process is Linux-only" }); + assert.equal(sent.length, 1); +}); + +test("for real: a process holding the profile is killed; one that does not name it is not", { skip: !linux }, async () => { + const dir = path.join(TMP, "real"); + mkdirSync(dir, { recursive: true }); + const holder = await sleeper(`--user-data-dir=${dir}`); + const bystander = await sleeper(`--user-data-dir=${dir}-other`); + // The lock names the bystander: nothing is killed. + symlinkSync(`${hostname()}-${bystander.pid}`, path.join(dir, "SingletonLock")); + const no = await killProfileBrowser(dir); + assert.equal(no.killed, false); + assert.equal(bystander.exitCode, null); + // The lock names the holder: it is killed, the bystander is not. + rmSync(path.join(dir, "SingletonLock")); + // A process that names the profile and is not a browser: left alone. + const impostor = await sleeper(`--user-data-dir=${dir}`, "node"); + symlinkSync(`${hostname()}-${impostor.pid}`, path.join(dir, "SingletonLock")); + assert.equal((await killProfileBrowser(dir)).killed, false); + assert.equal(impostor.exitCode, null); + rmSync(path.join(dir, "SingletonLock")); + symlinkSync(`${hostname()}-${holder.pid}`, path.join(dir, "SingletonLock")); + const gone = exited(holder); + assert.deepEqual(await killProfileBrowser(dir), { killed: true, pid: holder.pid }); + assert.equal(await gone, "SIGKILL"); + assert.equal(bystander.exitCode, null); + assert.equal(bystander.signalCode, null); +}); diff --git a/common/social/profileBrowserPid.ts b/common/social/profileBrowserPid.ts @@ -0,0 +1,107 @@ +// THE BROWSER THAT HOLDS A PROFILE, BY PID (lane x-trending-2) — for ending a +// browser that no longer answers. +// +// Playwright gives a persistent context no process handle (only +// `launchServer` has `process()`), and closing a context that has stopped +// answering closes nothing: the browser keeps the profile, and every later +// read, capture, Refresh and Connect fails on Chromium's profile lock until +// somebody kills it by hand. So the pid is read where Chromium itself writes +// it: `<profile>/SingletonLock`, a symlink to `<host>-<pid>`. +// +// A PID IS ONLY EVER KILLED WHEN IT IS THIS PROFILE'S BROWSER, and every one +// of these holds: +// - the lock was written on THIS machine (its host is os.hostname(): a +// profile on a shared disk can carry another machine's pid); +// - the process's command line (`/proc/<pid>/cmdline`) names this exact +// profile directory, `--user-data-dir=<profile>` as one argument; +// - its first argument looks like a Chromium binary (chrome, chromium, +// headless_shell, …); +// - it is the BROWSER process, not one of its children: no `--type=` +// argument (renderers, the GPU process and the rest carry one). +// The check is made once, by killProfileBrowser, immediately before the +// signal — nothing else runs between reading the command line and signalling. +// A stale lock whose pid now belongs to another process, a lock of another +// profile, another program that merely mentions the directory: none is +// signalled. Linux only (it reads /proc); anywhere else, and whenever the +// check does not hold, nothing is killed and the caller is told why — it falls +// back to closing, and says so in the job's log. +// +// `process.kill(pid)` on a checked pid, never a child's `.kill()` and never a +// process group. + +import { readFile, readlink } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +export type ProfileBrowserPidDeps = { + platform?: string; + readlink?: (file: string) => Promise<string>; + // /proc/<pid>/cmdline, raw (arguments separated by NUL). + cmdline?: (pid: number) => Promise<string>; + kill?: (pid: number, signal: NodeJS.Signals) => void; + selfPid?: number; + hostname?: string; +}; + +const CHROMIUM_BINARY = /^(chrome|chromium|chromium-browser|chrome-headless-shell|headless_shell|google-chrome(-[a-z]+)?|brave(-browser)?|msedge|microsoft-edge(-[a-z]+)?)$/i; + +export type ProfileBrowserPid = { pid: number } | { pid: null; why: string }; + +const realCmdline = (pid: number) => readFile(`/proc/${pid}/cmdline`, "utf8"); + +// The pid of the browser holding `profileDir`, checked against its command +// line — or why there is none to name. +export async function profileBrowserPid(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise<ProfileBrowserPid> { + if ((deps.platform ?? process.platform) !== "linux") { + return { pid: null, why: "finding the browser's process is Linux-only" }; + } + const dir = path.resolve(profileDir); + let target: string; + try { + target = await (deps.readlink ?? readlink)(path.join(dir, "SingletonLock")); + } catch { + return { pid: null, why: "the profile has no browser lock (no browser holds it)" }; + } + const m = /^(.*)-(\d{1,10})$/.exec(target); + const pid = m ? Number(m[2]) : NaN; + if (m && m[1] !== (deps.hostname ?? os.hostname())) { + return { pid: null, why: "the profile's lock was written on another machine: its process is not looked for here" }; + } + if (!Number.isInteger(pid) || pid <= 1 || pid === (deps.selfPid ?? process.pid)) { + return { pid: null, why: "the profile's lock names no browser process" }; + } + let cmdline: string; + try { + cmdline = await (deps.cmdline ?? realCmdline)(pid); + } catch { + return { pid: null, why: `the process the profile's lock names (${pid}) is gone` }; + } + const args = cmdline.split("\0"); + // The exact directory, as one argument: never a prefix of another profile's path. + const names = args.some((a) => a.startsWith("--user-data-dir=") && path.resolve(a.slice("--user-data-dir=".length)) === dir); + if (!names) { + return { pid: null, why: `process ${pid} does not name this profile on its command line (a stale lock): it is left alone` }; + } + if (!CHROMIUM_BINARY.test(path.basename(args[0] ?? ""))) { + return { pid: null, why: `process ${pid} is not a Chromium browser (${path.basename(args[0] ?? "") || "no name"}): it is left alone` }; + } + if (args.some((a) => a.startsWith("--type="))) { + return { pid: null, why: `process ${pid} is one of a browser's child processes, not the browser: it is left alone` }; + } + return { pid }; +} + +export type KilledProfileBrowser = { killed: true; pid: number } | { killed: false; why: string }; + +// SIGKILL to the browser holding `profileDir` — only to a pid that passes the +// check above, made here, immediately before the signal. +export async function killProfileBrowser(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise<KilledProfileBrowser> { + const found = await profileBrowserPid(profileDir, deps); + if (found.pid === null) return { killed: false, why: found.why }; + try { + (deps.kill ?? ((pid, signal) => void process.kill(pid, signal)))(found.pid, "SIGKILL"); + } catch (err) { + return { killed: false, why: `process ${found.pid} could not be signalled (${(err as Error).message.split("\n")[0]})` }; + } + return { killed: true, pid: found.pid }; +} diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -62,6 +62,7 @@ import { type OlderPostFetchResult, type PostCaptureInput, type PostCaptureResult, + type PostMediaDownloadArgs, type PostFetchInput, type PostFetchResult, type SocialFetcher, @@ -410,16 +411,23 @@ export async function captureXPostsByIds( } } let login: Promise<{ cookies?: string; cookieFile?: string }> | undefined; + // The fetcher's own media download: one logged-in gallery-dl run per post. + const loginDownload = async ({ id, dir, signal, onLog }: PostMediaDownloadArgs) => { + login ??= galleryDlLoginFor(input); + return downloadXPostMedia({ id, dir, login: await login, signal, onLog }); + }; return captureXPosts(input, { openPage: async () => { - const context = await launchXProfile(paths, { onLog: input.onLog }); + const context = await launchXProfile(paths, { + onLog: input.onLog, + ...(input.chromium ? { chromium: input.chromium } : {}), + }); const page = context.pages()[0] ?? (await context.newPage()); return { page, close: () => context.close() }; }, - downloadMedia: async ({ id, dir, signal, onLog }) => { - login ??= galleryDlLoginFor(input); - return downloadXPostMedia({ id, dir, login: await login, signal, onLog }); - }, + // A caller that does the media half itself (an X trending library) is + // handed the logged-in download to fall back on. + downloadMedia: input.downloadMedia ? (args) => input.downloadMedia!(args, loginDownload) : loginDownload, pauseMs: () => xRequestPauseMs(), pause, articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -415,6 +415,33 @@ test("run: media only, or shots only, does only that half", async () => { assert.deepEqual(r2.outcomes, [{ id: "11", state: "captured", availability: "available", files: 1 }]); }); +// Lane x-trending-2: a media half that is merely OWED, and one that stops the run. +test("run: a post owed the rest of its media is not a failure, keeps the files that landed, and is owed again; a stop ends the run", async () => { + const h = harness({}); + h.deps.downloadMedia = async ({ id, dir }) => { + h.downloads.push(id); + if (id === "4") return { ok: false, owed: "next", error: "X's media CDN answered 429", stop: "X's media CDN answered 429 (rate limit)." }; + await writeFile(path.join(dir, `${id}_1.jpg`), `media of ${id}`); + return { ok: false, owed: "kept", error: `${id}_2.mp4: over the cap: owed until the post is kept`, files: [{ name: `${id}_1.jpg` }] }; + }; + const inp = await input(["1", "2", "3", "4", "5"], { shots: false }); + const res = await captureXPosts(inp, h.deps); + // Three owed posts in a row are not three failures: the run went on to the fourth. + assert.deepEqual(res.outcomes.map((o) => [o.id, o.state, o.files]), [["1", "captured", 1], ["2", "captured", 1], ["3", "captured", 1], ["4", "captured", 0]]); + assert.match(res.stoppedEarly ?? "", /X's media CDN answered 429 \(rate limit\)\. Stopped at 4; the rest are left for a later run\./); + assert.deepEqual(h.downloads, ["1", "2", "3", "4"]); + const record = await readPostCapture(path.join(inp.outDir, "1")); + assert.equal(record?.mediaState, "error"); + assert.equal(record?.mediaOwed, "kept"); + assert.equal((await readPostCapture(path.join(inp.outDir, "4")))?.mediaOwed, "next"); + assert.deepEqual(record?.media.map((m) => m.name), ["1_1.jpg"]); + assert.match(record?.error ?? "", /owed until the post is kept/); + // Owed again by the next run. + const again = harness({}); + await captureXPosts({ ...inp, ids: ["1"] }, again.deps); + assert.deepEqual(again.downloads, ["1"]); +}); + // --- the real download path, over a fake gallery-dl ------------------------- test("media download: gallery-dl's tagged lines and the files it wrote, nothing from the network", async () => { diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -51,6 +51,7 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import type { PageLike } from "./playwrightRuntime"; import type { + PostMediaDownload, PostCaptureInput, PostCaptureOutcome, PostCaptureResult, @@ -348,9 +349,7 @@ export async function shootXPost( return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found }; } -export type MediaDownloadResult = - | { ok: true; files: { name: string; url?: string }[] } - | { ok: false; error: string; needsCookies?: boolean }; +export type MediaDownloadResult = PostMediaDownload; export type XCaptureDeps = { // A page in the logged-in profile. Opened on the first shot, closed at the @@ -511,6 +510,7 @@ export async function captureXPosts( let mediaState: CaptureMediaState = work.media ? "skipped" : (existing?.mediaState ?? "skipped"); let media: CapturedFile[] = work.media ? [] : (existing?.media ?? []); let needsCookies = false; + let mediaOwed: PostCaptureRecord["mediaOwed"] = work.media ? undefined : existing?.mediaOwed; // Only a post that rendered (or was not shot this run) is worth a // download: X has nothing to give for a deleted or walled one. const postIsThere = state === undefined || state === "captured"; @@ -525,9 +525,16 @@ export async function captureXPosts( mediaState = media.length > 0 ? "ok" : "none"; state ??= "captured"; } else { + // Not settled: owed again by the next run. The files that did land + // are named all the same. mediaState = "error"; + for (const f of got.files ?? []) media.push(await describeCapturedFile(dir, f.name, f.url)); error = error ? `${error}; ${got.error}` : got.error; - state ??= "error"; + // A post merely owed the rest of its media (a cap, the job's + // budget) did not fail. + state ??= got.owed ? "captured" : "error"; + mediaOwed = got.owed; + if (got.stop) stop = got.stop; if (got.needsCookies) { needsCookies = true; stop = "gallery-dl could not log in to X for the media."; @@ -574,6 +581,7 @@ export async function captureXPosts( ...(shot ? { shot } : {}), mediaState, media, + ...(mediaOwed && mediaState === "error" ? { mediaOwed } : {}), ...(article ? { article } : {}), ...(thread ? { thread } : {}), ...(threadNone && !thread ? { threadNone } : {}), diff --git a/common/social/xTrendingMedia.test.ts b/common/social/xTrendingMedia.test.ts @@ -0,0 +1,409 @@ +// The library's CDN media downloader over a stand-in fetch: no socket is +// opened (the harness runs with ARCHILYZER_NO_NETWORK=1 besides). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xTrendingMedia.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createLibraryMediaDownloader, libraryMediaPauseMs, type LibraryMediaDeps, type MediaFetch } from "./xTrendingMedia"; +import { readXTrendingMediaIndex } from "../lib/xTrending/mediaStore"; +import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; +import type { TrendingMediaSource } from "./xTrendingParse"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-cdn-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const img = (key: string): TrendingMediaSource => ({ + kind: "image", + url: `https://pbs.twimg.com/media/${key}.jpg`, + fetchUrl: `https://pbs.twimg.com/media/${key}?format=jpg&name=orig`, + ext: "jpg", +}); +const vid = (key: string): TrendingMediaSource => ({ + kind: "video", + url: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, + fetchUrl: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, + ext: "mp4", +}); + +type Answer = { status?: number; body?: string; length?: number; throws?: string; slowBodyMs?: number }; + +function harness(name: string, answers: Record<string, Answer>, over: Partial<LibraryMediaDeps> = {}) { + const root = path.join(TMP, name); + const asked: string[] = []; + const cancelled: string[] = []; + const pauses: number[] = []; + const state = { cooldown: 0, limited: 0 }; + const fetch: MediaFetch = async (url, init) => { + asked.push(url); + assert.equal(init.redirect, "error"); + assert.equal(init.credentials, "omit"); + const a = answers[url]; + if (!a) return { status: 404, headers: { get: () => null }, body: null }; + if (a.throws) throw new Error(a.throws); + const bytes = Buffer.from(a.body ?? ""); + return { + status: a.status ?? 200, + headers: { get: (h) => (h === "content-length" ? String(a.length ?? bytes.length) : null) }, + body: Object.assign( + (async function* () { + // Two chunks, so a cap can fall mid-stream. + yield bytes.subarray(0, Math.ceil(bytes.length / 2)); + if (a.slowBodyMs) await new Promise((r) => setTimeout(r, a.slowBodyMs)); + if (init.signal.aborted) throw new Error("aborted"); + yield bytes.subarray(Math.ceil(bytes.length / 2)); + })(), + { cancel: async () => void cancelled.push(url) }, + ), + }; + }; + const deps: LibraryMediaDeps = { + fetch, + pauseMs: () => 1500, + pause: async (ms) => void pauses.push(ms), + cooldownMs: async () => state.cooldown, + noteRateLimit: async () => { + state.limited++; + return Date.parse("2026-11-18T10:15:00Z"); + }, + now: () => Date.parse("2026-11-18T10:00:00Z"), + ...over, + }; + const dirOf = (id: string) => path.join(root, "trending", "posts-media", id); + const args = (id: string): PostMediaDownloadArgs => ({ id, dir: dirOf(id), signal: new AbortController().signal }); + const noLogin = async (): Promise<PostMediaDownload> => { + throw new Error("the logged-in download must not run"); + }; + return { root, asked, cancelled, pauses, state, deps, dirOf, args, noLogin }; +} + +test("files come from the CDN one after another, 1 to 2 s apart, and each is kept once", async () => { + const h = harness("fetch", { + [img("A").fetchUrl]: { body: "PICTURE-A" }, + [img("B").fetchUrl]: { body: "PICTURE-B" }, + [vid("V").fetchUrl]: { body: "VIDEO-V" }, + // Another address, the same bytes as A. + [img("A2").fetchUrl]: { body: "PICTURE-A" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["701", [img("A"), img("B")]], + ["702", [vid("V"), img("A"), img("A2")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + assert.deepEqual(await download(h.args("701"), h.noLogin), { + ok: true, + files: [ + { name: "701_1.jpg", url: img("A").url }, + { name: "701_2.jpg", url: img("B").url }, + ], + }); + const second = await download(h.args("702"), h.noLogin); + assert.equal(second.ok, true); + // A's address is known: 702_2.jpg is linked, never asked for again. + assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl, vid("V").fetchUrl, img("A2").fetchUrl]); + // A gap before every fetch but the job's first. + assert.deepEqual(h.pauses, [1500, 1500, 1500]); + const a1 = statSync(path.join(h.dirOf("701"), "701_1.jpg")); + assert.equal(statSync(path.join(h.dirOf("702"), "702_2.jpg")).ino, a1.ino); + // Same bytes from another address: fetched, then one file with A. + assert.equal(statSync(path.join(h.dirOf("702"), "702_3.jpg")).ino, a1.ino); + assert.equal(readFileSync(path.join(h.dirOf("702"), "702_1.mp4"), "utf8"), "VIDEO-V"); + assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).blobs).length, 3); + // No partial left behind. + assert.deepEqual(readdirSync(h.dirOf("702")).sort(), ["702_1.mp4", "702_2.jpg", "702_3.jpg"]); + // Asked again: everything is on disk, nothing is fetched. + h.asked.length = 0; + assert.equal((await download(h.args("701"), h.noLogin)).ok, true); + assert.deepEqual(h.asked, []); + const gap = libraryMediaPauseMs(() => 0.5); + assert.ok(gap >= 1000 && gap < 2000); +}); + +test("a 429 stops the job and records the cooldown; a 403 or 404 marks the file and nothing retries", async () => { + const h = harness("refused", { + [img("Gone").fetchUrl]: { status: 404 }, + [img("Forbidden").fetchUrl]: { status: 403 }, + [img("Fine").fetchUrl]: { body: "FINE" }, + [img("Limited").fetchUrl]: { status: 429 }, + [img("Never").fetchUrl]: { body: "NEVER" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["711", [img("Gone"), img("Forbidden"), img("Fine")]], + ["712", [img("Limited"), img("Never")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const first = await download(h.args("711"), h.noLogin); + assert.equal(first.ok, false); + if (first.ok) return; + assert.match(first.error, /711_1\.jpg: the CDN answered 404; 711_2\.jpg: the CDN answered 403/); + assert.deepEqual(first.files, [{ name: "711_3.jpg", url: img("Fine").url }]); + // A refused file is an error of the post, not something merely owed; and it does not stop the run. + assert.equal(first.owed, undefined); + assert.equal(first.stop, undefined); + // Each address asked exactly once. + assert.deepEqual(h.asked, [img("Gone").fetchUrl, img("Forbidden").fetchUrl, img("Fine").fetchUrl]); + + const limited = await download(h.args("712"), h.noLogin); + assert.equal(limited.ok, false); + if (limited.ok) return; + assert.match(limited.stop ?? "", /answered 429 \(rate limit\) for 712_1\.jpg.*Nothing X starts before 10:15 UTC; nothing retries by itself/); + assert.equal(h.state.limited, 1); + // The file after the 429 was never asked for. + assert.equal(h.asked.includes(img("Never").fetchUrl), false); + assert.equal(existsSync(path.join(h.dirOf("712"), "712_2.jpg")), false); +}); + +test("X's cooldown holds the media: nothing is asked while it runs", async () => { + const h = harness("cooling", { [img("A").fetchUrl]: { body: "A" } }); + h.state.cooldown = 9 * 60_000; + const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["721", [img("A")]]]), maxVideoBytes: 100, fallback: "none", deps: h.deps }); + const res = await download(h.args("721"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.match(res.stop ?? "", /no media fetch starts before 10:09 UTC \(9 min from now\)/); + assert.equal(res.owed, "next"); + assert.deepEqual(h.asked, []); +}); + +test("a file over the cap is owed, by its declared size or mid-stream; a kept post has no cap", async () => { + const answers = { + [vid("Declared").fetchUrl]: { body: "x", length: 5000 }, + [vid("Streamed").fetchUrl]: { body: "0123456789ABCDEF", length: 4 }, + [img("Small").fetchUrl]: { body: "ok" }, + }; + const h = harness("cap", answers); + const sources = new Map([["731", [vid("Declared"), vid("Streamed"), img("Small")]]]); + const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: 10, fallback: "none", deps: h.deps }); + const res = await watch(h.args("731"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.equal(res.owed, "kept"); + assert.match(res.error, /731_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept; 731_2\.mp4: it is over the 1 MB cap: owed until the post is kept/); + assert.deepEqual(res.files, [{ name: "731_3.jpg", url: img("Small").url }]); + assert.deepEqual(readdirSync(h.dirOf("731")), ["731_3.jpg"]); + // Found over the cap once: the next capture under the same cap does not ask for them again. + h.asked.length = 0; + const next = await watch(h.args("731"), h.noLogin); + assert.equal(next.ok, false); + assert.deepEqual(h.asked, []); + assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).oversize).length, 2); + // Kept: no cap, so the same files come down. + const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: null, fallback: "login", deps: h.deps }); + const again = await kept(h.args("731"), h.noLogin); + assert.equal(again.ok, true); + assert.equal(readFileSync(path.join(h.dirOf("731"), "731_2.mp4"), "utf8"), "0123456789ABCDEF"); + assert.deepEqual((await readXTrendingMediaIndex(h.root)).oversize, {}); +}); + +test("a job's budget: past it the rest is owed and nothing more is asked", async () => { + const h = harness("budget", { + [img("A").fetchUrl]: { body: "AAAA" }, + [img("B").fetchUrl]: { body: "BBBB" }, + [img("C").fetchUrl]: { body: "CCCC" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([["741", [img("A"), img("B")]], ["742", [img("C"), img("A")]]]), + maxVideoBytes: 100, + fallback: "none", + maxFiles: 2, + deps: h.deps, + }); + assert.equal((await download(h.args("741"), h.noLogin)).ok, true); + const res = await download(h.args("742"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.equal(res.owed, "next"); + assert.equal(res.stop, undefined); + assert.match(res.error, /742_1\.jpg: owed \(this job's media budget of 2 files/); + // What the library already holds is still linked, budget or not. + assert.deepEqual(res.files, [{ name: "742_2.jpg", url: img("A").url }]); + assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl]); +}); + +test("the logged-in download is the fallback for a kept post only, and what it lands is kept once too", async () => { + const h = harness("fallback", { [img("Fine").fetchUrl]: { body: "FINE" } }); + const sources = new Map([["751", [img("Fine")]]]); + const expected = new Map([["751", 2]]); + // A watch: the file the capture names no address for is owed; no login. + const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: 100, fallback: "none", deps: h.deps }); + const owed = await watch(h.args("751"), h.noLogin); + assert.equal(owed.ok, false); + if (owed.ok) return; + assert.equal(owed.owed, "kept"); + assert.match(owed.error, /1 of its 2 media file\(s\) have no CDN address in the saved capture: owed until the post is kept/); + // Kept: the fetcher's own download runs once, and its file joins the store. + let logins = 0; + const { writeFileSync } = await import("node:fs"); + const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: null, fallback: "login", deps: h.deps }); + const res = await kept(h.args("751"), async ({ dir }) => { + logins++; + writeFileSync(path.join(dir, "751_2.mp4"), "VIA-LOGIN"); + return { ok: true, files: [{ name: "751_1.jpg" }, { name: "751_2.mp4", url: "https://video.twimg.com/x/v.mp4" }] }; + }); + assert.equal(logins, 1); + assert.equal(res.ok, true); + const index = await readXTrendingMediaIndex(h.root); + const blobs = Object.values(index.blobs); + assert.equal(blobs.length, 2); + assert.ok(blobs.some((b) => b.urls.includes("https://video.twimg.com/x/v.mp4") && b.posts["751"]?.includes("751_2.mp4"))); +}); + +test("an address off X's media CDN is never asked; a fetch that throws marks the file", async () => { + const h = harness("hosts", { "https://pbs.twimg.com/media/T?format=jpg&name=orig": { throws: "socket hang up" } }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["761", [{ kind: "image", url: "https://example.test/a.jpg", fetchUrl: "https://example.test/a.jpg", ext: "jpg" }, img("T")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const res = await download(h.args("761"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.match(res.error, /761_1\.jpg: not an address on X's media CDN; 761_2\.jpg: the CDN did not answer \(socket hang up\)/); + assert.deepEqual(h.asked, ["https://pbs.twimg.com/media/T?format=jpg&name=orig"]); +}); + +// Review 1 S3. +test("S3: the wait for the headers ends when they arrive — a body slower than it still comes down; an oversize body is cancelled", async () => { + const h = harness( + "timers", + { [img("Slow").fetchUrl]: { body: "SLOW-BUT-WHOLE", slowBodyMs: 80 }, [vid("Big").fetchUrl]: { body: "x", length: 5000 } }, + { timeouts: { headersMs: 20, fileMs: 5_000 } }, + ); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([["771", [img("Slow"), vid("Big")]]]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const res = await download(h.args("771"), h.noLogin); + // The body took four times the headers' limit: it is whole. + assert.equal(readFileSync(path.join(h.dirOf("771"), "771_1.jpg"), "utf8"), "SLOW-BUT-WHOLE"); + assert.equal(res.ok, false); + if (res.ok) return; + assert.equal(res.owed, "kept"); + // The file declared over the cap was not left downloading. + assert.deepEqual(h.cancelled, [vid("Big").fetchUrl]); + // And the file's own limit is still a limit. + const strict = harness("timers-file", { [img("Slow").fetchUrl]: { body: "NEVER-WHOLE", slowBodyMs: 80 } }, { timeouts: { headersMs: 20, fileMs: 30 } }); + const cut = await createLibraryMediaDownloader({ channelRoot: strict.root, sources: new Map([["772", [img("Slow")]]]), maxVideoBytes: 100, fallback: "none", deps: strict.deps })(strict.args("772"), strict.noLogin); + assert.equal(cut.ok, false); + assert.equal(existsSync(path.join(strict.dirOf("772"), "772_1.jpg")), false); + assert.deepEqual(readdirSync(strict.dirOf("772")), []); +}); + +// Review 1 S9. +test("S9: three refusals in a row (a 403, or no answer) and the job asks the CDN no more; the rest is owed to a later capture", async () => { + const answers: Record<string, Answer> = { + [img("R1").fetchUrl]: { status: 403 }, + [img("R2").fetchUrl]: { throws: "socket hang up" }, + [img("R3").fetchUrl]: { status: 403 }, + [img("Never1").fetchUrl]: { body: "N1" }, + [img("Never2").fetchUrl]: { body: "N2" }, + }; + const h = harness("refusing", answers); + const log: string[] = []; + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([["781", [img("R1"), img("R2")]], ["782", [img("R3"), img("Never1")]], ["783", [img("Never2")]]]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) }); + await download(withLog("781"), h.noLogin); + const second = await download(withLog("782"), h.noLogin); + const third = await download(withLog("783"), h.noLogin); + assert.deepEqual(h.asked, [img("R1").fetchUrl, img("R2").fetchUrl, img("R3").fetchUrl]); + assert.equal(second.ok, false); + if (!second.ok) assert.match(second.error, /782_2\.jpg: owed \(the CDN refused 3 files in a row; this job asks it no more\)/); + // A post that only met the halt is merely owed, to the next capture. + assert.deepEqual(third.ok ? null : [third.owed, third.stop], ["next", undefined]); + assert.equal(log.filter((l) => /refused 3 files in a row/.test(l)).length, 1); + + // A 404 between them is not a refusal, and a file that comes down starts the count again. + const mixed = harness("refusing-mixed", { + [img("A").fetchUrl]: { status: 403 }, + [img("B").fetchUrl]: { status: 403 }, + [img("C").fetchUrl]: { body: "FINE" }, + [img("D").fetchUrl]: { status: 403 }, + [img("E").fetchUrl]: { status: 403 }, + [img("G").fetchUrl]: { body: "ALSO FINE" }, + }); + const res = await createLibraryMediaDownloader({ + channelRoot: mixed.root, + sources: new Map([["791", [img("A"), img("B"), img("C"), img("D"), img("E"), img("Gone"), img("G")]]]), + maxVideoBytes: 100, + fallback: "none", + deps: mixed.deps, + })(mixed.args("791"), mixed.noLogin); + assert.equal(mixed.asked.length, 7); + assert.deepEqual((res.ok ? [] : res.files ?? []).map((f) => f.name), ["791_3.jpg", "791_7.jpg"]); +}); + +// Review 1 M4, review 2 N3: one predicate, once per post, before its media. +test("M4/N3: a post still kept has no cap and the logged-in download; one dropped since the job was queued has neither", async () => { + const big = "0123456789ABCDEFGHIJ"; + const h = harness("still-kept", { [vid("K").fetchUrl]: { body: big }, [vid("D").fetchUrl]: { body: big } }); + const kept = new Set(["801", "803"]); + const asked: string[] = []; + const log: string[] = []; + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + // 801 and 802: a video over the library's cap. 803 and 804: media the capture names no address for. + sources: new Map([["801", [vid("K")]], ["802", [vid("D")]]]), + expected: new Map([["801", 1], ["802", 1], ["803", 1], ["804", 1]]), + maxVideoBytes: 10, + fallback: "login", + isKept: async (id) => (asked.push(id), kept.has(id)), + deps: h.deps, + }); + let logins = 0; + const login = async ({ id, dir }: PostMediaDownloadArgs): Promise<PostMediaDownload> => { + logins++; + const { writeFileSync } = await import("node:fs"); + writeFileSync(path.join(dir, `${id}_1.jpg`), "VIA-LOGIN"); + return { ok: true, files: [{ name: `${id}_1.jpg` }] }; + }; + const withLog = (id: string) => ({ ...h.args(id), onLog: (l: string) => void log.push(l) }); + // Kept: the whole video, over the cap or not. + assert.equal((await download(withLog("801"), login)).ok, true); + assert.equal(readFileSync(path.join(h.dirOf("801"), "801_1.mp4"), "utf8"), big); + // Dropped since: the cap applies — the uncapped download is not its any more. + const dropped = await download(withLog("802"), login); + assert.equal(dropped.ok, false); + if (!dropped.ok) { + assert.equal(dropped.owed, "kept"); + assert.match(dropped.error, /802_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept/); + } + assert.deepEqual(readdirSync(h.dirOf("802")), []); + // Kept, nothing on the CDN: the logged-in download. + assert.equal((await download(withLog("803"), login)).ok, true); + assert.equal(logins, 1); + // Dropped since, nothing on the CDN: no login for it. + const noLogin = await download(withLog("804"), login); + assert.equal(logins, 1); + assert.equal(noLogin.ok, false); + if (!noLogin.ok) assert.equal(noLogin.owed, "kept"); + // Asked once per post, before its media. + assert.deepEqual(asked, ["801", "802", "803", "804"]); + assert.equal(log.filter((l) => /no longer marked keep: its media is fetched as any post's/.test(l)).length, 2); +}); diff --git a/common/social/xTrendingMedia.ts b/common/social/xTrendingMedia.ts @@ -0,0 +1,387 @@ +// A LIBRARY POST'S MEDIA, FROM X'S MEDIA CDN (lane x-trending-2) — the media +// half of `capture-posts` for an X trending library (controller/ +// capturePosts.ts hands it to the X fetcher as `downloadMedia`). +// +// An ordinary X capture runs one LOGGED-IN gallery-dl per post. A library +// already holds the answer that listed the post — the saved capture of the +// read that showed it — and that answer names where the CDN serves each +// file (xTrendingParse.ts mediaSourcesOf). So the files are asked of the CDN +// directly: no login, no page, no request to X's API. +// +// IT RIDES THE CAPTURE JOB, on X's queue (`platform:twitter`): one job at a +// time with every read and capture, X's gap between jobs, the X alert and the +// fresh-jar rule at the job's start. Inside the job: +// - X's cooldown is asked before every post: a 429 anywhere on X (a read's, +// a capture's) holds the media too; +// - one file after another, 1 to 2 s apart (the gap an article's inline +// images use), never two at once; +// - a job fetches at most `maxFiles` files or `maxBytes` (40, 200 MB): the +// rest is OWED — its posts' media is not settled, and the next capture of +// them asks again; +// - a file over `maxVideoBytes` is not kept and is owed (a watch: 100 MB by +// default; a kept post has no cap); +// - a 429 from the CDN STOPS THE JOB and records the 15-minute cooldown; a +// 403, a 404 or any other answer marks that file and moves on. NOTHING IS +// RETRIED; +// - THREE REFUSALS IN A ROW (a 403, or no answer at all) and the job asks +// the CDN for nothing more: a CDN that has turned this client away is not +// asked forty times. The rest is owed to a later capture. +// +// A FILE THE LIBRARY ALREADY HOLDS IS NOT FETCHED: one whose address the media +// index knows is linked from the store (lib/xTrending/mediaStore.ts), and one +// already in the post's directory is kept. Every file fetched is taken into +// the store, so the same bytes under two posts are one file. +// +// THE LOGGED-IN FALLBACK (`fallback: "login"`, a post marked keep) runs the +// fetcher's own gallery-dl download for a post the CDN could not serve whole — +// no address in the capture, or a file refused — and takes what it lands into +// the store too. A watch never falls back. +// +// Only X's two media hosts are ever asked (xTrendingParse.ts xMediaCdnUrl), a +// redirect is refused, and no cookie or header of the session is sent. + +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect. +import "../lib/noNetwork.mjs"; +import { createWriteStream } from "node:fs"; +import { mkdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { once } from "node:events"; +import { + adoptXTrendingMedia, + noteXTrendingOversize, + linkXTrendingMedia, + readXTrendingMediaIndex, + xTrendingBlobByUrl, +} from "../lib/xTrending/mediaStore"; +import { xRateLimitHoldSentence } from "../lib/xTrending/config"; +import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; +import { listCapturedMediaFiles } from "./postCapture"; +import { xMediaCdnUrl, type TrendingMediaSource } from "./xTrendingParse"; + +export const LIBRARY_MEDIA_MAX_FILES = 40; +export const LIBRARY_MEDIA_MAX_BYTES = 200 * 1024 * 1024; +// No file is ever kept past this, cap or no cap. +export const LIBRARY_MEDIA_HARD_MAX_BYTES = 2 * 1024 * 1024 * 1024; +export const LIBRARY_MEDIA_HEADERS_TIMEOUT_MS = 60_000; +export const LIBRARY_MEDIA_FILE_TIMEOUT_MS = 10 * 60_000; + +// The gap between two files: 1 to 2 s. +export function libraryMediaPauseMs(rand: () => number = Math.random): number { + return 1000 + Math.floor(rand() * 1000); +} + +// The slice of `fetch` this needs (the global one in production; a stand-in +// that opens no socket in tests and under the e2e test server). +export type MediaFetch = ( + url: string, + init: { signal: AbortSignal; redirect: "error"; credentials: "omit" }, +) => Promise<{ + status: number; + headers: { get: (name: string) => string | null }; + // `cancel`, when the body has one (a web stream does), ends a download + // nobody is going to read. + body: (AsyncIterable<Uint8Array> & { cancel?: () => Promise<void> | void }) | null; +}>; + +export type LibraryMediaDeps = { + fetch: MediaFetch; + pauseMs: () => number; + pause: (ms: number, signal: AbortSignal) => Promise<void>; + // X's cooldown: how long is left of it (ms), and a rate limit recorded + // (answers when it ends, ms since the epoch). + cooldownMs: () => Promise<number>; + noteRateLimit: () => Promise<number>; + now?: () => number; + // For tests: the wait for an answer's headers, and for a whole file. + timeouts?: { headersMs?: number; fileMs?: number }; +}; + +export type LibraryMediaOptions = { + // The library's channel directory (channels/<lib>). + channelRoot: string; + // Post id → where the CDN serves its media, from the saved captures. + sources: ReadonlyMap<string, ReadonlyArray<TrendingMediaSource>>; + // Post id → how many media files the post carries (the read's count): a post + // whose capture names fewer addresses than that is owed the rest. + expected?: ReadonlyMap<string, number>; + // A file over this is owed, not kept. null: no cap (a kept post). + maxVideoBytes: number | null; + fallback: "login" | "none"; + // IS THIS POST STILL MARKED KEEP? — ONE predicate, asked once per post, + // before any of its media (review 1 M4, review 2 N3). A capture of kept + // posts is queued when they are kept and may start minutes later; a post + // dropped meanwhile gets NEITHER of the things keeping buys: its media is + // fetched under `maxVideoBytes` like any post's (no uncapped download), and + // no logged-in download is run for it. A post still kept has no per-file + // cap and the fallback `fallback` says. Absent: every post is fetched as + // `maxVideoBytes` and `fallback` say. + isKept?: (id: string) => Promise<boolean>; + maxFiles?: number; + maxBytes?: number; + deps: LibraryMediaDeps; +}; + +const mb = (bytes: number) => `${Math.max(1, Math.round(bytes / (1024 * 1024)))} MB`; +const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0]; + +const overCapWhy = (bytes: number, cap: number) => + `it is ${bytes > cap + 1 ? `${mb(bytes)}, ` : ""}over the ${mb(cap)} cap: owed until the post is kept`; + +// `refused`: the CDN said 403, or did not answer at all — what a CDN that has +// turned this client away looks like. +type Fetched = { ok: true; bytes: number } | { ok: false; why: string; oversize?: number; rateLimited?: boolean; refused?: boolean }; + +// A job stops asking the CDN after this many refusals in a row (review 1 S9). +export const LIBRARY_MEDIA_MAX_REFUSALS = 3; + +// One file, streamed to `<name>.part` and renamed when whole. +async function fetchOne(o: { + source: TrendingMediaSource; + file: string; + cap: number; + capIsHard: boolean; + fetch: MediaFetch; + signal: AbortSignal; + headersMs: number; + fileMs: number; +}): Promise<Fetched> { + const part = `${o.file}.part`; + const over = (bytes: number): Fetched => + o.capIsHard + ? { ok: false, why: `it is larger than ${mb(o.cap)}, more than is ever kept` } + : { ok: false, oversize: bytes > 0 ? bytes : o.cap + 1, why: overCapWhy(bytes, o.cap) }; + const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(o.fileMs)]); + // THE WAIT FOR THE HEADERS IS ITS OWN TIMER, CLEARED WHEN THEY ARRIVE + // (review 1 S3): the signal handed to fetch also aborts the body, so a timer + // left running there would cut every download at the headers' limit and the + // file's own limit would never be reached. + const headers = new AbortController(); + const headersTimer = setTimeout(() => headers.abort(new Error("no answer in time")), o.headersMs); + let res: Awaited<ReturnType<MediaFetch>>; + try { + res = await o.fetch(o.source.fetchUrl, { + signal: AbortSignal.any([deadline, headers.signal]), + redirect: "error", + credentials: "omit", + }); + } catch (err) { + return { ok: false, refused: !o.signal.aborted, why: `the CDN did not answer (${firstLine(err)})` }; + } finally { + clearTimeout(headersTimer); + } + // A body nobody will read is ended, not left to download. + const drop = async () => { + try { + await res.body?.cancel?.(); + } catch { + /* already ended */ + } + }; + if (res.status === 429) { + await drop(); + return { ok: false, rateLimited: true, why: "the CDN answered 429 (rate limit)" }; + } + if (res.status < 200 || res.status >= 300 || !res.body) { + await drop(); + return { ok: false, refused: res.status === 403, why: `the CDN answered ${res.status}` }; + } + const declared = Number(res.headers.get("content-length") ?? ""); + if (Number.isFinite(declared) && declared > o.cap) { + await drop(); + return over(declared); + } + await rm(part, { force: true }); + const out = createWriteStream(part); + let bytes = 0; + let tooBig = false; + try { + for await (const chunk of res.body) { + if (deadline.aborted) throw new Error(o.signal.aborted ? "cancelled" : "the file took too long"); + bytes += chunk.byteLength; + if (bytes > o.cap) { + tooBig = true; + break; + } + if (!out.write(chunk)) await once(out, "drain"); + } + } catch (err) { + out.destroy(); + await rm(part, { force: true }); + return { ok: false, refused: !o.signal.aborted, why: `the download broke off (${firstLine(err)})` }; + } + await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); + if (tooBig) { + await drop(); + await rm(part, { force: true }); + return over(0); + } + if (bytes === 0) { + await rm(part, { force: true }); + return { ok: false, why: "the CDN sent an empty file" }; + } + await rename(part, o.file); + return { ok: true, bytes }; +} + +// The media half of a library's capture: `(args, login) => result`, one call +// per post, sharing one job's budget. +export function createLibraryMediaDownloader( + o: LibraryMediaOptions, +): (args: PostMediaDownloadArgs, login: (args: PostMediaDownloadArgs) => Promise<PostMediaDownload>) => Promise<PostMediaDownload> { + const { deps } = o; + const now = deps.now ?? Date.now; + const maxFiles = o.maxFiles ?? LIBRARY_MEDIA_MAX_FILES; + const maxBytes = o.maxBytes ?? LIBRARY_MEDIA_MAX_BYTES; + const capFor = (maxVideoBytes: number | null) => ({ + cap: Math.min(maxVideoBytes ?? LIBRARY_MEDIA_HARD_MAX_BYTES, LIBRARY_MEDIA_HARD_MAX_BYTES), + capIsHard: maxVideoBytes === null || maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES, + }); + const budget = { files: 0, bytes: 0 }; + let saidSpent = false; + // Refusals in a row, across the job's posts; and whether the job has + // stopped asking the CDN for it. + let refusals = 0; + let halted = false; + const headersMs = deps.timeouts?.headersMs ?? LIBRARY_MEDIA_HEADERS_TIMEOUT_MS; + const fileMs = deps.timeouts?.fileMs ?? LIBRARY_MEDIA_FILE_TIMEOUT_MS; + + return async (args, login) => { + const { id, dir, signal } = args; + const log = args.onLog ?? (() => {}); + // X cooling down after a rate limit holds the media too. + const cooling = await deps.cooldownMs().catch(() => 0); + if (cooling > 0) { + const why = xRateLimitHoldSentence("media fetch", cooling, now()); + return { ok: false, owed: "next", error: why, stop: why }; + } + // Still kept? Asked now, once, before anything of this post is fetched. + const kept = o.isKept ? await o.isKept(id).catch(() => false) : null; + if (kept === false) log(`${id}: no longer marked keep: its media is fetched as any post's (the per-file cap applies, no logged-in download).`); + const { cap, capIsHard } = capFor(kept === true ? null : o.maxVideoBytes); + const mayLogin = o.fallback === "login" && kept !== false; + const sources = o.sources.get(id) ?? []; + const expected = o.expected?.get(id) ?? sources.length; + const files: { name: string; url?: string }[] = []; + const problems: string[] = []; + // Owed to a later capture (the budget, the cooldown), or until the post + // is kept (a file over the cap, a file the capture names no address for). + let owedNext = false; + let owedKept = false; + let failed = false; + let stop: string | undefined; + await mkdir(dir, { recursive: true }); + // Taken into the store; a file the store cannot share stays where it is. + const adopt = async (name: string, url?: string) => { + const got = await adoptXTrendingMedia(o.channelRoot, { postId: id, name, ...(url ? { url } : {}), now }); + if (got.deduped) log(`${id}: ${name} is a file the library already holds (kept once).`); + }; + + for (const [i, source] of sources.entries()) { + if (signal.aborted) break; + const name = `${id}_${i + 1}.${source.ext}`; + const file = path.join(dir, name); + if (!xMediaCdnUrl(source.fetchUrl)) { + problems.push(`${name}: not an address on X's media CDN`); + failed = true; + continue; + } + if ((await stat(file).catch(() => null))?.isFile()) { + await adopt(name, source.url); + files.push({ name, url: source.url }); + continue; + } + // An address the library has seen: linked from the store, nothing asked. + const index = await readXTrendingMediaIndex(o.channelRoot); + const known = xTrendingBlobByUrl(index, source.url); + if (known && (await linkXTrendingMedia(o.channelRoot, { postId: id, name, sha256: known, url: source.url }))) { + log(`${id}: ${name} is already in the library (same address): linked, not fetched.`); + files.push({ name, url: source.url }); + continue; + } + // Found over the cap before: not asked for again while the cap stands. + const big = index.oversize[source.url]; + if (!capIsHard && big && big.bytes > cap) { + owedKept = true; + problems.push(`${name}: ${overCapWhy(big.bytes, cap)}`); + continue; + } + // The CDN has refused this job three times running: it is not asked again. + if (halted) { + owedNext = true; + problems.push(`${name}: owed (the CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row; this job asks it no more)`); + continue; + } + if (budget.files >= maxFiles || budget.bytes >= maxBytes) { + owedNext = true; + problems.push(`${name}: owed (this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used)`); + if (!saidSpent) { + saidSpent = true; + log(`This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`); + } + continue; + } + if (budget.files > 0) await deps.pause(deps.pauseMs(), signal); + if (signal.aborted) break; + const got = await fetchOne({ source, file, cap, capIsHard, fetch: deps.fetch, signal, headersMs, fileMs }); + budget.files++; + refusals = !got.ok && got.refused ? refusals + 1 : 0; + if (refusals >= LIBRARY_MEDIA_MAX_REFUSALS && !halted) { + halted = true; + log( + `X's media CDN refused ${LIBRARY_MEDIA_MAX_REFUSALS} files in a row (a 403, or no answer): this job asks it for no more. ` + + "What is left is owed to a later capture; nothing retries by itself.", + ); + } + if (got.ok) { + budget.bytes += got.bytes; + await adopt(name, source.url); + files.push({ name, url: source.url }); + continue; + } + if (got.rateLimited) { + const until = await deps.noteRateLimit().catch(() => now() + 15 * 60_000); + stop = + `X's media CDN answered 429 (rate limit) for ${name}: the capture stopped at once and asked nothing more. ` + + `Nothing X starts before ${new Date(until).toISOString().slice(11, 16)} UTC; nothing retries by itself.`; + problems.push(`${name}: ${got.why}`); + owedNext = true; + break; + } + problems.push(`${name}: ${got.why}`); + if (got.oversize) { + owedKept = true; + await noteXTrendingOversize(o.channelRoot, { url: source.url, bytes: got.oversize, now }); + } else failed = true; + } + if (signal.aborted && !stop) { + return { ok: false, owed: "next", error: "cancelled", files }; + } + if (sources.length < expected && !stop) { + problems.push( + `${expected - sources.length} of its ${expected} media file(s) have no CDN address in the saved capture` + + (mayLogin ? "" : ": owed until the post is kept"), + ); + if (mayLogin) failed = true; + else owedKept = true; + } + // A kept post the CDN could not serve whole: the fetcher's own logged-in + // download, once, and what it lands is taken into the store. + if (failed && !stop && mayLogin) { + log(`${id}: ${problems.join("; ")} — falling back to the logged-in download.`); + const viaLogin = await login(args); + for (const name of await listCapturedMediaFiles(dir)) { + const url = viaLogin.ok ? viaLogin.files.find((f) => f.name === name)?.url : undefined; + await adopt(name, url ?? files.find((f) => f.name === name)?.url); + } + return viaLogin; + } + if (problems.length === 0) return { ok: true, files }; + return { + ok: false, + error: problems.join("; "), + files, + ...(failed ? {} : owedNext ? { owed: "next" as const } : owedKept ? { owed: "kept" as const } : {}), + ...(stop ? { stop } : {}), + }; + }; +} diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -114,3 +114,106 @@ test("an answer that failed, or whose body was not kept, yields nothing", () => assert.equal(parseTrendingCapture([line({})], "t").posts.length, 3); assert.equal(parseTrendingCapture([line({ body: { data: {} } })], "t").posts.length, 0); }); + +// Lane x-trending-2: where the CDN serves a post's media, read from the answer. +test("media sources: a picture at its original size, a video's highest-bitrate mp4, X's two hosts only", async () => { + const { mediaSourcesOf, mediaSourcesInCapture, xMediaCdnUrl } = await import("./xTrendingParse"); + const { fixtureTweetResult } = await import("./__fixtures__/xTrendingCapture"); + const { collectTimelineTweets } = await import("./xTrendingParse"); + const raw = (t: Parameters<typeof fixtureTweetResult>[0]) => collectTimelineTweets({ result: fixtureTweetResult(t) })[0]; + assert.deepEqual(mediaSourcesOf(raw({ id: "1900000000000002001", handle: "a", text: "t", media: ["photo", "video", "animated_gif"] })), [ + { + kind: "image", + url: "https://pbs.twimg.com/media/Fixture20010.jpg", + fetchUrl: "https://pbs.twimg.com/media/Fixture20010?format=jpg&name=orig", + ext: "jpg", + }, + { + kind: "video", + url: "https://video.twimg.com/ext_tw_video/19000000000000020011/vid/1280x720/high.mp4", + fetchUrl: "https://video.twimg.com/ext_tw_video/19000000000000020011/vid/1280x720/high.mp4", + ext: "mp4", + bitrate: 2176000, + }, + { + kind: "gif", + url: "https://video.twimg.com/ext_tw_video/19000000000000020012/vid/1280x720/high.mp4", + fetchUrl: "https://video.twimg.com/ext_tw_video/19000000000000020012/vid/1280x720/high.mp4", + ext: "mp4", + bitrate: 2176000, + }, + ]); + assert.deepEqual(mediaSourcesOf(raw({ id: "1900000000000002002", handle: "a", text: "no media" })), []); + // An address on another host, or not https, is no media source. + const elsewhere = { + id_str: "1", + full_text: "t", + extended_entities: { + media: [ + { type: "photo", media_url_https: "https://pbs.twimg.com.example.test/media/x.jpg" }, + { type: "photo", media_url_https: "http://pbs.twimg.com/media/x.jpg" }, + { type: "photo", media_url_https: "https://user:pw@pbs.twimg.com/media/x.jpg" }, + { type: "video", video_info: { variants: [{ content_type: "video/mp4", bitrate: 1, url: "https://example.test/v.mp4" }] } }, + { type: "video", video_info: { variants: [{ content_type: "application/x-mpegURL", url: "https://video.twimg.com/x/pl/list.m3u8" }] } }, + { type: "constructor", media_url_https: "https://pbs.twimg.com/media/y.jpg" }, + ], + }, + }; + assert.deepEqual(mediaSourcesOf(elsewhere as never), []); + assert.equal(xMediaCdnUrl("https://video.twimg.com/a.mp4")?.hostname, "video.twimg.com"); + assert.equal(xMediaCdnUrl("https://pbs.twimg.com:8443/a.jpg"), null); + assert.equal(xMediaCdnUrl(42), null); + // A capture's sources by post id: ignored operations and failed answers give none. + const body = { data: { list: [fixtureTweetResult({ id: "1900000000000002003", handle: "a", text: "t", media: ["photo"] })] } }; + const line = (op: string, status: number) => ({ n: 1, at: "x", op, status, url: "u", bytes: 1, body }); + assert.deepEqual([...mediaSourcesInCapture([line("ExampleTrendTimeline", 200)]).keys()], ["1900000000000002003"]); + assert.equal(mediaSourcesInCapture([line("HomeTimeline", 200), line("ExampleTrendTimeline", 500)]).size, 0); +}); + +// Review 1 S2, review 2 N4. +test("S2/N4: a capture shows the page's end only when the bottom-cursor continuation brought nothing new and no answer failed", async () => { + const { parseTrendingCapture, requestCursorOf, timelineShapeOf } = await import("./xTrendingParse"); + const { fixtureTimelineBody, FIXTURE_BOTTOM_CURSOR } = await import("./__fixtures__/xTrendingCapture"); + type Line = import("./xTrendingParse").TrendingCaptureLine; + const t = (id: string) => ({ id, handle: "a", text: `post ${id}` }); + let n = 0; + const url = (op: string, cursor?: string) => `https://x.com/i/api/graphql/q/${op}?variables=${encodeURIComponent(JSON.stringify({ rest_id: "1", ...(cursor ? { cursor } : {}) }))}`; + const line = (op: string, status: number, body?: unknown, cursor?: string): Line => ({ n: ++n, at: "x", op, status, url: url(op, cursor), bytes: 1, ...(body === undefined ? {} : { body }) }); + // The first page (no cursor), and a continuation from the bottom. + const first = (ids: string[]) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t))); + const more = (ids: string[], cursor: string = FIXTURE_BOTTOM_CURSOR) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t)), cursor); + const end = (lines: Line[]) => parseTrendingCapture(lines, "lib").pageEnd; + assert.equal(requestCursorOf(url("Op", "abc")), "abc"); + assert.equal(requestCursorOf(url("Op")), undefined); + assert.equal(requestCursorOf("not a url"), undefined); + assert.deepEqual(timelineShapeOf(fixtureTimelineBody([])), { instructions: true, bottom: FIXTURE_BOTTOM_CURSOR }); + assert.deepEqual(timelineShapeOf({ data: {} }), { instructions: false }); + + // Posts, then the continuation from the bottom with none: the end. + assert.equal(end([first(["1", "2"]), more([])]), true); + // ...or with only posts already seen. + assert.equal(end([first(["1", "2"]), more(["2"])]), true); + // The continuation still brought a new post: nothing says there was no more. + assert.equal(end([first(["1", "2"]), more(["3"])]), false); + assert.equal(end([first(["1", "2"])]), false); + // N4: an answer with nothing new that is NOT the bottom continuation says nothing about the bottom — + // a refresh from the top (no cursor), or another cursor. + assert.equal(end([first(["1", "2"]), first(["1", "2"])]), false); + assert.equal(end([first(["1", "2"]), first([])]), false); + assert.equal(end([first(["1", "2"]), more([], "some-top-cursor")]), false); + // The answer before it named no bottom cursor: the capture cannot tell. + const noCursor = line("ExampleTrendTimeline", 200, { data: { timeline: { instructions: [{ type: "TimelineAddEntries", entries: [{ entryId: "tweet-1", content: { itemContent: { tweet_results: { result: { __typename: "Tweet", rest_id: "1", legacy: { id_str: "1", full_text: "x" } } } } } }] }] } } }); + assert.equal(end([noCursor, more([])]), false); + // An answer that failed, or whose body was not kept: the capture cannot tell. + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 500), more([])]), false); + assert.equal(end([first(["1"]), { ...more([]), body: undefined, skipped: "too-large" as const }]), false); + assert.equal(end([first(["1"]), more([]), line("ExampleTrendPage", 429)]), false); + // N4: a 200 that carries GraphQL errors, or no timeline instructions, is a failed answer. + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 200, { ...fixtureTimelineBody([]), errors: [{ message: "Timeout: Unspecified" }] }, FIXTURE_BOTTOM_CURSOR)]), false); + assert.equal(end([first(["1"]), line("ExampleTrendTimeline", 200, { data: {} }, FIXTURE_BOTTOM_CURSOR)]), false); + assert.equal(end([first(["1"]), more([]), line("ExampleTrendPage", 200, { data: {}, errors: [{ message: "x" }] })]), false); + // Another surface's failure is not the page's. + assert.equal(end([first(["1"]), more([]), line("HomeTimeline", 500)]), true); + // No post at all: no page to have an end. + assert.equal(end([line("ExampleTrendPage", 200, { data: {} })]), false); +}); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -143,6 +143,141 @@ export function mediaSummaryOf(raw: XTweetRaw): TrendingMediaSummary | undefined return { count: media.length, kinds: [...kinds].sort() }; } +// ONE MEDIA FILE OF A POST, AS THE ANSWER NAMES IT (lane x-trending-2): where +// X's media CDN serves it. Nothing is fetched here; a capture job fetches +// `fetchUrl` later, with no login (lib/xTrending/mediaStore.ts keeps it once). +// +// url the address as the answer gives it: the file's identity, what +// the library's media index remembers it by +// fetchUrl what is asked of the CDN: a picture at its original size +// (`?format=<ext>&name=orig`), a video's highest-bitrate +// progressive mp4 +// +// ONLY X's two media hosts, over https, are ever named: an address anywhere +// else in an answer is not a media source (a capture is other people's data, +// and nothing in it may point a fetch at another host). +export type TrendingMediaSource = { + kind: TrendingMediaKind; + url: string; + fetchUrl: string; + ext: string; + bitrate?: number; +}; + +export const X_MEDIA_CDN_HOSTS: readonly string[] = ["pbs.twimg.com", "video.twimg.com"]; + +// An https address on one of X's media hosts, or null. +export function xMediaCdnUrl(v: unknown): URL | null { + if (typeof v !== "string") return null; + let u: URL; + try { + u = new URL(v); + } catch { + return null; + } + if (u.protocol !== "https:" || u.username || u.password || u.port) return null; + return X_MEDIA_CDN_HOSTS.includes(u.hostname) ? u : null; +} + +const IMAGE_EXT = /\.(jpe?g|png|webp)$/i; + +// A post's media files, in the order the post carries them. A file the answer +// names no usable address for (a video with no progressive mp4, an address on +// another host) is left out: the count in mediaSummaryOf still says it exists. +export function mediaSourcesOf(raw: XTweetRaw): TrendingMediaSource[] { + const media = obj(raw.extended_entities)?.media ?? obj(raw.entities)?.media; + if (!Array.isArray(media)) return []; + const out: TrendingMediaSource[] = []; + for (const item of media) { + const m = obj(item); + if (!m) continue; + const type = String(m.type ?? ""); + if (!Object.hasOwn(MEDIA_KIND, type)) continue; + const kind = MEDIA_KIND[type]; + if (kind === "image") { + const u = xMediaCdnUrl(m.media_url_https); + const ext = u ? IMAGE_EXT.exec(u.pathname)?.[1].toLowerCase() : undefined; + if (!u || !ext || u.hostname !== "pbs.twimg.com") continue; + const base = `${u.origin}${u.pathname.replace(IMAGE_EXT, "")}`; + out.push({ kind, url: `${u.origin}${u.pathname}`, fetchUrl: `${base}?format=${ext === "jpeg" ? "jpg" : ext}&name=orig`, ext: ext === "jpeg" ? "jpg" : ext }); + continue; + } + // A video or an animated GIF: the progressive mp4 with the highest bitrate. + const variants = obj(m.video_info)?.variants; + let best: { u: URL; bitrate: number } | undefined; + for (const v of Array.isArray(variants) ? variants : []) { + const variant = obj(v); + if (!variant || variant.content_type !== "video/mp4") continue; + const u = xMediaCdnUrl(variant.url); + if (!u || u.hostname !== "video.twimg.com" || !/\.mp4$/i.test(u.pathname)) continue; + const bitrate = typeof variant.bitrate === "number" && Number.isFinite(variant.bitrate) ? variant.bitrate : 0; + if (!best || bitrate > best.bitrate) best = { u, bitrate }; + } + if (!best) continue; + const url = `${best.u.origin}${best.u.pathname}`; + out.push({ kind, url, fetchUrl: url, ext: "mp4", ...(best.bitrate ? { bitrate: best.bitrate } : {}) }); + } + return out; +} + +// Every post's media sources in a saved capture, by post id (the first answer +// that names a post's media wins). For the capture job: it reads the reads +// that showed the posts it was asked for. +export function mediaSourcesInCapture(lines: ReadonlyArray<TrendingCaptureLine>): Map<string, TrendingMediaSource[]> { + const out = new Map<string, TrendingMediaSource[]>(); + for (const line of lines) { + if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue; + if (line.status < 200 || line.status >= 300) continue; + for (const raw of collectTimelineTweets(line.body)) { + const id = xIdOf(raw); + if (!id || out.has(id)) continue; + const sources = mediaSourcesOf(raw); + if (sources.length > 0) out.set(id, sources); + } + } + return out; +} + +// The cursor a request carried: `variables` of the GraphQL URL, its `cursor`. +// Undefined when the URL has none or cannot be read. +export function requestCursorOf(url: string): string | undefined { + try { + const raw = new URL(url).searchParams.get("variables"); + const cursor = raw ? (JSON.parse(raw) as { cursor?: unknown } | null)?.cursor : undefined; + return typeof cursor === "string" && cursor ? cursor : undefined; + } catch { + return undefined; + } +} + +// What an answer says of its timeline: whether it carries instructions at all, +// and the BOTTOM cursor it ends with (the last one, when it names several). +export function timelineShapeOf(payload: unknown): { instructions: boolean; bottom?: string } { + let instructions = false; + let bottom: string | undefined; + 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 (Array.isArray(rec.instructions)) instructions = true; + const value = typeof rec.value === "string" && rec.value ? rec.value : undefined; + if (value && rec.cursorType === "Bottom") bottom = value; + if (typeof rec.entryId === "string" && rec.entryId.startsWith("cursor-bottom")) { + const inner = obj(rec.content); + const v = inner?.value ?? obj(inner?.itemContent)?.value; + if (typeof v === "string" && v) bottom = v; + } + for (const child of Object.values(rec)) visit(child); + }; + visit(payload); + return { instructions, ...(bottom ? { bottom } : {}) }; +} + export type TrendingOperation = { op: string; responses: number; bytes: number; statuses: number[]; tweets: number }; export type ParsedTrendingCapture = { @@ -154,6 +289,19 @@ export type ParsedTrendingCapture = { operations: TrendingOperation[]; responses: number; bytes: number; + // THE CAPTURE SHOWS THE PAGE'S END (review 1 S2, review 2 N4). All of: + // - no answer of the page failed: every one a 2xx whose body was kept, + // carrying no GraphQL `errors`, and — for an operation that lists the + // page's posts — carrying timeline instructions; + // - the LAST answer of the listing operation is the CONTINUATION FROM THE + // BOTTOM: its request carries the bottom cursor the answer before it + // ended with (a refresh from the top, or any other cursor, that brings + // nothing new says nothing about the bottom); + // - and it brought no post the capture had not already seen. + // False whenever the capture cannot tell — which cursor an answer was for + // included. Only a capture that shows the end may be read as "what this + // page no longer shows". + pageEnd: boolean; }; // The capture, parsed. `channelSlug` is the library's (a Post names its channel). @@ -165,6 +313,11 @@ export function parseTrendingCapture( const media: Record<string, TrendingMediaSummary> = {}; const ops = new Map<string, TrendingOperation>(); let bytes = 0; + // Per answer of the page's own operations, in order: its operation, and how + // many posts it brought that no earlier answer had. + const answers: Array<{ op: string; fresh: number; asked?: string; bottom?: string; instructions: boolean }> = []; + const seenIds = new Set<string>(); + let failed = false; 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); @@ -172,17 +325,43 @@ export function parseTrendingCapture( 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; + if (X_TRENDING_IGNORED_OPS.includes(line.op)) continue; + if (line.body === undefined || line.status < 200 || line.status >= 300) { + failed = true; + continue; + } + // A 200 that carries GraphQL errors answered only in part, or not at all. + const errors = obj(line.body)?.errors; + if (Array.isArray(errors) && errors.length > 0) failed = true; const found = collectTimelineTweets(line.body); op.tweets += found.length; + let fresh = 0; for (const raw of found) { raws.push(raw); const id = xIdOf(raw); + if (id && !seenIds.has(id)) { + seenIds.add(id); + fresh++; + } const summary = mediaSummaryOf(raw); if (id && summary && !media[id]) media[id] = summary; } + const shape = timelineShapeOf(line.body); + const asked = requestCursorOf(line.url); + answers.push({ op: line.op, fresh, instructions: shape.instructions, ...(asked ? { asked } : {}), ...(shape.bottom ? { bottom: shape.bottom } : {}) }); } + // The answers of the operations that ever listed posts, in order. + const listing = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0); + if (listing.some((a) => !a.instructions)) failed = true; + const last = listing.at(-1); + // The answer before it of the same operation: whose bottom cursor it must carry. + const before = last ? listing.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; + const pageEnd = + !failed && + last !== undefined && + before?.bottom !== undefined && + last.asked === before.bottom && + last.fresh === 0; 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]; @@ -192,6 +371,7 @@ export function parseTrendingCapture( operations: [...ops.values()].sort((a, b) => a.op.localeCompare(b.op)), responses: lines.length, bytes, + pageEnd, }; } diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts @@ -497,3 +497,53 @@ test("N3: a call bounded on a signal already aborted leaves no unhandled rejecti process.off("unhandledRejection", onUnhandled); } }); + +// Lane x-trending-2: a browser that will not close is killed by its checked pid. +test("kill ends the browser's own process when its pid checks out; else it says why and closes again", async () => { + const profileDir = path.join(TMP, "killable", ".x-session", "profile"); + const stub = stubChromium(); + const log: string[] = []; + const sent: Array<[number, string]> = []; + const session = await openXTrendingPage(paths("killable"), { + chromium: stub.chromium, + onLog: (l) => log.push(l), + killDeps: { + platform: "linux", + hostname: "host", + readlink: async (file) => { + assert.equal(file, path.join(profileDir, "SingletonLock")); + return "host-31337"; + }, + cmdline: async () => `chrome\0--user-data-dir=${profileDir}\0`, + kill: (pid, signal) => void sent.push([pid, signal]), + }, + }); + await session.kill!(); + assert.deepEqual(sent, [[31337, "SIGKILL"]]); + assert.ok(log.some((l) => l === "Killed the browser that held the X profile (pid 31337): the profile is free again."), log.join("\n")); + + // A lock whose process does not name this profile: never signalled; closed again, and said. + let closes = 0; + const other = stubChromium(); + const real = other.chromium.launchPersistentContext; + other.chromium.launchPersistentContext = async (dir, opts) => { + const context = await real(dir, opts); + return { ...context, close: async () => void closes++ }; + }; + const log2: string[] = []; + const stale = await openXTrendingPage(paths("stale"), { + chromium: other.chromium, + onLog: (l) => log2.push(l), + killDeps: { platform: "linux", hostname: "host", readlink: async () => "host-31337", cmdline: async () => "bash\0", kill: (pid, signal) => void sent.push([pid, signal]) }, + }); + await stale.kill!(); + assert.equal(sent.length, 1); + assert.equal(closes, 1); + assert.ok(log2.some((l) => /^The browser was not killed \(process 31337 does not name this profile on its command line \(a stale lock\): it is left alone\); closing it again instead\.$/.test(l)), log2.join("\n")); + + // Off Linux: the same fallback. + const log3: string[] = []; + const mac = await openXTrendingPage(paths("mac"), { chromium: stubChromium().chromium, onLog: (l) => log3.push(l), killDeps: { platform: "darwin" } }); + await mac.kill!(); + assert.ok(log3.some((l) => /not killed \(finding the browser's process is Linux-only\); closing it again instead/.test(l))); +}); diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts @@ -31,8 +31,9 @@ // 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). +// A browser that will not close is killed (`session.kill`, by a checked pid: +// profileBrowserPid.ts): 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"; @@ -45,6 +46,7 @@ import { import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; import { findXBrowser } from "./xBrowser"; +import { killProfileBrowser, type ProfileBrowserPidDeps } from "./profileBrowserPid"; import { launchXProfile, xProfileDir } from "./xSessionBroker"; import { xIdOf } from "./xNormalize"; import { @@ -106,7 +108,8 @@ export type TrendingPageRead = { stoppedBy?: { op: string; status: number }; }; -// `kill` ends the browser when `close` does not answer (optional: a fake has none). +// `kill` ends the browser when `close` does not answer: the process itself, +// by its checked pid (openXTrendingPage). Optional: a test's page has none. export type TrendingPageSession = { page: PageLike; close: () => Promise<void>; kill?: () => Promise<void> }; export class PageDeadlineError extends Error { @@ -406,6 +409,8 @@ export async function openXTrendingPage( onLog?: (line: string) => void; env?: Record<string, string | undefined>; display?: HeadedDisplayLaunchDeps; + // For tests: how the browser's pid is found and signalled. + killDeps?: ProfileBrowserPidDeps; } = {}, ): Promise<TrendingPageSession> { const log = o.onLog ?? (() => {}); @@ -432,12 +437,23 @@ export async function openXTrendingPage( 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; + // A BROWSER THAT DOES NOT CLOSE IS KILLED, BY PID (lane x-trending-2; + // profileBrowserPid.ts): the process Chromium's own lock in the profile + // names, and only when its command line names this exact profile directory. + // Off Linux, or when that check does not hold, nothing is killed: the + // context is closed again instead, and the log says which it was. + const profileDir = xProfileDir(paths); return { page, close: () => context.close(), - ...(browser?.close ? { kill: () => browser.close!() } : {}), + kill: async () => { + const r = await killProfileBrowser(profileDir, o.killDeps); + if (r.killed) { + log(`Killed the browser that held the X profile (pid ${r.pid}): the profile is free again.`); + return; + } + log(`The browser was not killed (${r.why}); closing it again instead.`); + await context.close(); + }, }; } diff --git a/common/views/review.ts b/common/views/review.ts @@ -56,3 +56,9 @@ export function autoPausedRows(model: ChannelPriority): AutoPausedRow[] { } return rows; } + +// PAUSED WATCHES (lane x-trending-2): topics of an X trending library someone +// switched a watch on for, which the watch's scan cannot tick now. The row and +// its builder live a layer down (lib/xTrending/watch.ts), where the controller +// that reads the libraries may import them; /review's types are named here. +export { pausedWatchRows, type PausedWatchRow } from "../lib/xTrending/watch"; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,32 @@ # Changelog ## [Unreleased] +- **A trending library can be judged, archived and watched.** + - **Keep / Drop / Later** under each post on a library's page, or `pnpm ops judge-trending`. A thread can be + judged by its root post. An agent's judgement never replaces the operator's: it is skipped for that post and + reported. Drop deletes nothing. + - Keep archives the post: one capture job takes a screenshot, the post's context, a reply's thread shot and its + media. + - A library's media comes from X's media CDN, with no login and one file at a time, and each file is stored + once however many posts or topics carry it (`trending/media-store/`, hardlinked per post). A job fetches at + most 40 files or 200 MB; a file over 100 MB waits until its post is kept. A rate limit from the CDN stops the + job and leaves X alone for 15 minutes. + - **Watch** on a topic, or `pnpm ops watch-trending`: the topic's trending page is read again every 30 minutes + for 48 hours (both adjustable; at most 4 topics a library), and the media of new posts is fetched at once. + "Screenshot everything new" is per topic. + - **A watch runs only while X's cookie jar is under 60 minutes old.** The editor does not refresh the jar by + itself, so a watch pauses when the jar goes stale and resumes after Refresh cookies on /cookies. It does not + cover a night nobody refreshes in. /review lists paused watches. The limit is the watch's own: it holds + whatever the login source, and with the cookie-age setting at 0. + - All libraries share one stream of ticks: no tick starts while a trending read or capture of any library is + queued or running. Three failed reads in a row pause a watch until someone switches it on again. + - A post a trending page stops showing is marked "Gone from the page at …", and only when the saved capture + shows the page's end. That is not a claim it was deleted. + - A browser that will not close is now killed by its process id, checked against the profile it holds. + - `pnpm ops get trending` and the MCP's `x_trending_topics` / `x_trending_posts` show each topic's watch and each + post's thread, judgement, capture and gone mark. + - Everything this adds stays private: `trending/.gitignore` keeps the media out of the corpus's git repo, and no + site, build, report or video project is given a judgement, a capture or a watch. - **The dashboard, Jobs, Settings, Storage and Channels show their heading and controls at once, and the slow parts fill in.** Each page used to wait for every read before sending anything. Now the sidebar, the heading and the buttons arrive first, and each slow section arrives when its read is done, in the place a grey placeholder of the diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts @@ -0,0 +1,50 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { isXTrendingLibrarySync } from "yt-dlp-transcript-common/lib/xTrending/library-server"; +import { armXTrendingWatch, type WatchScanDeps } from "yt-dlp-transcript-common/controller/xTrendingWatch"; +import { readXTrendingAction } from "../../channels/[slug]/xTrendingActions"; + +// THE WATCH'S EDITOR SIDE (lane x-trending-2): what the scan +// (common/controller/xTrendingWatch.ts) runs on in this editor — its job +// registry and its own read action, so a tick is exactly the job a person +// starts — shared by `watch-trending {"tick": true}` and the timer +// instrumentation.ts arms. +export function xTrendingWatchDeps(): WatchScanDeps { + const paths = getPaths(); + return { + paths, + log: (line) => console.log(line), + // A trending read, a reparse, or a capture of a LIBRARY, waiting its turn + // or running — whatever the library (review 1 M3): every library's ticks + // are one stream, so the scan never stacks one read per library on X's + // queue. + busy: () => xTrendingJobWaiting(getRegistry().list(), (slug) => isXTrendingLibrarySync(paths.channelsDir, slug)), + enqueue: async (tick) => { + // Marked as the watch's: its job asks the watch's jar rule at its start. + const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic, watch: true }); + if (!started.ok) return { ok: false, error: started.error }; + void started.stream.cancel(); + return { ok: true, jobId: started.jobId }; + }, + }; +} + +type JobLike = { kind: string; status: string; channelSlug?: string }; + +// A trending job of ANY library that is queued or running. +export function xTrendingJobWaiting(jobs: ReadonlyArray<JobLike>, isLibrary: (slug: string) => boolean): boolean { + return jobs.some( + (j) => + (j.status === "queued" || j.status === "running") && + (j.kind === READ_X_TRENDING_KIND || + j.kind === REPARSE_X_TRENDING_KIND || + (j.kind === "capture-posts" && !!j.channelSlug && isLibrary(j.channelSlug))), + ); +} + +// Armed once per process, below the idle gate (armXTrendingWatch refuses an +// idle boot itself too). +export function armXTrendingWatchLane(): boolean { + return armXTrendingWatch(xTrendingWatchDeps()); +} diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,7 +10,7 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, keptMedia?, queueKey? } -> { ok: true, jobId } // // Capture specific archived posts of a social channel: a screenshot of each // (`shots`, default true) and its attached media (`media`, default true), into @@ -48,10 +48,27 @@ export const dynamic = "force-dynamic"; // is not a social one, a fetcher that cannot capture, an id not in the // channel's posts archive, `avatarsOnly` or `contextOnly` on a channel that // is not X, both of them at once. +// +// AN X TRENDING LIBRARY (lane x-trending-2) is captured by this same job, its +// captures under `channels/<slug>/trending/posts-media/<id>/`. Its MEDIA comes +// from X's media CDN, by the addresses in the library's saved captures — no +// login, one file after another 1 to 2 s apart, under X's cooldown; each file +// is kept once (`trending/media-store/`, a hardlink per post). A file over the +// library's `maxVideoMb` (100 MB) and whatever is past the job's budget (40 +// files / 200 MB) is OWED: asked for again by the next capture of that post. A +// 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or a +// 404 marks the file; nothing retries. `keptMedia: true` is for posts marked +// keep (refused for any other id): no per-file cap, and a post the CDN cannot +// serve whole is downloaded the logged-in way — the judgements are read again, +// once per post, before its media, so a post dropped since the job was queued +// gets neither: it is fetched under the library's cap, with no login. `judge-trending` runs it for the posts it marks keep. A +// library's capture runs on X's queue only: `queueKey` is refused for it. Three +// refusals in a row from the CDN (a 403, or no answer) and the job asks it for +// no more; the rest is owed. export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "keptMedia", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -70,6 +87,7 @@ export async function POST(request: Request) { avatarsOnly: optBool(body, "avatarsOnly"), context: optBool(body, "context"), contextOnly: optBool(body, "contextOnly"), + keptMedia: optBool(body, "keptMedia"), }, ), ); diff --git a/editor/app/api/ops/judge-trending/route.test.ts b/editor/app/api/ops/judge-trending/route.test.ts @@ -0,0 +1,153 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { 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/judge-trending/route.test.ts" +// +// judge-trending over ops (lane x-trending-2), against a temp corpus: the +// refusals, a write by an agent, the operator's judgement an agent cannot +// replace, and the listing carrying what was written. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-judge-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 A = "1900000000000001001"; +const B = "1900000000000001002"; + +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"), + [A, B] + .map((id) => + JSON.stringify({ + id, + slug: `trending/${id}`, + channelSlug: "trending", + author: "teapot_news", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: `post ${id}`, + url: `https://x.com/teapot_news/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }), + ) + .join("\n") + "\n", +); +await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\n`); +const seen = [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }]; +await writeFile( + path.join(lib, "trending", "membership.json"), + JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen }, [B]: { topic: "kettles", seen } } }), +); + +const judge = (await import("./route")).POST; +const listing = (await import("../trending/route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(body: Record<string, unknown>, token = "test-token") { + const res = await judge( + new Request("http://localhost/api/ops/judge-trending", { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} + +test("judge-trending refuses with a sentence", async () => { + assert.equal((await call({ slug: "trending", set: [{ id: A, state: "keep" }] }, "wrong")).status, 401); + for (const [body, re] of [ + [{ slug: "nope", set: [{ id: A, state: "keep" }] }, /No such channel: nope/], + [{ slug: "account-x", set: [{ id: A, state: "keep" }] }, /not an X trending library/], + [{ slug: "trending" }, /"set" is a list of judgements/], + [{ slug: "trending", set: [] }, /"set" is a list of judgements/], + [{ slug: "trending", set: [{ id: A, state: "maybe" }] }, /keep, drop, later or undecided/], + [{ slug: "trending", set: [{ id: A, state: "keep" }], by: "someone" }, /"by" is who decided/], + [{ slug: "trending", set: [{ id: A, state: "keep" }], force: true }, /unknown key\(s\): force/], + ] as const) { + const r = await call(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.json.error), re); + } +}); + +test("an agent's judgement is written; the operator's is not replaced by an agent; the listing carries both", async () => { + const first = await call({ slug: "trending", archive: false, set: [{ id: A, state: "keep", note: "the opening" }, { id: "42", state: "keep" }] }); + assert.equal(first.json.archive, undefined); + assert.equal(first.status, 200); + assert.deepEqual(first.json.written, [{ id: A, state: "keep" }]); + assert.deepEqual(first.json.skipped, [{ id: "42", reason: "not in this library" }]); + assert.deepEqual(first.json.kept, [A]); + const op = await call({ slug: "trending", by: "operator", set: [{ id: A, state: "drop" }, { id: B, state: "later" }] }); + assert.deepEqual(op.json.written, [{ id: A, state: "drop" }, { id: B, state: "later" }]); + const again = await call({ slug: "trending", archive: false, set: [{ id: A, state: "keep" }] }); + assert.equal(again.status, 200); + assert.deepEqual(again.json.written, []); + assert.match(JSON.stringify(again.json.skipped), /judged by the operator/); + const file = JSON.parse(await readFile(path.join(lib, "trending", "judgements.json"), "utf8")); + assert.equal(file.posts[A].state, "drop"); + assert.equal(file.posts[A].by, "operator"); + const res = await listing(new Request("http://localhost/api/ops/trending?slug=trending", { headers: { authorization: "Bearer test-token" } })); + const rows = ((await res.json()) as { posts: Array<{ id: string; judgement?: { state: string } }> }).posts; + assert.deepEqual(rows.map((p) => [p.id, p.judgement?.state]).sort(), [[A, "drop"], [B, "later"]]); +}); + +test("a keep archives through capture-posts; a refused capture leaves the judgement written and says why", async () => { + // This corpus has no connected X profile and no cookie jar: the capture is + // refused before a job exists (nothing is asked of X), the keep stands. + const r = await call({ slug: "trending", by: "operator", set: [{ id: B, state: "keep" }] }); + assert.equal(r.status, 200); + assert.deepEqual(r.json.kept, [B]); + const archive = r.json.archive as { error?: string; jobId?: string; ids: string[] }; + assert.deepEqual(archive.ids, [B]); + assert.equal(archive.jobId, undefined); + assert.ok(archive.error && archive.error.length > 20, String(archive.error)); + const file = JSON.parse(await readFile(path.join(lib, "trending", "judgements.json"), "utf8")); + assert.equal(file.posts[B].state, "keep"); +}); + +test("capture-posts keptMedia is for a library's kept posts only", async () => { + const capture = (await import("../capture-posts/route")).POST; + const ask = async (body: Record<string, unknown>) => { + const res = await capture( + new Request("http://localhost/api/ops/capture-posts", { + 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> }; + }; + // A is dropped by the operator above: not kept. + const notKept = await ask({ slug: "trending", ids: [A], keptMedia: true }); + assert.equal(notKept.status, 400); + assert.match(String(notKept.json.error), new RegExp(`not kept: ${A}`)); + const notLibrary = await ask({ slug: "account-x", ids: ["1"], keptMedia: true }); + assert.equal(notLibrary.status, 400); + // Review 1 S5: a library's capture runs on X's queue only. + for (const queueKey of ["", "side-queue"]) { + const moved = await ask({ slug: "trending", ids: [B], queueKey }); + assert.equal(moved.status, 400); + assert.match(String(moved.json.error), /is an X trending library: its captures run on X's queue only \("queueKey" is refused\)/); + } + // An id that is not the library's is refused as stray before anything else. + assert.match(String((await ask({ slug: "trending", ids: ["42"], keptMedia: true })).json.error), /not in trending's posts archive/); +}); diff --git a/editor/app/api/ops/judge-trending/route.ts b/editor/app/api/ops/judge-trending/route.ts @@ -0,0 +1,65 @@ +import { NextResponse } from "next/server"; +import { judgeXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { OpsInputError, ops, opsFail, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, set: [{id | thread, state, note?}, …], by?, archive? } +// -> { ok: true, slug, written: [{id | thread, state}], +// skipped: [{id | thread, reason}], kept: [<post id>, …], +// archive?: {jobId, ids} | {error, ids} } +// +// JUDGE POSTS OF AN X TRENDING LIBRARY (lane x-trending-2), written to +// `channels/<slug>/trending/judgements.json` by its one writer: +// +// id a post of the library } one of them +// thread a thread's ROOT post id: every post of the thread with no +// judgement of its own is taken to be the thread's +// state keep | drop | later, or undecided (the judgement is removed: no +// entry is undecided) +// note up to 2000 characters, kept with the judgement +// by "agent" (the default here) or "operator" (the channel page's +// buttons). IT IS THE CALLER'S WORD: this route cannot tell who is +// asking, so an agent is trusted to say "agent" (the operator's +// hand is the page's buttons, and slice 3's judge view). +// AN AGENT'S JUDGEMENT IS A SUGGESTION: an agent's write over a +// judgement the operator made is skipped for that id and named in +// `skipped`; the rest of the ask is written. +// +// WHICH JUDGEMENT IS IN FORCE, one rule: the operator's entry, for the post or +// for its thread, always outranks an agent's about the same post, whatever +// the order in time; between two entries of the same hand, the post's own +// outranks its thread's. So an agent's post-level write is skipped whenever +// the post's thread is the operator's, and an operator's thread judgement +// overrides an agent's older entry for one of its posts at once (that entry +// stays in the file and decides nothing). +// +// `kept` names the posts whose judgement BECAME keep by this ask (their own, +// or their thread's). A KEEP ARCHIVES THEM: one `capture-posts` job on X's +// queue (a screenshot, the context, a reply's thread shot, the media — +// `archive.jobId`), unless `archive: false`. When that job is refused (a +// stale jar, the X alert, X cooling down) the judgements are written all the +// same and `archive.error` says why nothing was started; `capture-posts +// {slug, ids, thread: true, keptMedia: true}` archives them later. +// DROP DELETES NOTHING: the post, its capture and its media stay, and a +// later keep puts it back. +// +// Refused with a sentence: no such channel, not a library, an ill-shaped set +// (an unknown key, both or neither of id and thread, a state that is none of +// the four, a note on "undecided", an id judged twice). An id the library +// does not hold is not a refusal: it is skipped by name. +export async function POST(request: Request) { + return ops(request, ["slug", "set", "by", "archive"], async (body) => { + const archive = optBool(body, "archive"); + const by = body.by === undefined ? "agent" : body.by; + if (body.set === undefined) throw new OpsInputError(`"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`); + const result = await judgeXTrendingAction({ + slug: reqSlug(body, "slug"), + by, + set: body.set, + ...(archive !== undefined ? { archive } : {}), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/api/ops/read-x-trending/route.test.ts b/editor/app/api/ops/read-x-trending/route.test.ts @@ -145,6 +145,7 @@ test("get trending lists topics and posts — words, author, media, reads, topic media: { count: 2, kinds: ["image"] }, topic: "kettles", reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }], + thread: "1900000000000001001", }); assert.equal(all.json.total, 2); assert.deepEqual(all.json.reads, [READ]); diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -10,10 +10,11 @@ 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}]}], +// title?, summary?, reads, lastReadAt}], watch?}], // posts: [{id, author, authorName?, createdAt, url, text, // media: {count, kinds, thumbnail?}, topic, -// reads: [{read, trendId, at}], judgement?}], +// reads: [{read, trendId, at}], gone?, capture?, thread, +// judgement?}], // total, reads: [<readId>, …] } // // An X trending library's topics and posts (lane x-trending) — `pnpm ops get @@ -26,9 +27,19 @@ export const dynamic = "force-dynamic"; // 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. +// and no route serves it yet), present once the post is captured; `thread` is +// the root post id of the thread it belongs to; `judgement` ({state: keep | +// drop | later, note?, by: agent | operator, at, from?}) is its own, else its +// thread's (`from: "thread"`), written by `judge-trending`; a post with none +// is undecided. `gone` ({at, read, trendId}) says a page that showed the post +// before did not show it at `at`, a read that reached the page's end: gone +// FROM THE PAGE, which is not deleted. `capture` ({at, state, shot, files, +// mediaState, mediaOwed?}) is what its capture holds; `mediaOwed` "next" is +// asked for again by a later capture, "kept" once the post is marked keep. +// A topic's `watch` ({on, intervalMinutes, until, shots, lastTickAt?, +// nextTickAt?, ticks, paused?: {reason, since, sentence}, ended?, sentence}) is +// there once it has been watched (`watch-trending`); `sentence` says what it +// is doing. NEVER the raw capture, a cookie or a token. export async function GET(request: Request) { const denied = opsAuth(request); if (denied) return denied; diff --git a/editor/app/api/ops/watch-trending/route.test.ts b/editor/app/api/ops/watch-trending/route.test.ts @@ -0,0 +1,145 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { 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/watch-trending/route.test.ts" +// +// watch-trending over ops (lane x-trending-2), against a temp corpus with no +// connected X profile: the switch, the library's settings, the listing's +// watch, and ONE SCAN that — there being no profile — pauses the watch +// instead of starting a read. No browser opens and nothing is asked of X. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-watch-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: { maxPosts: 30 } }); +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", "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 }] }] }, + { id: "empty", title: "Empty", createdAt: "2026-11-17T10:00:00.000Z", sources: [] }, + ], + }), +); + +const watch = (await import("./route")).POST; +const listing = (await import("../trending/route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(body: Record<string, unknown>) { + const res = await watch( + new Request("http://localhost/api/ops/watch-trending", { + 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> }; +} + +const topics = async () => { + const res = await listing(new Request("http://localhost/api/ops/trending?slug=trending", { headers: { authorization: "Bearer test-token" } })); + return ((await res.json()) as { topics: Array<{ id: string; watch?: Record<string, unknown> }> }).topics; +}; + +test("watch-trending refuses with a sentence", async () => { + for (const [body, re] of [ + [{ slug: "nope", topic: "kettles", on: true }, /No such channel: nope/], + [{ slug: "account-x", topic: "kettles", on: true }, /not an X trending library/], + [{ slug: "trending" }, /Give "topic" with "on".*one of them/], + [{ slug: "trending", topic: "kettles", on: true, tick: true }, /one of them/], + [{ slug: "trending", topic: "kettles" }, /"on" is true \(watch the topic\) or false/], + [{ slug: "trending", topic: "spouts", on: true }, /no topic "spouts" \(its topics: kettles, empty\)/], + [{ slug: "trending", topic: "empty", on: true }, /holds no trending page to watch/], + [{ slug: "trending", topic: "kettles", on: true, intervalMinutes: 5 }, /"intervalMinutes" is a whole number, 15–1440/], + [{ slug: "trending", topic: "kettles", on: true, hours: 1000 }, /"hours" is a whole number, 1–168/], + [{ slug: "trending", topic: "kettles", on: false }, /is not being watched/], + [{ slug: "trending", settings: { maxVideoMb: 0 } }, /"maxVideoMb" is a whole number, 1–2000/], + [{ slug: "trending", settings: { colour: 1 } }, /unknown setting\(s\): colour/], + [{ slug: "trending", settings: {} }, /names nothing to change/], + [{ slug: "trending", topic: "kettles", on: true, force: true }, /unknown key\(s\): force/], + ] as const) { + const r = await call(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.json.error), re, JSON.stringify(body)); + } +}); + +test("the library's settings are written into config.xTrending, the marker and its other keys kept", async () => { + const r = await call({ slug: "trending", settings: { maxVideoMb: 50, intervalMinutes: 20, hours: 6, maxTopics: 1 } }); + assert.equal(r.status, 200); + const config = JSON.parse(await readFile(path.join(lib, "config.json"), "utf8")); + assert.deepEqual(config.xTrending, { maxPosts: 30, maxVideoMb: 50, watchIntervalMinutes: 20, watchHours: 6, watchMaxTopics: 1 }); + assert.equal(config.platform, "twitter"); +}); + +test("a topic is watched on the library's terms; the listing shows it; a scan with no connected profile pauses it and starts nothing", async () => { + const on = await call({ slug: "trending", topic: "Kettles", on: true, shots: true }); + assert.equal(on.status, 200, JSON.stringify(on.json)); + assert.equal(on.json.topic, "kettles"); + const w = on.json.watch as { on: boolean; intervalMinutes: number; shots: boolean; until: string; startedAt: string }; + assert.deepEqual([w.on, w.intervalMinutes, w.shots], [true, 20, true]); + assert.equal(Date.parse(w.until) - Date.parse(w.startedAt), 6 * 3_600_000); + assert.match(String(on.json.sentence), /^Watched every 20 min until .* UTC, screenshotting every new post; 0 ticks so far/); + assert.equal((await topics()).find((t) => t.id === "kettles")?.watch?.on, true); + assert.equal((await topics()).find((t) => t.id === "empty")?.watch, undefined); + + const tick = await call({ slug: "trending", tick: true }); + assert.equal(tick.status, 200, JSON.stringify(tick.json)); + const scan = tick.json.scan as { live: number; enqueued?: unknown; paused: Array<{ topic: string; reason: string }> }; + assert.equal(scan.enqueued, undefined); + assert.deepEqual(scan.paused, [{ slug: "trending", topic: "kettles", reason: "no-profile" }]); + const paused = (await topics()).find((t) => t.id === "kettles")?.watch as { paused?: { reason: string }; sentence: string }; + assert.equal(paused.paused?.reason, "no-profile"); + assert.match(paused.sentence, /PAUSED since .* UTC: There is no connected X profile/); + + const off = await call({ slug: "trending", topic: "kettles", on: false, by: "operator" }); + assert.equal(off.status, 200); + assert.equal(off.json.sentence, 'The watch of "Kettles" was switched off.'); +}); + +// Review 1 S6. +test("S6: a scan asked for by hand is refused on an idle boot; a settings change and the switch are not", async () => { + process.env.ARCHILYZER_IDLE_BOOT = "1"; + try { + const tick = await call({ slug: "trending", tick: true }); + assert.equal(tick.status, 400); + assert.match(String(tick.json.error), /booted idle \(ARCHILYZER_IDLE_BOOT\): it starts no work, so no watch scan runs/); + assert.equal((await call({ slug: "trending", settings: { maxTopics: 2 } })).status, 200); + } finally { + delete process.env.ARCHILYZER_IDLE_BOOT; + } +}); + +// Review 1 M3. +test("M3: the scan counts a trending job of ANY library as waiting — and no other channel's capture", async () => { + const { xTrendingJobWaiting } = await import("../_xTrendingWatch"); + const isLibrary = (slug: string) => slug === "trending" || slug === "other-library"; + const job = (kind: string, status: string, channelSlug?: string) => ({ kind, status, ...(channelSlug ? { channelSlug } : {}) }); + assert.equal(xTrendingJobWaiting([], isLibrary), false); + assert.equal(xTrendingJobWaiting([job("read-x-trending", "queued", "other-library")], isLibrary), true); + assert.equal(xTrendingJobWaiting([job("read-x-trending", "running", "trending")], isLibrary), true); + assert.equal(xTrendingJobWaiting([job("reparse-x-trending", "queued", "other-library")], isLibrary), true); + assert.equal(xTrendingJobWaiting([job("capture-posts", "queued", "other-library")], isLibrary), true); + // An ordinary X channel's capture is not the watch's business; nor is a finished job. + assert.equal(xTrendingJobWaiting([job("capture-posts", "running", "account-x")], isLibrary), false); + assert.equal(xTrendingJobWaiting([job("read-x-trending", "done", "trending"), job("capture-posts", "failed", "trending")], isLibrary), false); +}); diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts @@ -0,0 +1,89 @@ +import { NextResponse } from "next/server"; +import { watchXTrendingAction, type WatchSettingsAsk } from "../../../channels/[slug]/xTrendingActions"; +import { ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, topic, on, intervalMinutes?, hours?, shots?, by? } +// -> { ok: true, slug, topic, watch, sentence } +// POST { slug, settings: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?} } +// -> { ok: true, slug, settings, sentence } +// POST { slug, tick: true } +// -> { ok: true, slug, scan, sentence } +// +// WATCH A TOPIC OF AN X TRENDING LIBRARY (lane x-trending-2). While a topic +// is watched, its trending page is read again every `intervalMinutes` +// (15–1440; default the library's, else 30) until `hours` from now (1–168; +// else 48), each tick the SAME single `read-x-trending` job on X's queue, +// started by the editor's own scan (once a minute; at most one read per scan; +// none while a trending read, a reparse or a capture of ANY library waits its +// turn: every library's ticks are one stream). A topic of +// several trending pages reads one page per tick, in turn. At most +// `maxTopics` topics of a library are watched at once (default 4). +// +// on true watches the topic (again: its terms change, its history +// stays); false stops (the watch ends "switched off") +// shots also screenshot every new post. Default: a new post's MEDIA only, +// fetched at once from X's media CDN with no page opened +// by "agent" (default) or "operator" +// +// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes). The +// editor never refreshes the jar by itself, so a watch PAUSES when the jar +// goes stale — X's jar-age alert goes up and /review lists the paused watches +// — and resumes at the first scan after Refresh cookies on /cookies. It does +// not cover a night nobody presses Refresh in. THE LIMIT IS THE WATCH'S OWN, +// stricter than the one a person's job meets: whatever the login source, a +// watch asks the profile's exported jar to be between 0 and the limit old (the +// setting when above 0, else 60 minutes), and never ticks when settings +// cannot be read. It is asked when a tick is queued AND AGAIN WHEN THE TICK'S +// JOB STARTS (and when the capture that follows it is queued and starts): a +// job waits its turn on X's queue, and a tick whose turn comes on a jar past +// the limit is not read — no browser opens, the watch pauses, and it is no +// strike against it. The X alert, X cooling down after a rate limit and a +// missing profile pause it the same way. +// +// THREE READS IN A ROW THAT DO NOT END "read" (a rate limit, a 403, a page +// that will not load) pause the watch as "failing". That pause does not end +// by itself, and only the OPERATOR ends it: switch the watch on again with +// `"by": "operator"` (the page's Watch button); an agent's ask is refused. +// +// A post a page showed before and does not show at a read whose capture shows +// the page's end (the page asked for more FROM THE BOTTOM — the request carries +// the previous answer's bottom cursor — and got nothing new, and no answer +// failed or carried errors) is recorded "gone from the page at <time>" (`get trending`: `gone`) +// — never "deleted": a trending page is a ranked list. A read that merely went +// quiet says nothing. A trending +// page X no longer has is not read again, and the watch ends with a sentence +// when it was the topic's last. +// +// `settings` changes the library's own defaults (config.xTrending): +// maxVideoMb (1–2000; the largest media file fetched for a post nobody has +// kept), intervalMinutes, hours, maxTopics (1–12). `tick: true` runs one scan +// now, as the timer does: through the same single scan (two asks at once are +// one), and refused on an idle boot (ARCHILYZER_IDLE_BOOT). +// +// Refused with a sentence: no such channel, not a library, not exactly one of +// topic / settings / tick, no such topic, a topic with no trending page, the +// library's limit, an interval or length out of range, a topic not watched +// (off). +export async function POST(request: Request) { + return ops(request, ["slug", "topic", "on", "intervalMinutes", "hours", "shots", "by", "settings", "tick"], async (body) => { + const topic = optString(body, "topic"); + const on = optBool(body, "on"); + const shots = optBool(body, "shots"); + const tick = optBool(body, "tick"); + const result = await watchXTrendingAction({ + slug: reqSlug(body, "slug"), + ...(tick ? { tick: true } : {}), + ...(body.settings !== undefined ? { settings: body.settings as WatchSettingsAsk } : {}), + ...(topic !== undefined ? { topic } : {}), + ...(on !== undefined ? { on } : {}), + ...(body.intervalMinutes !== undefined ? { intervalMinutes: body.intervalMinutes } : {}), + ...(body.hours !== undefined ? { hours: body.hours } : {}), + ...(shots !== undefined ? { shots } : {}), + ...(body.by !== undefined ? { by: body.by } : {}), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx @@ -1,20 +1,177 @@ "use client"; -import { useState } from "react"; +import { useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; 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 { + X_TRENDING_WATCH_MAX_HOURS, + X_TRENDING_WATCH_MAX_INTERVAL_MINUTES, + X_TRENDING_WATCH_MIN_INTERVAL_MINUTES, +} from "yt-dlp-transcript-common/lib/xTrending/config"; +import type { + XTrendingListing, + XTrendingPostRow, + XTrendingTopicRow, +} from "yt-dlp-transcript-common/lib/xTrending/store"; import { cancelJobAction } from "../../../jobs/actions"; -import { readXTrendingAction } from "../xTrendingActions"; +import { judgeXTrendingAction, readXTrendingAction, watchXTrendingAction } from "../xTrendingActions"; + +const when = (iso: string) => iso.slice(0, 16).replace("T", " "); + +// THE WATCH OF ONE TOPIC (lane x-trending-2): the switch, its interval and +// length, and "screenshot everything new" — `pnpm ops watch-trending`. +// A field left empty takes the library's default (30 min, 48 h unless its +// settings say otherwise). +function TopicWatch({ slug, topic }: { slug: string; topic: XTrendingTopicRow }) { + const router = useRouter(); + const [pending, start] = useTransition(); + const live = !!topic.watch && topic.watch.on && !topic.watch.ended; + const [every, setEvery] = useState(live && topic.watch ? String(topic.watch.intervalMinutes) : ""); + const [hours, setHours] = useState(""); + const [shots, setShots] = useState(topic.watch?.shots ?? false); + const [said, setSaid] = useState<string | null>(null); + const input = "rounded border border-border bg-card px-2 py-1 text-xs"; + const set = (on: boolean) => + start(async () => { + const r = await watchXTrendingAction({ + slug, + topic: topic.id, + on, + by: "operator", + ...(on + ? { + ...(every.trim() ? { intervalMinutes: Number(every) } : {}), + ...(hours.trim() ? { hours: Number(hours) } : {}), + shots, + } + : {}), + }); + setSaid(r.ok ? r.sentence : r.error); + router.refresh(); + }); + return ( + <div data-x-trending-watch={topic.id} className="flex flex-col gap-1 text-xs"> + <div className="flex flex-wrap items-end gap-2"> + <label className="flex flex-col gap-0.5"> + <span className="font-medium">Every (min)</span> + <input + type="number" + min={X_TRENDING_WATCH_MIN_INTERVAL_MINUTES} + max={X_TRENDING_WATCH_MAX_INTERVAL_MINUTES} + value={every} + placeholder="30" + onChange={(e) => setEvery(e.target.value)} + aria-label={`watch interval of ${topic.title}`} + className={`${input} w-20`} + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="font-medium">For (hours)</span> + <input + type="number" + min={1} + max={X_TRENDING_WATCH_MAX_HOURS} + value={hours} + placeholder="48" + onChange={(e) => setHours(e.target.value)} + aria-label={`watch length of ${topic.title}`} + className={`${input} w-20`} + /> + </label> + <label className="flex items-center gap-1" title="Also take a screenshot of every new post (a page load each); otherwise only their media is fetched"> + <input type="checkbox" checked={shots} onChange={(e) => setShots(e.target.checked)} aria-label={`screenshot everything new in ${topic.title}`} /> + Screenshot everything new + </label> + <button type="button" disabled={pending} onClick={() => set(true)} className="rounded border border-border px-2 py-1 font-medium disabled:opacity-50"> + {live ? "Change watch" : "Watch"} + </button> + {live && ( + <button type="button" disabled={pending} onClick={() => set(false)} className="rounded border border-border px-2 py-1 disabled:opacity-50"> + Stop watching + </button> + )} + </div> + <span data-x-trending-watch-state="" className={topic.watch?.paused ? "text-amber-700 dark:text-amber-400" : "text-muted-foreground"}> + {said ?? topic.watch?.sentence ?? "Not watched."} + </span> + <span className="text-muted-foreground"> + A watch runs only while X&apos;s cookie jar is under its limit (60 min): it pauses when the jar goes stale and resumes after Refresh cookies on /cookies, so it does not cover a night nobody refreshes in. + </span> + </div> + ); +} + +const STATES = [ + ["keep", "Keep"], + ["drop", "Drop"], + ["later", "Later"], +] as const; + +// ONE POST'S JUDGEMENT (lane x-trending-2): keep / drop / later, or cleared — +// `pnpm ops judge-trending`, by the operator. Keep archives the post. +function PostJudge({ slug, post }: { slug: string; post: XTrendingPostRow }) { + const router = useRouter(); + const [pending, start] = useTransition(); + const [said, setSaid] = useState<string | null>(null); + const own = post.judgement && !post.judgement.from ? post.judgement.state : undefined; + const judge = (state: "keep" | "drop" | "later" | "undecided") => + start(async () => { + const r = await judgeXTrendingAction({ slug, by: "operator", set: [{ id: post.id, state }] }); + setSaid( + !r.ok + ? r.error + : r.archive && "error" in r.archive + ? `Kept. Not archived yet: ${r.archive.error}` + : r.archive + ? `Kept; archiving as job ${r.archive.jobId}.` + : null, + ); + router.refresh(); + }); + return ( + <span className="flex flex-wrap items-center gap-1 text-xs"> + {STATES.map(([state, label]) => ( + <button + key={state} + type="button" + disabled={pending} + aria-pressed={own === state} + aria-label={`${label} ${post.id}`} + onClick={() => judge(state)} + className={`rounded border px-2 py-0.5 disabled:opacity-50 ${own === state ? "border-foreground font-semibold" : "border-border"}`} + > + {label} + </button> + ))} + {own && ( + <button type="button" disabled={pending} aria-label={`Clear ${post.id}`} onClick={() => judge("undecided")} className="rounded border border-border px-2 py-0.5 disabled:opacity-50"> + Clear + </button> + )} + {post.judgement && ( + <span data-x-trending-judgement={post.judgement.state} className="text-muted-foreground"> + {post.judgement.state} by {post.judgement.by} + {post.judgement.from ? " (its thread)" : ""} + {post.judgement.note ? `: ${post.judgement.note}` : ""} + </span> + )} + {said && <span className="text-muted-foreground">{said}</span>} + </span> + ); +} // 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`. +// Lane x-trending-2 adds, per topic, its watch (`watch-trending`), and per +// post its judgement (`judge-trending`), what its capture holds and whether a +// page stopped showing it. export function XTrendingPanel({ slug, listing, @@ -168,6 +325,7 @@ export function XTrendingPanel({ </li> ))} </ul> + {t.sources.length > 0 && <TopicWatch slug={slug} topic={t} />} <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"> @@ -180,8 +338,18 @@ export function XTrendingPanel({ ? ` · ${p.media.count} media${p.media.kinds.length ? ` (${p.media.kinds.join(", ")})` : ""}` : ""} {p.reads.length > 1 ? ` · on ${p.reads.length} reads` : ""} + {p.capture + ? ` · captured${p.capture.shot ? " (shot)" : ""}, ${p.capture.files} file${p.capture.files === 1 ? "" : "s"}` + + (p.capture.mediaOwed === "kept" ? ", more owed once kept" : p.capture.mediaOwed === "next" ? ", more owed to the next capture" : "") + : ""} </span> + {p.gone && ( + <span data-x-trending-gone="" className="text-xs text-amber-700 dark:text-amber-400"> + Gone from the page at {when(p.gone.at)} UTC. + </span> + )} <span className="whitespace-pre-wrap">{p.text}</span> + <PostJudge slug={slug} post={p} /> </li> ))} </ol> diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -23,6 +23,10 @@ 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 { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements"; +import { refuseWatchJob } from "yt-dlp-transcript-common/controller/xTrendingWatch"; +import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; 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"; @@ -55,6 +59,7 @@ import { capturePosts, contextOnlyProblem, capturePostsProblem, + X_LIBRARY_FETCHER, NOTHING_TO_CAPTURE, nothingToCapture, parseThreadRedact, @@ -355,9 +360,18 @@ export async function capturePostsAction( avatarsOnly?: boolean; context?: boolean; contextOnly?: boolean; + // An X trending library: these posts are marked KEEP, so their media has + // no per-file cap and a post the CDN cannot serve whole is downloaded the + // logged-in way. Refused for an id that is not kept. + keptMedia?: boolean; + // An X trending library: this capture was queued BY A WATCH (the media of + // a watched topic's new posts), not asked for by a person. Its job asks + // the watch's own jar rule when it starts (review 2 N1), and starts + // nothing when that refuses. + watch?: boolean; } = {}, ): Promise<StreamActionResult> { - const { thread, avatars, avatarsOnly, context, contextOnly } = more; + const { thread, avatars, avatarsOnly, context, contextOnly, keptMedia, watch } = more; const redact = parseThreadRedact(more.threadRedact); if (!redact.ok) return { ok: false, error: redact.error }; const threadRedact = redact.value; @@ -375,9 +389,14 @@ export async function capturePostsAction( const pages = isWaybackPagesChannel(config); if (pages && avatarsOnly) return { ok: false, error: avatarsOnlyProblem(undefined, "a Wayback pages channel")! }; if (pages && contextOnly) return { ok: false, error: contextOnlyProblem(undefined, "a Wayback pages channel", { avatarsOnly })! }; + // An X trending library is captured one directory down, by X's fetcher + // (controller/capturePosts.ts says why). + const library = isXTrendingChannel(config); if (!pages) { await registerBuiltinSocialFetchers(); - const fetcher = resolveSocialFetcher(config.postFetcher, config.url); + const fetcher = library + ? (getSocialFetcher(config.postFetcher) ?? getSocialFetcher(X_LIBRARY_FETCHER)) + : resolveSocialFetcher(config.postFetcher, config.url); const problem = capturePostsProblem(fetcher); if (problem) return { ok: false, error: problem }; const nope = avatarsOnly ? avatarsOnlyProblem(fetcher?.platform, fetcher?.label ?? "") : null; @@ -387,9 +406,25 @@ export async function capturePostsAction( } const stray = strayCaptureIds( wanted, - await readSeenPostIds(path.join(paths.channelsDir, slug)), + library + ? await readXTrendingPostIds(path.join(paths.channelsDir, slug)) + : await readSeenPostIds(path.join(paths.channelsDir, slug)), ); if (stray) return { ok: false, error: strayIdsRefusal(slug, stray) }; + // A LIBRARY'S CAPTURE STAYS ON X'S QUEUE (review 1 S5): its media half is + // paced against every other X job there, and the watch counts on one + // stream. No queue override, named or immediate. + if (library && queueKey !== undefined) { + return { ok: false, error: `${slug} is an X trending library: its captures run on X's queue only ("queueKey" is refused).` }; + } + if (keptMedia) { + if (!library) return { ok: false, error: `"keptMedia" is for an X trending library's kept posts; ${slug} is not a library.` }; + const kept = await readXTrendingKeptIds(path.join(paths.channelsDir, slug)); + const not = wanted.filter((id) => !kept.has(id)); + if (not.length) { + return { ok: false, error: `"keptMedia" is for posts marked keep; not kept: ${not.join(", ")} (judge-trending marks them).` }; + } + } const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey); return runManagedFunction({ @@ -408,6 +443,8 @@ export async function capturePostsAction( ...(avatarsOnly ? { avatarsOnly } : {}), ...(context !== undefined ? { context } : {}), ...(contextOnly ? { contextOnly } : {}), + ...(keptMedia ? { keptMedia } : {}), + ...(watch ? { watch } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -421,7 +458,44 @@ export async function capturePostsAction( 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); + // A WATCH'S CAPTURE ASKS THE WATCH'S JAR RULE NOW, at its start: it may + // have waited its turn on X's queue long past the jar's limit, and the + // guard above lets through what a watch must not (a cookie-age setting + // of 0, the browser as login source). Refused: nothing is opened or + // fetched, and the library's watches pause. + if (watch && library) { + const refusal = await refuseWatchJob(paths, slug); + if (refusal) throw new Error(`This capture was queued by a watch and did not start: ${refusal.sentence}`); + } + // UNDER THE E2E TEST SERVER a library's capture never reaches X or its + // CDN: the fake profile browser, the played-back CDN, and no logged-in + // download (social/fakeXProfileBrowser.ts). + const testServer = process.env.E2E_TEST_ROUTES === "1"; + const fakeChromium = library ? fakeXProfileChromium(paths.transcriptsDir) : null; + const fakeFetch = library ? fakeXMediaFetch(paths.transcriptsDir) : null; + if (library && testServer && !fakeChromium && shots !== false) { + throw new Error("The test server has no fake X profile browser for this capture: nothing was opened."); + } const result = await capturePosts({ + ...(fakeChromium ? { chromium: fakeChromium } : {}), + ...(library + ? { + libraryMedia: { + fallback: keptMedia && !testServer ? ("login" as const) : ("none" as const), + // KEPT WHEN QUEUED IS NOT KEPT NOW (review 1 M4, review 2 + // N3): the job may start minutes later (X's gap, a queue), + // and the operator may have dropped a post meanwhile. The + // judgements are read again, once per post, before its media: + // only a post STILL kept has no per-file cap and the + // logged-in download; one dropped since is fetched as any + // post is, under the library's cap. + ...(keptMedia + ? { isKept: async (id: string) => (await readXTrendingKeptIds(path.join(paths.channelsDir, slug))).has(id) } + : {}), + ...(fakeFetch ? { deps: { fetch: fakeFetch, pauseMs: () => 20 } } : {}), + }, + } + : {}), paths, slug, settings: getSettings(), diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -29,9 +29,45 @@ import { runXTrendingRead, X_TRENDING_QUEUE, type ReadXTrendingAsk, + type ReadXTrendingResult, } from "yt-dlp-transcript-common/controller/readXTrending"; +import { + noteXTrendingWatchRead, + refuseWatchJob, + runXTrendingWatchScan, + xTrendingWatchFollowUp, + type WatchScanResult, +} from "yt-dlp-transcript-common/controller/xTrendingWatch"; +import { + describeXTrendingWatch, + setXTrendingWatch, + type XTrendingWatch, +} from "yt-dlp-transcript-common/lib/xTrending/watch"; +import { + X_TRENDING_MAX_VIDEO_MB, + X_TRENDING_WATCH_MAX_HOURS, + X_TRENDING_WATCH_MAX_INTERVAL_MINUTES, + X_TRENDING_WATCH_MAX_TOPICS, + X_TRENDING_WATCH_MIN_INTERVAL_MINUTES, + xTrendingWatchMaxTopics, + xTrendingWatchTerms, + type XTrendingConfig, +} from "yt-dlp-transcript-common/lib/xTrending/config"; + import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; +import path from "node:path"; +import { isValidChannelSlug, patchChannelConfig, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { + judgeXTrending, + xTrendingJudgeProblem, + type XTrendingJudgeItem, + type XTrendingJudgeResult, +} from "yt-dlp-transcript-common/lib/xTrending/judgements"; +import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot"; +import { readXTrendingTopics } from "yt-dlp-transcript-common/lib/xTrending/store"; import { safeRevalidate } from "../../lib/safeRevalidate"; +import { capturePostsAction } from "./socialActions"; import { xPressInFlight } from "../../lib/cookieRefreshGuard"; export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<StreamActionResult> { @@ -56,7 +92,8 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream queueKey: X_TRENDING_QUEUE, paths, channelSlug: plan.slug, - fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog })), + // Asked again inside the job: the read may have started since the plan. + fn: async (onLog) => done(onLog, await reparseXTrendingRead({ plan, onLog, readInFlight })), }); } const busy = xPressInFlight(); @@ -70,19 +107,246 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream queueKey: X_TRENDING_QUEUE, paths, channelSlug: plan.slug, - fn: async (onLog, signal) => - done( + fn: async (onLog, signal) => { + const result = await runXTrendingRead({ + paths, + plan, onLog, - await runXTrendingRead({ - paths, - plan, - onLog, - signal, - deps: { - profileBusy: () => xPressInFlight(), - ...(chromium ? { chromium, pauseMs: () => 50 } : {}), - }, - }), - ), + signal, + deps: { + profileBusy: () => xPressInFlight(), + // A watch's tick asks the watch's own jar rule again, now, at its + // start (review 2 N1): it may have waited its turn for a long time. + ...(plan.watch ? { watchRefusal: () => refuseWatchJob(paths, plan.slug) } : {}), + ...(chromium ? { chromium, pauseMs: () => 50 } : {}), + }, + }); + // A tick the watch's rule refused was not a read: the watch is paused + // (refuseWatchJob), and it is no strike against it. + if (!result.watchRefused) { + await afterXTrendingRead(plan.slug, plan.channelRoot, result, onLog).catch((err) => + onLog(`The watch could not be told of this read: ${(err as Error).message}`), + ); + } + done(onLog, result); + }, + }); +} + +// THE END OF A READ, FOR THE WATCH (controller/xTrendingWatch.ts): a page X +// retired is not read again, and ends its topic's watch when it was the last; +// and a read into a WATCHED topic queues ONE capture for its new posts — +// their media at once, from the CDN (no page is opened), and a screenshot +// too when the topic says so — and for what an earlier capture left owed. +async function afterXTrendingRead( + slug: string, + channelRoot: string, + result: ReadXTrendingResult, + onLog: (line: string) => void, +): Promise<void> { + const told = await noteXTrendingWatchRead(channelRoot, { trendId: result.trendId, outcome: result.outcome, sentence: result.sentence }); + if (told) onLog(told); + if (result.outcome !== "read" || !result.topic) return; + const follow = await xTrendingWatchFollowUp(channelRoot, { topic: result.topic.id, newIds: result.newIds ?? [] }); + if (!follow) return; + const what = + `${follow.fresh} new post${follow.fresh === 1 ? "" : "s"}` + + (follow.owed ? ` and ${follow.owed} owed from an earlier capture` : "") + + (follow.uncaptured ? ` and ${follow.uncaptured} never captured` : "") + + ` of the watched topic "${result.topic.title}"`; + // THE CAPTURE IS THE WATCH'S JOB TOO (review 2 N1): the watch's jar rule is + // asked before it is queued, and again inside the job when it starts + // (`watch: true`) — with "screenshot everything new" it opens pages on X. + const refusal = await refuseWatchJob(getPaths(), slug); + if (refusal) { + onLog(`The media of ${what} was not queued, and the watch is paused: ${refusal.sentence}`); + return; + } + const started = await capturePostsAction(slug, follow.ids, undefined, follow.shots, true, false, false, { + // Media only: no page is opened for the avatars or the context either. + ...(follow.shots ? {} : { avatars: false, context: false }), + watch: true, + }); + if (started.ok) { + void started.stream.cancel(); + onLog(`Queued capture ${started.jobId} for ${what}: their media${follow.shots ? " and a screenshot of each" : ""}.`); + } else { + onLog(`The media of ${what} was not queued: ${started.error}`); + } +} + +// A library's root on disk, or the refusal's sentence. +async function libraryRoot(slug: string): Promise<{ ok: true; channelRoot: string } | { ok: false; error: string }> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${String(slug)}" is not a valid channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXTrendingChannel(config)) return { ok: false, error: NOT_AN_X_TRENDING_LIBRARY(slug) }; + return { ok: true, channelRoot: path.join(paths.channelsDir, slug) }; +} + +export type JudgeXTrendingAsk = { + slug: string; + // Who decided: the channel page's buttons say "operator"; `pnpm ops + // judge-trending` says "agent" unless told otherwise. + by: unknown; + set: unknown; + // false: mark only; the posts that became keep are not archived now. + archive?: boolean; +}; + +// What became of archiving the posts that became keep: the capture job, or +// why none was started (the judgements are written all the same). +export type JudgeArchive = { jobId: string; ids: string[] } | { error: string; ids: string[] }; + +export type JudgeXTrendingActionResult = + | ({ ok: true; slug: string; archive?: JudgeArchive } & XTrendingJudgeResult) + | { ok: false; error: string }; + +// JUDGE POSTS OF A LIBRARY (lane x-trending-2): keep / drop / later, or +// undecided (the judgement removed), per post or per thread — the channel +// page's buttons and `pnpm ops judge-trending`, one writer +// (lib/xTrending/judgements.ts). An agent's write over the operator's +// judgement is skipped for that id and reported. +export async function judgeXTrendingAction(ask: JudgeXTrendingAsk): Promise<JudgeXTrendingActionResult> { + const lib = await libraryRoot(ask.slug); + if (!lib.ok) return lib; + const problem = xTrendingJudgeProblem(ask); + if (problem) return { ok: false, error: problem }; + const result = await judgeXTrending(lib.channelRoot, { + by: ask.by as "agent" | "operator", + set: ask.set as XTrendingJudgeItem[], + }); + safeRevalidate([`/channels/${ask.slug}`]); + // A KEEP ARCHIVES: the posts that became keep go into ONE capture-posts job + // on X's queue — a screenshot, the context, a reply's thread shot, and the + // media (from the CDN, no cap, the logged-in download as the fallback). A + // refusal (a stale jar, the X alert, X cooling down) leaves the judgements + // written and says why nothing was started. + let archive: JudgeArchive | undefined; + if (result.kept.length > 0 && ask.archive !== false) { + const started = await capturePostsAction(ask.slug, result.kept, undefined, true, true, false, true, { + thread: true, + keptMedia: true, + }); + if (started.ok) { + void started.stream.cancel(); + archive = { jobId: started.jobId, ids: result.kept }; + } else { + archive = { error: started.error, ids: result.kept }; + } + } + return { ok: true, slug: ask.slug, ...result, ...(archive ? { archive } : {}) }; +} + +// ── the watch ────────────────────────────────────────────────────────────── + +export type WatchSettingsAsk = { maxVideoMb?: unknown; intervalMinutes?: unknown; hours?: unknown; maxTopics?: unknown }; + +export type WatchXTrendingAsk = { + slug: string; + // One scan now (what the timer does every minute). + tick?: boolean; + // The library's defaults, changed. + settings?: WatchSettingsAsk; + // The switch of one topic. + topic?: string; + on?: boolean; + intervalMinutes?: unknown; + hours?: unknown; + shots?: boolean; + by?: unknown; +}; + +export type WatchXTrendingResult = + | { ok: true; slug: string; topic?: string; watch?: XTrendingWatch; sentence: string; scan?: WatchScanResult; settings?: XTrendingConfig } + | { ok: false; error: string }; + +const WATCH_ONE_OF = `Give "topic" with "on" (the switch of one topic), "settings" (the library's defaults) or "tick": true (one scan now), one of them.`; + +function settingsPatch(ask: WatchSettingsAsk): { ok: true; patch: Partial<XTrendingConfig> } | { ok: false; error: string } { + const patch: Partial<XTrendingConfig> = {}; + const int = (v: unknown, min: number, max: number, what: string): number | string => + typeof v === "number" && Number.isInteger(v) && v >= min && v <= max ? v : `"${what}" is a whole number, ${min}–${max}`; + const unknown = Object.keys(ask).filter((k) => !["maxVideoMb", "intervalMinutes", "hours", "maxTopics"].includes(k)); + if (unknown.length) return { ok: false, error: `unknown setting(s): ${unknown.join(", ")} (maxVideoMb, intervalMinutes, hours, maxTopics)` }; + for (const [key, to, min, max] of [ + ["maxVideoMb", "maxVideoMb", 1, X_TRENDING_MAX_VIDEO_MB], + ["intervalMinutes", "watchIntervalMinutes", X_TRENDING_WATCH_MIN_INTERVAL_MINUTES, X_TRENDING_WATCH_MAX_INTERVAL_MINUTES], + ["hours", "watchHours", 1, X_TRENDING_WATCH_MAX_HOURS], + ["maxTopics", "watchMaxTopics", 1, X_TRENDING_WATCH_MAX_TOPICS], + ] as const) { + const v = ask[key]; + if (v === undefined) continue; + const n = int(v, min, max, key); + if (typeof n === "string") return { ok: false, error: n }; + patch[to] = n; + } + if (Object.keys(patch).length === 0) return { ok: false, error: `"settings" names nothing to change (maxVideoMb, intervalMinutes, hours, maxTopics)` }; + return { ok: true, patch }; +} + +// WATCH A TOPIC (lane x-trending-2): the channel page's switch and `pnpm ops +// watch-trending`. While a topic is watched its trending page is read again +// every `intervalMinutes` until `hours` from now — each tick the same single +// read-x-trending job, started by the scan (controller/xTrendingWatch.ts). +// A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS FRESH: it pauses when the jar +// passes its limit and resumes at the first scan after Refresh cookies. +export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<WatchXTrendingResult> { + const lib = await libraryRoot(ask.slug); + if (!lib.ok) return lib; + const paths = getPaths(); + const asked = [ask.tick === true, ask.settings !== undefined, ask.topic !== undefined].filter(Boolean).length; + if (asked !== 1) return { ok: false, error: WATCH_ONE_OF }; + if (ask.tick) { + // The armed scan when there is one (one scan at a time); else one of its own. + // AN IDLE BOOT STARTS NO WORK (review 1 S6): the scan is not armed + // there, and asking for one by hand is refused too. + if (isIdleBoot()) { + return { ok: false, error: "This editor booted idle (ARCHILYZER_IDLE_BOOT): it starts no work, so no watch scan runs. Restart it without the switch to watch topics." }; + } + // One scan at a time, the armed timer's included: two asks are one scan. + const { xTrendingWatchDeps } = await import("../../api/ops/_xTrendingWatch"); + const scan = await runXTrendingWatchScan(xTrendingWatchDeps); + safeRevalidate([`/channels/${ask.slug}`, "/review"]); + const sentence = scan.enqueued + ? `Scanned: a tick of "${scan.enqueued.topic}" (${scan.enqueued.slug}) was started, job ${scan.enqueued.jobId}.` + : scan.refused + ? `Scanned: the tick of "${scan.refused.topic}" was refused: ${scan.refused.error}` + : `Scanned: ${scan.live} live watch${scan.live === 1 ? "" : "es"}, no tick started` + + (scan.paused.length ? ` (${scan.paused.length} paused)` : "") + + "."; + return { ok: true, slug: ask.slug, scan, sentence }; + } + if (ask.settings !== undefined) { + if (!ask.settings || typeof ask.settings !== "object" || Array.isArray(ask.settings)) { + return { ok: false, error: `"settings" is an object: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?}` }; + } + const parsed = settingsPatch(ask.settings); + if (!parsed.ok) return parsed; + const next = await patchChannelConfig(paths, ask.slug, {}, { derive: (current) => ({ xTrending: { ...current.xTrending, ...parsed.patch } }) }); + safeRevalidate([`/channels/${ask.slug}`]); + const settings = next?.xTrending ?? {}; + return { ok: true, slug: ask.slug, settings, sentence: `Saved: ${JSON.stringify(parsed.patch)}.` }; + } + if (typeof ask.on !== "boolean") return { ok: false, error: `"on" is true (watch the topic) or false (stop watching it)` }; + if (ask.by !== undefined && ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; + const config = (await readChannelConfig(paths, ask.slug))?.xTrending; + const terms = xTrendingWatchTerms(config, ask.on ? { intervalMinutes: ask.intervalMinutes, hours: ask.hours } : {}); + if (!terms.ok) return terms; + const now = Date.now(); + const set = await setXTrendingWatch(lib.channelRoot, { + topics: await readXTrendingTopics(lib.channelRoot), + topic: String(ask.topic), + on: ask.on, + intervalMinutes: terms.terms.intervalMinutes, + hours: terms.terms.hours, + ...(ask.shots !== undefined ? { shots: ask.shots } : {}), + by: ask.by === "operator" ? "operator" : "agent", + maxTopics: xTrendingWatchMaxTopics(config), + now, }); + if (!set.ok) return set; + safeRevalidate([`/channels/${ask.slug}`, "/review"]); + return { ok: true, slug: ask.slug, topic: set.topic, watch: set.watch, sentence: describeXTrendingWatch(set.watch, now) }; } diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -484,6 +484,9 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { avatarsOnly: bool(p.avatarsOnly), context: bool(p.context), contextOnly: bool(p.contextOnly), + keptMedia: bool(p.keptMedia), + // A watch's capture stays a watch's when it is re-run or resumed. + watch: bool(p.watch), }, ); }, diff --git a/editor/app/review/lib/loadReview.ts b/editor/app/review/lib/loadReview.ts @@ -16,7 +16,9 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { autoPausedRows, type AutoPausedRow, + type PausedWatchRow, } from "yt-dlp-transcript-common/views/review"; +import { pausedXTrendingWatches } from "yt-dlp-transcript-common/controller/xTrendingWatch"; import { getDuplicateReport } from "../../lib/requestCache"; // The half of the old actionable summary that is a HUMAN judgement rather than @@ -53,15 +55,21 @@ export type ReviewSummary = { // reading it costs nothing (getSettings is memoized and every other page on // this render already called it). autoPaused: AutoPausedRow[]; + // WATCHES OF X TRENDING TOPICS THAT ARE PAUSED (lane x-trending-2): a watch + // runs only while X's cookie jar is fresh, and only a person refreshes it. + // Read from each library's own watch.json (a library is in no index). + pausedWatches: PausedWatchRow[]; }; export async function loadReviewSummary(paths: Paths): Promise<ReviewSummary> { - const [duplicates, duplicateOverrides, mediaScan, mediaScanOverrides] = + const [duplicates, duplicateOverrides, mediaScan, mediaScanOverrides, pausedWatches] = await Promise.all([ getDuplicateReport(paths), readDuplicateOverrides(paths), readMediaScanReport(paths), readMediaScanOverrides(paths), + // A library that cannot be read must not take the page down. + pausedXTrendingWatches(paths).catch(() => []), ]); return { duplicates, @@ -69,5 +77,6 @@ export async function loadReviewSummary(paths: Paths): Promise<ReviewSummary> { mediaScan, mediaScanOverrides, autoPaused: autoPausedRows(getSettings().channelPriority), + pausedWatches, }; } diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx @@ -13,7 +13,7 @@ import type { DuplicateOverrides, DuplicateReport, } from "yt-dlp-transcript-common/lib/duplicates"; -import type { AutoPausedRow } from "yt-dlp-transcript-common/views/review"; +import type { AutoPausedRow, PausedWatchRow } from "yt-dlp-transcript-common/views/review"; import { loadReviewSummary } from "./lib/loadReview"; import { ResumeAutoPausedButton } from "./components/ResumeAutoPausedButton"; import { RunDuplicateDetectionButton } from "./components/RunDuplicateDetectionButton"; @@ -46,6 +46,7 @@ export default async function ReviewPage() { <div className="flex flex-col gap-6"> <h1 className="text-2xl font-semibold">Review</h1> <AutoPausedSection rows={review.autoPaused} /> + <PausedWatchesSection rows={review.pausedWatches} /> <XRunConsole initial={xRun} /> <DuplicatesSection report={review.duplicates} @@ -59,6 +60,58 @@ export default async function ReviewPage() { ); } +// WATCHES OF X TRENDING TOPICS THAT ARE PAUSED (lane x-trending-2). +// +// A watch reads a topic's trending page every so often — but only while X's +// cookie jar is under its limit, and the editor never refreshes that jar by +// itself (a refresh loads X). So a watch someone switched on stops reading +// the moment the jar goes stale, and what starts it again is a person's press +// on /cookies. That is a thing waiting on a human, which is what this page +// lists; the dashboard's X banner says the jar is stale, this says what is +// not being read because of it. +// +// RENDERED ONLY WHEN THERE IS SOMETHING TO SAY, like the section below it. +function PausedWatchesSection({ rows }: { rows: PausedWatchRow[] }) { + if (rows.length === 0) return null; + const when = (iso: string) => iso.slice(0, 16).replace("T", " "); + return ( + <section aria-label="paused watches" className="flex flex-col gap-2"> + <div className="flex items-center justify-between flex-wrap gap-2"> + <h2 className="text-lg font-semibold">Paused watches ({rows.length})</h2> + <Link href="/cookies" className="text-sm underline hover:text-foreground"> + Cookies + </Link> + </div> + <ul className="flex flex-col gap-2"> + {rows.map((row) => ( + <li + key={`${row.slug}/${row.topic}`} + aria-label={`paused watch ${row.slug} ${row.topic}`} + className="border border-border rounded-md p-3 flex flex-col gap-1 text-sm" + > + <div className="flex items-center gap-2 flex-wrap"> + <Link href={`/channels/${row.slug}`} className="font-medium underline hover:text-foreground"> + {row.title} + </Link> + <span className="text-muted-foreground"> + {row.slug} · paused since {when(row.since)} UTC · the watch ends {when(row.until)} UTC + </span> + </div> + <span>{row.sentence}</span> + <span className="text-xs text-muted-foreground"> + {row.reason === "jar" + ? "It resumes by itself at the first scan after Refresh cookies on /cookies. Nothing is read while it is paused." + : row.reason === "failing" + ? "It does not resume by itself: press Watch on the topic again once the reads can succeed. Nothing is read while it is paused." + : "It resumes by itself at the first scan that finds this gone. Nothing is read while it is paused."} + </span> + </li> + ))} + </ul> + </section> + ); +} + // CHANNELS THE MACHINE PAUSED WHILE NOBODY WAS LOOKING. // // The storage watch forces a channel to `paused` when the drive its media is on diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -13,12 +13,19 @@ // 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 { mkdir, readFile, readdir, stat, 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"; +import { + FIXTURE_FIRST_PAGE, + FIXTURE_TIMELINE_OP, + FIXTURE_TREND_URL, + fixtureContinuation, + fixtureTimelineBody, + fixtureTrendingResponses, +} from "../../common/social/__fixtures__/xTrendingCapture"; const TOKEN = "test-worker-token"; const AUTH = { authorization: `Bearer ${TOKEN}` }; @@ -173,3 +180,134 @@ test("an X trending library: the form, one read, the library by topic, the listi expect(await pathExists(rel(`channels/${SLUG}/posts`))).toBe(false); expect(await pathExists(rel(`channels/${SLUG}/posts-archive`))).toBe(false); }); + +// LANE x-trending-2: judge, watch, media kept once, gone from the page, and +// the jar rule pausing the watch. Still no browser and no request to X or to +// its media CDN: the fake page and the played-back CDN +// (common/social/fakeXProfileBrowser.ts fakeXMediaFetch) answer everything. +test("an X trending library: judgements, a watch tick, media kept once, gone from the page, a stale jar pauses the watch", async ({ page, request }) => { + test.setTimeout(180_000); + await seed(); + const post = async (action: string, data: Record<string, unknown>) => { + const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); + return { status: res.status(), json: (await res.json()) as Record<string, unknown> }; + }; + const listing = async () => + (await (await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}`, { headers: AUTH })).json()) as { + topics: { id: string; watch?: { on: boolean; ticks: number; paused?: { reason: string }; sentence: string } }[]; + posts: { id: string; gone?: { at: string }; capture?: { files: number; mediaState: string }; judgement?: { state: string; by: string } }[]; + }; + const made = await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } }); + expect(made.status, JSON.stringify(made.json)).toBe(200); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); + await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); + + // JUDGE. An agent keeps one (marking only); the operator drops another on the page. + const A = "1900000000000001001"; + const B = "1900000000000001002"; + const kept = await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: A, state: "keep", note: "the opening" }] }); + expect(kept.json).toMatchObject({ ok: true, written: [{ id: A, state: "keep" }], skipped: [], kept: [A] }); + await generateReport(page, SLUG); + await page.goto(`/channels/${SLUG}`); + const topic = page.locator('[data-x-trending-topic="kettle-festival"]'); + await expect(topic.locator(`[data-x-trending-post="${A}"] [data-x-trending-judgement="keep"]`)).toContainText("keep by agent: the opening"); + await page.getByRole("button", { name: `Drop ${B}`, exact: true }).click(); + // (The page re-renders after the action: allow it more than the default wait.) + await expect(topic.locator(`[data-x-trending-post="${B}"] [data-x-trending-judgement="drop"]`)).toContainText("drop by operator", { timeout: 30_000 }); + // An agent's judgement never replaces the operator's. + const over = await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: B, state: "keep" }] }); + expect(over.json).toMatchObject({ written: [], skipped: [{ id: B, reason: "judged by the operator: an agent's judgement does not replace it" }] }); + expect((await readJson<{ posts: Record<string, { state: string; by: string }> }>(rel(`channels/${SLUG}/trending/judgements.json`))).posts[B]).toMatchObject({ state: "drop", by: "operator" }); + + // WATCH the topic, from the page. + await topic.getByRole("button", { name: "Watch", exact: true }).click(); + await expect(topic.locator("[data-x-trending-watch-state]")).toContainText("Watched every 30 min until", { timeout: 30_000 }); + await expect(topic).toContainText("it does not cover a night nobody refreshes in"); + expect((await listing()).topics[0].watch).toMatchObject({ on: true, ticks: 0 }); + + // The page has changed: the opening post and a NEW one with two pictures; the rest are no longer shown. + const NEW = "1900000000000001006"; + const picture = (i: number) => `https://pbs.twimg.com/media/Fixture1006${i}?format=jpg&name=orig`; + await writeFile( + t(".fake-x-profile-cookies.json"), + JSON.stringify({ + cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], + trending: { + load: [ + { + url: `https://x.com/i/api/graphql/fixtureQueryId2/${FIXTURE_TIMELINE_OP}?variables=%7B%7D`, + status: 200, + body: fixtureTimelineBody([FIXTURE_FIRST_PAGE[0], { id: NEW, handle: "spout_clips", text: "Two pictures of the queue.", media: ["photo", "photo"] }]), + }, + ], + // Asked for more, the timeline has none: the page's end, which is what lets a read say "gone". + scrolls: [[fixtureContinuation()], []], + }, + // The same bytes at both addresses: one file in the library. (The opening + // post's two pictures, never captured, are taken by the same job.) + media: { + [picture(0)]: { text: "FIXTURE PICTURE BYTES" }, + [picture(1)]: { text: "FIXTURE PICTURE BYTES" }, + "https://pbs.twimg.com/media/Fixture10010?format=jpg&name=orig": { text: "OPENING PICTURE ONE" }, + "https://pbs.twimg.com/media/Fixture10011?format=jpg&name=orig": { text: "OPENING PICTURE TWO" }, + }, + }), + ); + + // ONE SCAN (what the timer does once a minute; not armed on the test server): one read is started. + const tick = await post("watch-trending", { slug: SLUG, tick: true }); + expect(tick.status, JSON.stringify(tick.json)).toBe(200); + expect(tick.json.scan).toMatchObject({ live: 1, enqueued: { slug: SLUG, topic: "kettle-festival", url: FIXTURE_TREND_URL }, paused: [] }); + await expect.poll(archiveLines, { timeout: 60_000 }).toBe(5); + // A second scan at once starts nothing: the next tick is an interval away. + expect(((await post("watch-trending", { slug: SLUG, tick: true })).json.scan as { enqueued?: unknown }).enqueued).toBeUndefined(); + + // The new post's MEDIA came at once, from the (played-back) CDN, and is kept once. + const dir = t(`channels/${SLUG}/trending/posts-media/${NEW}`); + await expect.poll(async () => (await readdir(dir).catch(() => [] as string[])).sort(), { timeout: 60_000 }).toEqual([`${NEW}_1.jpg`, `${NEW}_2.jpg`, "capture.json"]); + expect(await readFile(`${dir}/${NEW}_1.jpg`, "utf8")).toBe("FIXTURE PICTURE BYTES"); + expect((await stat(`${dir}/${NEW}_1.jpg`)).ino).toBe((await stat(`${dir}/${NEW}_2.jpg`)).ino); + const index = await readJson<{ blobs: Record<string, { posts: Record<string, string[]>; urls: string[] }> }>(rel(`channels/${SLUG}/trending/media-index.json`)); + const blobOfNew = Object.values(index.blobs).filter((b) => b.posts[NEW]); + expect(blobOfNew).toHaveLength(1); + expect(blobOfNew[0].posts).toEqual({ [NEW]: [`${NEW}_1.jpg`, `${NEW}_2.jpg`] }); + // A post of the watched topic that has media and was never captured is taken by the same job. + await expect.poll(async () => (await readdir(t(`channels/${SLUG}/trending/posts-media/${A}`)).catch(() => [] as string[])).sort(), { timeout: 60_000 }).toEqual([`${A}_1.jpg`, `${A}_2.jpg`, "capture.json"]); + // Never committed, and never where a posts channel keeps its captures. + expect(await readFile(t(`channels/${SLUG}/trending/.gitignore`), "utf8")).toMatch(/^posts-media\/$/m); + expect(await pathExists(rel(`channels/${SLUG}/posts-media`))).toBe(false); + + // GONE FROM THE PAGE: the three posts the page stopped showing, said so, never "deleted". + const after = await listing(); + expect(after.posts.filter((p) => p.gone).map((p) => p.id).sort()).toEqual([B, "1900000000000001004", "1900000000000001005"]); + expect(after.posts.find((p) => p.id === NEW)?.capture).toMatchObject({ files: 2, mediaState: "ok" }); + expect(after.topics[0].watch).toMatchObject({ on: true, ticks: 1 }); + await page.reload(); + await expect(topic.locator(`[data-x-trending-post="${B}"] [data-x-trending-gone]`)).toContainText("Gone from the page at"); + await expect(topic.locator(`[data-x-trending-post="${A}"] [data-x-trending-gone]`)).toHaveCount(0); + await expect(page.locator("body")).not.toContainText(/deleted/i); + + // THE JAR RULE: past its limit the watch PAUSES (nothing is enqueued, nothing refreshes the jar), and /review says so. + const old = new Date(Date.now() - 2 * 60 * 60_000); + await utimes(t(".x-session/cookies.txt"), old, old); + const paused = await post("watch-trending", { slug: SLUG, tick: true }); + expect(paused.json.scan).toMatchObject({ paused: [{ slug: SLUG, topic: "kettle-festival", reason: "jar" }] }); + expect((paused.json.scan as { enqueued?: unknown }).enqueued).toBeUndefined(); + expect((await listing()).topics[0].watch?.sentence).toMatch(/PAUSED since .* UTC: X cookies were last refreshed 2 h ago \(limit 60 min for a watch\)/); + expect((await stat(t(".x-session/cookies.txt"))).mtimeMs).toBeLessThan(Date.now() - 60 * 60_000); + await page.goto("/review"); + const section = page.getByRole("region", { name: "paused watches" }); + await expect(section).toContainText("Paused watches (1)"); + await expect(section).toContainText("Kettle Festival"); + await expect(section).toContainText("It resumes by itself at the first scan after Refresh cookies on /cookies."); + // "Refreshed" (the jar written now): the first scan after it resumes the watch. + const now = new Date(); + await utimes(t(".x-session/cookies.txt"), now, now); + const resumed = await post("watch-trending", { slug: SLUG, tick: true }); + expect(resumed.json.scan).toMatchObject({ resumed: [{ slug: SLUG, topic: "kettle-festival" }], paused: [] }); + await page.reload(); + await expect(page.getByRole("region", { name: "paused watches" })).toHaveCount(0); + // Stop watching. + const off = await post("watch-trending", { slug: SLUG, topic: "kettle-festival", on: false, by: "operator" }); + expect(off.json.sentence).toBe('The watch of "Kettle Festival" was switched off.'); +}); diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -336,6 +336,21 @@ export async function register() { /* auto-continue that fails to arm must not block server readiness */ } + // THE WATCH OF X TRENDING LIBRARIES (lane x-trending-2): a scan every + // minute, at most ONE read-x-trending job per scan, for the topics someone + // switched a watch on for. Below the idle gate — a tick is a request to X — + // and not on the e2e test server, whose spec drives a scan by hand + // (`watch-trending {"tick": true}`). It never refreshes X's cookie jar: on a + // stale jar the watches pause. See common/controller/xTrendingWatch.ts. + if (process.env.E2E_TEST_ROUTES !== "1") { + try { + const { armXTrendingWatchLane } = await import("./app/api/ops/_xTrendingWatch"); + armXTrendingWatchLane(); + } catch { + /* a watch that fails to arm must not block server readiness */ + } + } + // THE RECURRING REPORTS (umtool R5): the report-schedule lane — a scan now // and every minute, ONE report-tick job per due schedule, held by its pause // gate. Below the idle gate: a tick is generation work. diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -127,3 +127,39 @@ test("with no editor configured, the tools say what is missing and ask nothing", assert.ok(isError(res)); assert.equal(sent.length, 0); }); + +// Lane x-trending-2: what a watch, a capture, a thread's judgement and a page +// that stopped showing a post look like to the agent. +test("the tools say a topic's watch, and a post's thread, capture, gone-from-the-page mark and thread judgement", async () => { + const listing = { + ...LISTING, + topics: [ + { + ...LISTING.topics[0], + watch: { on: true, paused: { reason: "jar" }, sentence: "Watched every 30 min until 2026-11-20 10:00 UTC — PAUSED since 2026-11-18 11:00 UTC: X cookies were last refreshed 61 min ago (limit 60 min)." }, + }, + ], + posts: [ + { + ...LISTING.posts[0], + thread: "1900000000000000999", + gone: { at: "2026-11-18T10:30:00.000Z", read: READ, trendId: "1900000000000000001" }, + capture: { at: "2026-11-18T10:05:00.000Z", state: "captured", shot: false, files: 1, mediaState: "error", mediaOwed: "kept" }, + judgement: { state: "keep", by: "operator", at: "2026-11-18T09:00:00.000Z", from: "thread" }, + }, + ], + total: 1, + }; + const { deps } = fakeEditor(() => ({ status: 200, body: listing }), env); + const client = await connectWith(deps); + const topics = body(await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } })); + assert.match(topics, /^ {4}watch: Watched every 30 min until 2026-11-20 10:00 UTC — PAUSED since 2026-11-18 11:00 UTC: X cookies were last refreshed 61 min ago/m); + const posts = body(await client.callTool({ name: "x_trending_posts", arguments: { channel: "trending" } })); + assert.deepEqual(posts.split("\n").slice(4), [ + ` shown by: ${READ} (2026-11-17 10:00 UTC)`, + " in thread 1900000000000000999", + ` gone from the page at 2026-11-18 10:30 UTC (read ${READ}; the page stopped showing it, which is not "deleted")`, + " captured 2026-11-18 10:05 UTC: captured, 1 media file; more media owed once it is kept", + " judged keep by operator (its thread) (2026-11-18 09:00 UTC)", + ]); +}); diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -14,7 +14,9 @@ import type { ToolAnswer } from "./archivalTools"; // // 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). +// jar — `pnpm ops get x-session` says whether one would start). Judging a post +// (`judge-trending`) and watching a topic (`watch-trending`) are asks of the +// editor too; these tools only show what they left (lane x-trending-2). const SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/i; export const X_TRENDING_POSTS_MAX = 500; @@ -24,6 +26,8 @@ type Topic = { title: string; posts: number; sources?: Array<{ trendId: string; url: string; title?: string; summary?: string; reads: number; lastReadAt: string | null }>; + // The topic's watch, once it has been watched; `sentence` says what it is doing. + watch?: { on: boolean; sentence: string; paused?: { reason: string }; ended?: { reason: string } }; }; type PostRow = { @@ -36,7 +40,11 @@ type PostRow = { 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 }; + judgement?: { state: string; note?: string; by: string; at: string; from?: string }; + thread?: string; + // A page that showed it before did not show it at `at` (never "deleted"). + gone?: { at: string; read: string; trendId: string }; + capture?: { at: string; state: string; shot: boolean; files: number; mediaState: string; mediaOwed?: string }; }; type ListingBody = { name?: string; topics?: Topic[]; posts?: PostRow[]; total?: number; reads?: string[] }; @@ -53,6 +61,7 @@ export function renderXTrendingTopics(slug: string, body: ListingBody): string { 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 (t.watch) lines.push(` watch: ${t.watch.sentence}`); } if (body.reads?.length) lines.push(`Saved reads (newest first): ${body.reads.join(", ")}`); return lines.join("\n"); @@ -76,9 +85,19 @@ export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: st 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.thread && p.thread !== p.id) lines.push(` in thread ${p.thread}`); + if (p.gone) lines.push(` gone from the page at ${day(p.gone.at)} UTC (read ${p.gone.read}; the page stopped showing it, which is not "deleted")`); + if (p.capture) { + const owed = p.capture.mediaOwed === "kept" ? "; more media owed once it is kept" : p.capture.mediaOwed === "next" ? "; more media owed to the next capture" : ""; + lines.push( + ` captured ${day(p.capture.at)} UTC: ${p.capture.state}${p.capture.shot ? ", shot" : ""}, ${p.capture.files} media file${p.capture.files === 1 ? "" : "s"}${owed}` + + (p.media?.thumbnail ? ` (${p.media.thumbnail})` : ""), + ); + } else 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}` : ""}`); + lines.push( + ` judged ${p.judgement.state} by ${p.judgement.by}${p.judgement.from === "thread" ? " (its thread)" : ""} (${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).`); @@ -133,7 +152,9 @@ export const X_TRENDING_TOOLS = [ 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 " + + "ids of the saved reads; and each topic's WATCH, when it has one — whether it is being " + + "read again on an interval, until when, and why it is paused (a watch runs only while " + + "X's cookie jar is fresh, so a stale jar pauses it until the operator refreshes). 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.", @@ -151,7 +172,10 @@ export const X_TRENDING_TOOLS = [ 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 " + + "it has them — the thread it belongs to, what its capture holds (and what media it is " + + "still owed), its judgement (keep / drop / later; none is undecided; its own, or its " + + "thread's), and whether a page stopped showing it (\"gone from the page at <time>\": a " + + "trending page is a ranked list, so this is NOT a claim the post was deleted) — 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. " + diff --git a/mcp/src/xTrendingPrivacy.test.ts b/mcp/src/xTrendingPrivacy.test.ts @@ -41,7 +41,7 @@ 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 { recordXTrendingRead, writeXTrendingPosts, trendingReadDir, readXTrendingTopics } = await import("yt-dlp-transcript-common/lib/xTrending/store"); const { createCorpusTools } = await import("./callTool"); const paths = getPaths(); @@ -50,7 +50,10 @@ 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 { plantSlice2Library, SLICE2_MARK_LIST } = await import("yt-dlp-transcript-common/lib/xTrending/__fixtures__/slice2Library"); +// The last five are lane x-trending-2's: a judgement's note, a captured media +// file's bytes and address, the capture's context, the shot. +const MARKS = ["trendpostmarkerq7x", "trendhandlemarkerz4k", "trendtopicmarkerw2p", "trendrawmarkerj9m", ...SLICE2_MARK_LIST]; const READ = "tr-01JA0000000000000000000000"; const writeJson = (file: string, value: unknown) => { @@ -98,6 +101,8 @@ await recordXTrendingRead(libRoot, { }); 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`); +// What a keep, a capture and a watch leave (lane x-trending-2). +await plantSlice2Library(libRoot, { postId: LIB_ID, topicId: (await readXTrendingTopics(libRoot))[0].id }); // 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: "", @@ -148,6 +153,9 @@ test("every read-only corpus tool over the composed site: the account's post, ne assert.ok(!text.includes(mark), `${tool}: answers with ${mark}`); } assert.ok(!text.includes("responses.jsonl") && !text.includes(READ), `${tool}: names a raw capture`); + for (const name of ["judgements.json", "media-index.json", "media-store", "watch.json", "posts-media"]) { + assert.ok(!text.includes(name), `${tool}: names ${name}`); + } } // 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"]) { diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -0,0 +1,196 @@ +# X trending pages, in a private library + +Lanes `lane/x-trending` (slice 1, merged 2026-11-17) and `lane/x-trending-2` (slice 2). This is the brief +for the whole feature: what was asked, what is ruled, what slice 1 built, and what slices 2 to 4 are. + +## The ask + +An agent operating Archilyzer (through `pnpm ops` and the MCP, with nobody in the loop if desired) looks +through X's trending pages (`https://x.com/i/trending/<number>`), archives the interesting threads and +their media, stores each piece of media once however many posts or topics carry it, and organises what it +found by topic. The operator then browses and judges the library, and nothing is on any site until a +person publishes it. + +## Rulings + +These are rulings, not reasons. A later ruling overturns an earlier one only when it says so. + +**Privacy** + +- A trending library is PRIVATE: on no site, in no build, export, index shard, `corpus.json`, `llms.txt` + or remote MCP surface, until a deliberate publish step. Every publishing door refuses it by its marker. +- No real person's, channel's or the operator's name or handle, no hostname, home path or real trending + id, in code, fixtures, tests, docs or commit messages. Fixtures are invented. +- The raw capture of a read is never committed and never served. + +**X safety** + +- All X traffic goes through the editor's X queue (`platform:twitter`), its pace, its hold and backoff, + the X alert and the fresh-jar rule. One trending page read is ONE job. Never a burst. +- A 429 stops the job at once and leaves X alone for 15 minutes: reads, captures, watch ticks and media + fetches all honour that cooldown. Nothing retries by itself. +- Development and tests use fixtures and the fake profile browser only. No test opens a socket. +- The page reader MAY be the connected profile's Playwright browser. It reads the JSON the page itself + fetches, never builds a request of its own, scrolls gently under a cap, and saves the raw capture so + parsing never needs a second read. +- THE JAR RULE STANDS FOR THE WATCH. The editor never refreshes X's cookie jar by itself: a refresh is a + person's press on /cookies. A watch therefore runs only while the jar is under 60 minutes old. It + pauses when the jar goes stale and resumes at the first scan after a Refresh, so **a watch does not + cover the night unattended**. A tick that exports the profile's cookies itself is NOT built, not even + behind a switch. + +**The library** + +- A topic is an entity inside the library, not a channel. The operator's topics may merge several + trending pages and need not carry X's titles. +- A read archives nothing: it lists posts. Media, a screenshot and thread context are fetched for posts + marked keep, and for new posts of a watched topic (media at once; screenshots when the topic says so). +- Every step is an editor job or action with a `pnpm ops` twin, and an MCP read tool where an agent + needs to look. The UI works with no model. +- Curated and corpus files have one writer each. A media file is removed with `removeMediaFile`. + +**Judging** + +- States are `keep | drop | later`. No entry means undecided; clearing a judgement removes the entry. +- A judgement records who decided (`agent` or `operator`) and when, with an optional note. A thread can + be judged too: its key is its root post's id, and a post's effective judgement is its own, else its + thread's. +- An agent's judgement is a suggestion. An agent's write never overrides an operator's: it is skipped + for that id and reported. +- WHICH JUDGEMENT IS IN FORCE is one rule, in one function (`xTrendingEffectiveJudgement`): the + operator's entry, for the post or its thread, always outranks an agent's about the same post, whatever + the order in time; between two entries of the same hand the post's own outranks its thread's. `by` is the caller's word: the ops route cannot tell who asks, so an agent is trusted to say + "agent"; the operator's hand is the page's buttons and slice 3's judge view. +- Drop deletes nothing and is reversible. Purging a dropped post's capture is the operator's press + (slice 3). + +**Media** + +- Stored once, deduplicated by content hash across posts and topics. Exact duplicates only: the same + video at another quality is another file. +- The media CDN addresses already in the saved capture are preferred over logged-in page loads. The + logged-in fallback runs only for posts marked keep. +- Deleting a post never deletes media another post still uses. +- Watch media includes videos up to a per-file cap (100 MB, `config.xTrending.maxVideoMb`); larger ones + are owed until the post is kept. One capture job fetches at most 40 files or 200 MB; the rest is owed. +- A library's media is not in the media tier (no posts channel's `posts-media/` is): it stays on the + corpus disk, beside the library's text. + +**Watch** + +- A per-topic switch with an interval and an end time. Defaults: 30 minutes, 48 hours, at most 4 watched + topics per library. Each tick is the same single read job. +- A post seen before and absent from a read that reached the page's end is recorded as "gone from the + page at <time>". It is never called deleted. A capped, cancelled or failed read asserts nothing. +- A trending page X has retired ends the watch with a sentence. +- The watch has its own scan timer, armed below the idle gate (`ARCHILYZER_IDLE_BOOT` arms nothing, and + refuses a scan asked for by hand). +- THE WATCH'S JAR RULE IS ITS OWN. The exemptions a person's job has (the browser as login source, a + cookie-age setting of 0, settings that cannot be read) do not apply to a watch: it ticks only when the + profile's exported jar is between 0 and the limit old (the setting when above 0, else 60 minutes). The + rule is asked when a tick is queued AND when its job starts, and for the capture that follows a read + both before it is queued and when it starts (`refuseWatchJob`): a refusal there opens nothing, pauses + the watch and is no strike. +- ALL LIBRARIES SHARE ONE STREAM OF TICKS: no tick starts while a trending read, a reparse or a capture of + any library is queued or running. The cap on watched topics stays per library. +- THREE READS IN A ROW that do not end "read" pause a watch ("failing") until the OPERATOR switches it on + again; an agent's ask is refused. +- "Gone from the page" needs the page's end IN THE CAPTURE: the last listing answer is the continuation + from the bottom (its request carries the previous answer's bottom cursor) and brought nothing new, and no + answer failed, was dropped, carried GraphQL errors or lacked timeline instructions. +- A POST IS KEPT WHEN ITS MEDIA IS FETCHED, not when the job was queued: one predicate, asked once per post + before its media, decides both the uncapped download and the logged-in fallback. + +**Later slices** + +- The judge view is a project-less Posts library page in umtool, built on the export's post display. +- Publishing a topic materialises its KEPT posts into an ordinary posts channel named for the topic. +- "Break out a user": the library lists its accounts like an X search channel's leads and reuses that + channel's archive action to create the account's own channel, on no site. + +## Slice 1, as built + +- **The library** is a channel made with platform `x-trending`; `config.xTrending` is its marker, and + the marker alone decides (`common/lib/xTrending/config.ts`, `marker.mjs`). It has no URL and no + timeline to fetch. +- **`read-x-trending`** (`common/controller/readXTrending.ts`, `common/social/xTrendingRead.ts`): one + page opened in the connected X profile's browser; every GraphQL JSON answer the page fetched is saved + raw to `channels/<lib>/trending/reads/<readId>/responses.jsonl` with `page.png` and `read.json` (the + record: operation names and sizes, never a body). Posts are parsed FROM THE SAVED FILE + (`common/social/xTrendingParse.ts`). `probe` saves and writes no post; `reparse` parses a saved read + again, offline, as `reparse-x-trending`. +- **Stops and deadlines.** A read stops at its scroll cap, its post cap, after two scrolls that brought + nothing new, and at once on a 429, a 403, a 401 or a login page. Deadlines: the load 75 s, any other + page call 20 s, closing 10 s, a whole read 6 minutes. +- **The store** (`common/lib/xTrending/store.ts`): the library's posts live under + `channels/<lib>/trending/posts/` (a posts channel's shard format, one directory down, so every reader + of an ordinary posts channel sees a channel with no posts), `topics.json`, `membership.json` (post → + topic, the reads that showed it, its media by kind). One writer, under the file's lock. +- **One browser on the profile at a time.** A Connect or a Refresh is refused while a read or a capture + runs, and those jobs are refused while a Connect or Refresh is in flight + (`editor/app/lib/cookieRefreshGuard.ts`). +- **The doors.** Sites, the index build, reports and articles, drafts and research, umtool's post + archive and the MCP's remote surface all refuse a library; pinned by + `common/publish/xTrendingReportDoor.test.ts`, `umtool/lib/report/xTrendingLibrary.test.mjs` and + `mcp/src/xTrendingPrivacy.test.ts`. +- **Looking.** `pnpm ops get trending <slug>` and the MCP tools `x_trending_topics` / + `x_trending_posts`. + +## Slice 2, as built + +- **`judge-trending`** (`common/lib/xTrending/judgements.ts`, the one writer of `trending/judgements.json`): + per post or per thread, with who decided, when and a note. The listing gives each post's `thread` and its + own judgement, else its thread's. A keep starts one `capture-posts` job for the posts that became keep. +- **`capture-posts` on a library** (`common/controller/capturePosts.ts`): by the marker alone, the archive + check, the captures (`trending/posts-media/<id>/`) and the availability sidecar + (`trending/posts-availability.json`) are rooted under `trending/`. `keptMedia` is refused for a post that + is not kept. +- **Media** (`common/social/xTrendingMedia.ts`, `common/lib/xTrending/mediaStore.ts`): the parser reads + each post's CDN addresses from the saved capture (`mediaSourcesOf`, X's two media hosts only); the capture + job's media half fetches them with no login, 1 to 2 s apart, under the cooldown, a per-file cap and the + job's budget; each file is a hardlink to its blob in `trending/media-store/<aa>/<sha256>.<ext>`, and + `trending/media-index.json` maps hash to bytes, addresses and posts, and remembers addresses found over + the cap. A media half says whether it is owed to the next capture or until the post is kept. + `removeXTrendingPostCapture` removes a capture and only the blobs nothing else links to, and refuses + while a capture of the library is queued or running (its caller answers that); no door calls it. A media + index that is there and cannot be read fails the job and is never written over. Three refusals in a row + from the CDN end a job's media half. The logged-in fallback asks, immediately before each download, + whether the post is still kept. A library's capture takes no queue override. +- **Watch** (`common/lib/xTrending/watch.ts`, `common/controller/xTrendingWatch.ts`): `trending/watch.json`, + `watch-trending`, a scan on its own timer armed below the idle gate, at most one read per scan across + all libraries, pauses with a reason when X would refuse (by the watch's own jar rule, `watchRefusal`), + the jar never refreshed, a `failing` pause after three reads that did not end "read". One scan at a time, + armed or asked for by hand (`runXTrendingWatchScan`). A read's end tells the watch + (`noteXTrendingWatchRead`) and queues one capture for a watched topic's new posts + (`xTrendingWatchFollowUp`), for what a capture left owed, and for the topic's posts with media that were + never captured. `gone` marks are written by `recordXTrendingRead` only when the scrolling went idle, no + answer failed, and the parser finds the page's end in the capture (`pageEnd`). A post's thread key is + decided when it is placed and kept in its membership record. +- **/review** lists paused watches (`common/views/review.ts` `pausedWatchRows`). +- **The kill** (`common/social/profileBrowserPid.ts`: the lock's host, the exact profile directory, a + Chromium binary, the browser process) and the reparse's refusal inside its job. +- **Pins.** `common/bin/xTrendingPrivacy.test.ts`, `common/publish/xTrendingReportDoor.test.ts`, + `mcp/src/xTrendingPrivacy.test.ts` and `umtool/lib/report/xTrendingLibrary.test.mjs` plant a kept, + captured and watched post (`common/lib/xTrending/__fixtures__/slice2Library.ts`) and look for it in what + each door gives out. + +**Left for later slices.** The purge door (button and `pnpm ops` twin). The library's settings have no form: +`watch-trending {"settings"}` sets them. A watched topic's media that failed (a 403, a 404) is not asked for +again by the watch; keeping the post asks again. + +## Slice 3: the judge view + +umtool's Posts library page: by topic, filters by state, media type and author, bulk actions, keyboard +friendly, judgements through the editor's `judge-trending`; the purge button and its `pnpm ops` twin. + +## Slice 4: topics and publishing + +Rename, merge, move a post between topics; publish a topic's kept posts into an ordinary posts channel; +break out a user. + +## Open + +- The real page's shape is confirmed only by the first probe. The parser is built so that a change is + local to `common/social/xTrendingParse.ts`. +- Whether a watch may keep the jar fresh by itself is the operator's to rule; until then the jar rule + above stands. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -178,6 +178,9 @@ // 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 watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}' +// pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}' +// pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}' // 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 @@ -704,6 +707,14 @@ const ACTIONS = [ // 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", + // A library's posts judged: keep / drop / later, or undecided (removed), + // per post or per thread ({slug, set: [{id | thread, state, note?}], by?, + // archive?}); a keep archives the post through capture-posts. + "judge-trending", + // A topic watched: read again every interval until an end time ({slug, + // topic, on, intervalMinutes?, hours?, shots?}); the library's defaults + // ({slug, settings}); one scan now ({slug, tick: true}). + "watch-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), @@ -1296,11 +1307,19 @@ export function usage() { " 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,", + " gone?, capture?, thread, 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", + " (trending/posts-media/<id>/<name>, relative to the channel); thread is", + " the root post id of the thread a post belongs to; judgement is {state:", + " keep | drop | later, note?, by, at, from?} once a post has one (its own,", + " or its thread's: from \"thread\"); no judgement is undecided. gone is", + " {at, read, trendId}: a page that showed the post before did not show it", + " at a read that reached the page's end (gone from the page, not", + " deleted). capture is {at, state, shot, files, mediaState, mediaOwed?}", + " (mediaOwed \"next\": a later capture asks again; \"kept\": once the post", + " is kept). A topic carries watch {on, intervalMinutes, until, shots,", + " ticks, paused?, ended?, sentence} once it has been watched. 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,", @@ -1910,6 +1929,61 @@ export function usage() { " in no index build; \"xTrendingMaxScrolls\"?, \"xTrendingMaxPosts\"? set", " its caps).", "", + 'judge-trending judges posts of an X trending library: {"slug", "set":', + ' [{"id" | "thread", "state", "note"?}, ...], "by"?}. "id" is a post of', + " the library; \"thread\" a thread's ROOT post id (get trending gives each", + " post's thread), judging every post of it that has no judgement of its", + ' own. "state": keep, drop, later, or undecided (the judgement is', + ' removed: no entry is undecided). "note": up to 2000 characters. "by":', + ' "agent" (the default) or "operator" - the caller\'s word: an agent says', + ' "agent". An agent\'s judgement is a suggestion: an agent\'s write over', + " a judgement the operator made is skipped for that id and named in", + " skipped, and the rest is written; a post the operator judged through", + " its thread is the operator's too.", + " Answers {written, skipped: [{id | thread, reason}], kept, archive?} -", + " kept names the posts whose judgement BECAME keep. A keep archives them:", + " ONE capture-posts job on X's queue (a screenshot, the context, a", + " reply's thread shot, the media), its id in archive.jobId; \"archive\":", + " false marks only. When that job is refused (a stale jar, the X alert, X", + " cooling down) the judgements are written all the same and", + " archive.error says why; capture-posts {slug, ids, \"thread\": true,", + " \"keptMedia\": true} archives them later. Drop deletes nothing: the", + " post, its capture and its media stay, and a later keep puts it back. An", + " id the library does not hold is skipped by name, not refused.", + "", + 'watch-trending watches a topic of an X trending library: {"slug",', + ' "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}.', + " While a topic is watched its trending page is read again every", + " intervalMinutes (15-1440; default the library's, else 30) until hours", + " from now (1-168; else 48), each tick the SAME single read-x-trending", + " job on X's queue, started by the editor's own scan (once a minute, at", + " most one read per scan, none while a trending read or capture of ANY", + " library waits its turn: every library's ticks are one stream). A topic", + " of several pages reads one page per tick, in turn. At most 4 topics of", + " a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN,", + " no page opened; \"shots\": true also screenshots every new post.", + ' "on": false stops it. A WATCH RUNS ONLY WHILE X\'S COOKIE JAR IS UNDER', + " ITS LIMIT (60 minutes): the editor never refreshes the jar by itself,", + " so a watch pauses when the jar goes stale (X's jar-age alert goes up,", + " /review lists the paused watches) and resumes at the first scan after", + " Refresh cookies on /cookies. It does not cover a night nobody presses", + " Refresh in. That limit is the watch's own, whatever the login source", + " or the setting: a jar whose age cannot be read, a limit set to 0 and", + " an unreadable settings file all pause it. The X alert, a rate-limit", + " cooldown and a missing profile pause it the same way. Three reads in a", + " row that do not end \"read\" (a rate limit, a 403, a page that will", + " not load) pause it until someone switches it on again. A post a page", + " showed before and does not show at a read whose capture shows the", + " page's end (asked for more, the page had none, no answer failed) is", + " recorded gone from the page at that time (get trending: gone) - never", + " \"deleted\". A page X no", + " longer has is not read again, and ends the watch when it was the", + ' topic\'s last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?,', + ' "hours"?, "maxTopics"?}} changes the library\'s defaults; {"slug",', + ' "tick": true} runs one scan now (refused on an idle boot; two asks at', + " once are one scan). get trending shows each topic's", + " watch and what it is doing (watch.sentence).", + "", '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', @@ -1968,6 +2042,21 @@ export function usage() { ' no media, article, thread shot or availability; a post whose context is', ' already read is skipped unless "force". Not with "avatarsOnly".', ' Paced like a post fetch, on its queue.', + " An X trending library is captured by this same job, under", + " channels/<slug>/trending/posts-media/<id>/. Its media comes from X's", + " media CDN by the addresses in the library's saved captures: no login,", + " one file after another 1-2 s apart, under X's cooldown, each file kept", + " once (trending/media-store/, a hardlink per post). A file over the", + " library's maxVideoMb (100 MB) and whatever is past the job's budget (40", + " files / 200 MB) is owed: asked for again by the next capture of that", + " post. A 429 from the CDN stops the job and leaves X alone for 15", + " minutes; a 403 or 404 marks the file; three refusals in a row (a 403,", + " or no answer) and the job asks the CDN no more; nothing retries.", + " \"keptMedia\": true is for posts marked keep (refused for any other", + " id): no per-file cap, and a post the CDN cannot serve whole is", + " downloaded the logged-in way, if it is still kept when that download", + " would start. A library's capture runs on X's queue only: \"queueKey\"", + " is refused for it.", "", 'persist-videos saves specific videos, across channels, to the saved-video', ' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1148,5 +1148,26 @@ test("read-x-trending is a POST with a result marker; get trending reads the lib 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/); + assert.match(usage(), /Actions:.*x-search-lead, read-x-trending, judge-trending, watch-trending/); +}); + +test("judge-trending posts its body; its help says an agent never replaces the operator", () => { + const p = parseArgs(["judge-trending", "--json", '{"slug":"lib","set":[{"id":"1900000000000001001","state":"keep"}]}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/judge-trending"); + assert.deepEqual(p.body, { slug: "lib", set: [{ id: "1900000000000001001", state: "keep" }] }); + assert.match(usage(), /judge-trending judges posts of an X trending library/); + assert.match(usage(), /an agent's write over\n\s+a judgement the operator made is skipped/); + assert.match(usage(), /a post the operator judged through\n\s+its thread is the operator's too/); +}); + +test("watch-trending posts its body; its help says a watch runs only on a fresh jar", () => { + const p = parseArgs(["watch-trending", "--json", '{"slug":"lib","topic":"kettles","on":true,"intervalMinutes":30}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/watch-trending"); + assert.deepEqual(p.body, { slug: "lib", topic: "kettles", on: true, intervalMinutes: 30 }); + assert.match(usage(), /A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER\n\s+ITS LIMIT/); + assert.match(usage(), /It does not cover a night nobody presses\n\s+Refresh in/); + assert.match(usage(), /none while a trending read or capture of ANY\n\s+library waits its turn/); + assert.match(usage(), /pause it until someone switches it on again/); }); diff --git a/umtool/lib/report/xTrendingLibrary.test.mjs b/umtool/lib/report/xTrendingLibrary.test.mjs @@ -32,6 +32,19 @@ test("the post search, the channels offered and the reels' archive reader find n 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"); + // Lane x-trending-2: the library's post is kept, captured and watched — + // a judgement, a capture record, a shot, a media file, the store, a watch. + const lib = path.join(channels, "trending-lib", "trending"); + await mkdir(path.join(lib, "posts-media", "1900000000000006001"), { recursive: true }); + await mkdir(path.join(lib, "media-store", "ab"), { recursive: true }); + await writeFile(path.join(lib, "posts-media", "1900000000000006001", "shot.png"), "shot trendshotmarkert6b"); + await writeFile(path.join(lib, "posts-media", "1900000000000006001", "1900000000000006001_1.jpg"), "picture trendmediamarkerk8d"); + await writeFile(path.join(lib, "posts-media", "1900000000000006001", "capture.json"), JSON.stringify({ version: 1, id: "1900000000000006001", state: "captured", mediaState: "ok", media: [] })); + await writeFile(path.join(lib, "media-store", "ab", `${"ab".repeat(32)}.jpg`), "picture trendmediamarkerk8d"); + await writeFile(path.join(lib, "media-index.json"), JSON.stringify({ version: 1, blobs: {}, oversize: {} })); + await writeFile(path.join(lib, "judgements.json"), JSON.stringify({ version: 1, posts: { "1900000000000006001": { state: "keep", note: "kept trendnotemarkerh3v", by: "operator", at: "2026-11-18T10:00:00.000Z" } }, threads: {} })); + await writeFile(path.join(lib, "watch.json"), JSON.stringify({ version: 1, topics: {} })); + 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); @@ -39,6 +52,16 @@ test("the post search, the channels offered and the reels' archive reader find n 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"), []); + // Nothing any of them answered carries the kept post, its note or its media. + const answered = JSON.stringify([ + await postChannels(channels, null), + await searchPostArchive(channels, "trending-lib", "kettles"), + await searchPostArchive(channels, "trending-lib", "trendnotemarkerh3v"), + await readPostsArchive(channels, "trending-lib"), + ]); + for (const leak of ["trendnotemarkerh3v", "trendmediamarkerk8d", "trendshotmarkert6b", "posts-media", "media-store", "judgements", "1900000000000006001"]) { + assert.ok(!answered.includes(leak), `a reader answered with ${leak}`); + } } finally { await rm(channels, { recursive: true, force: true }); }