Archilyzer · Source

archilyzer

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

commit 3b7caec64ba92249993f96be3e7d717edc1ef68c
parent 519cd561663e329fd729ed37988b6b726ae5afc8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 19 Nov 2026 00:59:07 -0500

Merge lane/x-followups: X jobs only on X's queue, a fixed job cap, and a two-tab trending read

An X job runs on X's queue alone, whatever queue the ask names, and is judged
by the address it fetches (x.com, twitter.com, t.co, twimg.com) as well as by
its channel. A window cut from a saved copy never falls back to X. A fixed cap
of 12 X job starts an hour and 150 a day, for the machine, in code: a job over
it is deferred, not failed, and a lost count is rebuilt only from job records
shown to cover the day, else X jobs are refused until it is. A trending read
reads Top, then presses Latest; a post is marked gone only when every tab that
showed it dropped it in one read. The trending parser reads the topic's title,
summary and tabs; a resumed X history walk keeps its place. Read caps raised to
200 posts and 20 scrolls by default.

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

Diffstat:
MCHANNEL.md | 2+-
MCOMMANDS.md | 19++++++++++++++-----
MOPERATING.md | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/architecture.test.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 2+-
Mcommon/bin/fetch-posts.ts | 6++++++
Mcommon/controller/capturePosts.test.ts | 22+++++++++++++++++++++-
Mcommon/controller/capturePosts.ts | 7+++++++
Mcommon/controller/checkPostAvailability.ts | 7+++++++
Mcommon/controller/fetchCopies.test.ts | 22++++++++++++++++++++++
Mcommon/controller/fetchCopies.ts | 10++++++++++
Mcommon/controller/fetchForumPosts.test.ts | 13+++++++++++++
Mcommon/controller/fetchOlderPosts.test.ts | 5++++-
Mcommon/controller/fetchPosts.test.ts | 319++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/fetchPosts.ts | 39++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/fetchWindows.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 21+++++++++++++++++++++
Mcommon/controller/fetchXSearch.test.ts | 18+++++++++++++++++-
Mcommon/controller/importMedia.ts | 33+++++++++++++++++++++++++++++----
Mcommon/controller/landMedia.test.ts | 33++++++++++++++++++++++++++++++++-
Mcommon/controller/publishXTrending.test.ts | 39+++++++++++++++++++++++++++++++++++++++
Mcommon/controller/publishXTrending.ts | 17++++++++++++++++-
Mcommon/controller/readXTrending.test.ts | 377+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/readXTrending.ts | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/controller/xRun.ts | 2++
Mcommon/controller/xTrendingCooldown.test.ts | 5++++-
Mcommon/controller/xTrendingWatch.test.ts | 19+++++++++++++++++++
Mcommon/controller/xTrendingWatch.ts | 17++++++++++++++---
Mcommon/controller/xTrendingWatchJob.test.ts | 5++++-
Mcommon/jobs/instagramSchedule.test.ts | 22++++++++++++++++++++++
Mcommon/jobs/jobMeta.ts | 13+++++++++++++
Mcommon/jobs/listJobs.test.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/listJobs.ts | 27+++++++++++++++++++++++++++
Mcommon/jobs/networkGuard.ts | 185++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/jobs/pacingGuard.test.ts | 345+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 9+++++++++
Mcommon/jobs/streamCommand.ts | 34++++++++++++++++++++++++++++++----
Mcommon/jobs/syncScheduler.test.ts | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/jobs/syncScheduler.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Acommon/jobs/xJobCap.test.ts | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/xJobCap.ts | 277+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 2+-
Mcommon/lib/clipWindow.ts | 13+++++++++++++
Mcommon/lib/queueKeys.ts | 5+++++
Mcommon/lib/timelineWalk.test.ts | 13+++++++++++++
Mcommon/lib/timelineWalk.ts | 9++++++++-
Acommon/lib/xJobRule.test.ts | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xJobRule.ts | 300+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/config.test.ts | 16++++++++--------
Mcommon/lib/xTrending/config.ts | 8++++----
Mcommon/lib/xTrending/organise.ts | 5++++-
Mcommon/lib/xTrending/store.test.ts | 439+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 379+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/xTrending/watch.ts | 20+++++++++++++++++++-
Mcommon/social/__fixtures__/xTrendingCapture.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Acommon/social/__fixtures__/xTrendingRealShape.ts | 278+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fakeXProfileBrowser.ts | 64+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/social/fetchers.ts | 9+++++++++
Mcommon/social/importPost.test.ts | 22+++++++++++++++++++++-
Mcommon/social/importPost.ts | 6++++++
Mcommon/social/playwrightRuntime.ts | 13+++++++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 263++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/social/xTrendingParse.test.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.ts | 234+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/social/xTrendingRead.test.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/social/xTrendingRead.ts | 321++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Acommon/testing/jobs/asEditorJob.ts | 28++++++++++++++++++++++++++++
Mcommon/views/jobRowView.ts | 3+++
Mcommon/views/jobRows.ts | 1+
Mcommon/views/schedulerStatus.ts | 3+++
Meditor/CHANGELOG.md | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/jobs/[id]/log/route.ts | 2++
Meditor/app/api/media/fetch-window/route.test.ts | 11+++++++++++
Meditor/app/api/media/fetch-window/route.ts | 8++++++++
Meditor/app/api/ops/_xTrendingWatch.ts | 2+-
Meditor/app/api/ops/read-x-trending/route.test.ts | 4++--
Meditor/app/api/ops/read-x-trending/route.ts | 18++++++++++++------
Meditor/app/api/ops/trending/route.ts | 5+++--
Meditor/app/api/ops/watch-trending/route.ts | 7+++++--
Meditor/app/channels/[slug]/components/XTrendingPanel.tsx | 46+++++++++++++++++++++++++++++++++++++++++-----
Meditor/app/channels/[slug]/pipelineActions.ts | 5++++-
Meditor/app/channels/[slug]/socialActions.ts | 34++++++++++++++++++++++------------
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 10++++++++--
Meditor/app/channels/[slug]/videos/fetchWindowsAction.test.ts | 16++++++++++++++++
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 20++++++++++++++++++--
Meditor/app/channels/[slug]/whisperActions.ts | 8+++++++-
Meditor/app/channels/[slug]/xTrendingActions.ts | 13++++++++++++-
Meditor/app/channels/components/parseChannelForm.test.ts | 6+++---
Meditor/app/jobs/[id]/page.tsx | 9+++++++++
Meditor/app/jobs/components/JobRow.tsx | 4++--
Meditor/app/scheduler/runTick.ts | 44++++++++++++++++++++++++--------------------
Meditor/app/scheduler/status.ts | 4+++-
Meditor/e2e/fixtures/bin/fake-gallery-dl.mjs | 11++++++++++-
Meditor/e2e/x-trending.spec.ts | 125++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mmcp/src/xTrending.test.ts | 53++++++++++++++++++++++++++++++++++++++++++++++++-----
Mmcp/src/xTrending.ts | 49+++++++++++++++++++++++++++++++++++++++++--------
Mplans/x-trending.md | 188++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.mjs | 36+++++++++++++++++++++++++++++-------
Mumtool/components/tools/library/LibraryView.tsx | 42++++++++++++++++++++++++++++++++++++++++--
Mumtool/e2e/fixtures/editor-stub-trending.mjs | 3++-
Mumtool/e2e/fixtures/library-fixture.mjs | 9++++++++-
Mumtool/e2e/library.spec.ts | 10++++++++++
Mumtool/lib/library/cli.mjs | 15+++++++++++++--
Mumtool/lib/library/cli.test.mjs | 33++++++++++++++++++++++++++++++++-
Mumtool/lib/library/filters.mjs | 5+++++
Mumtool/lib/library/view.test.mjs | 5+++++
107 files changed, 6808 insertions(+), 354 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?, 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. | +| `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–40 scrolls, default 20; 1–400 posts, default 200; each of the page's two tabs has both); 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 @@ -70,7 +70,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer seed` | | the home seeder of last resort: seed the playable torrents of settings.seeder.sites, each only while no other seeder has it (standby otherwise, with hysteresis), TCP + WebRTC, no DHT; runs until interrupted — behind the VPN (docker compose profile `seeder`, docker-compose.seeder.yml) | | `archilyzer tracker` | `[--host 127.0.0.1] [--port 8000]` | the self-hosted tracker (HTTP + WebSocket, no UDP) for the seeder's torrents only — any other infohash is refused; runs until interrupted | | `archilyzer duplicates` | `[--threshold N] [--all-durations] [--blocking title\|duration\|both] [--near F] [--tolerance N] …` | on-demand duplicate detection (after index + stats) *(passthrough)* | -| `archilyzer posts fetch` | `--slug <channel> [--backfill \| --full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again) *(passthrough)* | +| `archilyzer posts fetch` | `--slug <channel> [--backfill \| --full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again). An X or Instagram channel is refused here and names `pnpm ops fetch-posts`: those are asked only by the editor's jobs, on their queue, gap and cookie rules; Bluesky, a forum thread and a web page are fetched) *(passthrough)* | | `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched | | `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* | | `archilyzer evidence pack` | `<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media\|--no-media] [--stamp\|--no-stamp] [--dry-run] [--json]` | package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/&lt;postId&gt;/ (the post's captured files, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/&lt;handle\|channel&gt;-&lt;YYYY-MM-DD&gt;/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later) | @@ -168,7 +168,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `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. AN INSTAGRAM CHANNEL: a sync reads ONE page (up to 30 posts), a first fetch, "full" or "backfill" walks up to 120 posts and the next run resumes; the new posts' pictures and videos are fetched in the same job (a sync 40 files / 200 MB, a walk 120 / 600 MB, 100 MB a file; a walk leaves the posts whose media would not fit for its next run; what is still not fetched is recorded as owed, and none after a refusal). Refused before a job exists when the channel has no cookiesFromBrowser of its own, with "retryOnBlock" or "older", and with a "queueKey" other than platform:instagram. A login, challenge or checkpoint page raises Instagram's alert and refuses every Instagram job until recheck-service; the first 429 holds Instagram for an hour (clear-platform-hold {"platform": "instagram"} ends that by hand). 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` | +| `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. It ends only at the timeline's end, its budget or a cap: posts already archived are skipped, never taken for the end, and its place is cleared only by the timeline's end. A resume that began again from the top (the first posts read are the newest) stops at once with a sentence and keeps its place. | `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. An Instagram channel is refused: no screenshot is taken of an Instagram post, and its media come with the post, in the fetch-posts job. "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` | @@ -218,9 +218,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `save-page-now-batch` | save-page-now-batch saves a LIST of pages as ONE resumable job: {"urls": \[...\]} \| {"file": &lt;abs path: a JSON list, {urls}, or a URL a line&gt;} \| {"batch": &lt;id&gt;}, "skipArchived"? (true), "sources"? (\["wayback", "archive.today"\]), "evidence"? (abs path), "dailyCap"? (150 anonymous, at most 200; 5000 with keys), "dryRun"? -&gt; {jobId, batch}. Each URL in turn: looked up (the Wayback CDX, archive.today's timemap, each paced) and archived-already when a copy shows it (a Wayback row that recorded a 200, or an archive.today copy); else saved through Save Page Now's pacer (anonymous without keys), saved or failed with the reason; a site Save Page Now refuses as a site (x.com, 5 Nov: "limitations when it comes to archiving this site") is asked once a run, its other URLs looked up only. archive.today and Ghostarchive are looked up, never asked to save. The state is &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.json, written after every URL: the same request again, {batch}, a Retry or a restart continues from the first pending URL. The evidence (JSON + CSV: url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt) is rewritten after every URL; default &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.evidence.json. Progress (done/total, ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode, counts, run, evidence, statePath, etaSeconds, stopped?}. | `pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'`<br>`pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'`<br>`pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'` | | `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -&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. An X TRENDING LIBRARY's accounts (get trending &lt;slug&gt; --accounts) are leads too: with "slug" a library, "archive" creates &lt;handle&gt;-x for an account that wrote a post the library holds, on no site, naming nothing of the library, and ASKS X NOTHING, now or later: no first fetch is started and the channel is made with SYNC OFF (its priority tier paused, which the scheduler, Sync all and the lanes honour) -&gt; {slug, jobIds: \[\], syncOff: true, sentence}. The sentence says how to turn sync on (channel-priority, tier normal) and run the first fetch (fetch-posts). "fetch": true asks for the ordinary behaviour instead (the first fetch started, sync on). "never" and "restore" are a search channel's only. | `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"}'`<br>`pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}'` | -| `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` | +| `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 the page's own title). "tabs": \["top"\], \["latest"\] or both (the default): BOTH ARE READ IN THIS ONE JOB - Top to its stop, then the page's own Latest tab is pressed and read under the same caps. A Latest that cannot be opened ends the read "Top read; Latest not read: &lt;why&gt;", ok, nothing retried. "scrolls": 1-40 moves to the bottom of a tab (default: the channel's cap, else 20); "posts": stop a tab once 1-400 are seen on it (else 200); a tab also stops after two scrolls with nothing new, and the whole read 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 its deadline: 2 minutes plus 12 s for every scroll each tab may make (both tabs at 20 scrolls: 10 minutes; one tab: 6; both at 40: 18). 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 the operator switches it on again ("by": "operator"; 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 (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}'` | +| `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. "tabs": the page's tabs each tick reads, as read-x-trending's (the default: both, in the one job). "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 the operator switches it on again ("by": "operator"; 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 (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}'` | | `purge-trending` | purge-trending removes the captures of DROPPED posts of an X trending library, in two steps. {"slug", "dryRun": true, "topic"?, "ids"?} removes nothing: it counts the dropped posts with a capture (posts, ids, files, bytes) and answers "confirm", a digest of exactly those posts. {"slug", "confirm", "by": "operator", "topic"?, "ids"?} removes them: the screenshot, the record and the media under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. It is the operator's press: an agent's removal is refused (an agent may ask for the dry run), and a confirm that no longer matches (a post dropped or kept, a capture added since) is refused with nothing removed. Only posts whose judgement in force is drop BY THE OPERATOR (their own entry, or their thread's) are taken: an agent's drop is a suggestion and is never purged (agentDropped counts those left alone), nor is a post marked later, kept or undecided; an id named that is not such a post is listed in skipped. gone names the posts to be removed that are gone from the page: their capture is the only copy, and the sentence says removing it cannot be undone. The judgements, the posts and the reads stay, and so does every media file another post still uses (blobsKept). Refused while a capture of the library is queued or running (a dry run then says captureInFlight). A later keep captures the post again. | `pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | | `organise-trending` | organise-trending organises the topics of an X trending library. "by" is who asks ("agent" unless told) and is recorded. {"slug", "op": "rename", "topic", "title"} renames a topic: its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused, and so is a rename while a read or a reparse of the library is queued or running (a read may name its topic by its name). {"slug", "op": "move", "to", "ids": \[..\] \| "thread", "create"?} moves posts (or every post of one thread, by its root post's id) into the topic "to" (an id or a name; "create": true makes a topic of that name, with no trending page, when there is none) -&gt; {to, moved, skipped}; judgements and captures are untouched, a later read never moves a post back, and it is not refused beside a read or a capture. {"slug", "op": "merge", "into", "from": \[..\], "by": "operator"} puts every post, page and read of the "from" topics into "into" and removes them -&gt; {into, merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the operator's (an agent's is refused), and it is refused while a read or a reparse of the library is queued or running. The merged topics' ids keep meaning "into"; judgements are untouched; ONE watch stands (the target's live watch with its own terms, else the first merged topic's moves to it), and "sentence" says which. A topic has one published channel too (published: {carried?, left}): the target's stays; with none, the first merged topic's becomes its own; any other is left as it is, never added to again, and named in the sentence. | `pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}'` | | `publish-trending` | publish-trending publishes a topic of an X trending library, in two steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it says what would be written (channel, creates, posts, ids, already, files, bytes, textOnly, noLongerKept) and what to know before the press: sites (the sites the channel is ALREADY ON: what is added goes public at their next build), movedIn (posts to publish that were moved into the topic, and by whom) and mismatched (files that no longer match the digest their capture recorded: not copied). It answers "confirm", a digest of exactly that, the sites included. Then {"slug", "topic", "confirm", "by": "operator"} publishes: the topic's posts whose judgement in force is keep BY THE OPERATOR (their own entry, or their thread's) go into an ORDINARY posts channel ("channel": a slug of the topic's name unless given, fixed at the first publish) with their captured media and screenshots, COPIED (the library keeps its own; a purge of the library and a delete of the channel do not reach each other). An agent's keep is not published. The channel is on NO site (adding it to one is a separate step: site-config, /sites), names nothing of the library (no judgement, note, read, watch or gone mark) and is never fetched. It is the operator's press: an agent's publish is refused (an agent may ask for the dry run), and a confirm that no longer matches is refused with nothing written. Re-publishing adds newly kept posts and files and removes nothing: a post published before and since dropped is listed in noLongerKept and left; textOnly lists kept posts with no capture yet (published as their words; a later publish adds the files). Refused while a read, a reparse or a capture of the library is queued or running (a dry run then says inFlight), and when a channel of that slug exists that this publish did not make (no record of it, a source of its own, a post this topic never published, or not the very directory this publish made: a channel deleted and made again by hand is refused, even empty). | `pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | @@ -360,7 +360,16 @@ get x-session [<slug>] is the X login an X job would use and whether one "browser": cookiesFromBrowser, whose age cannot be read), hasCookies, looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up, - allowed, and reason (the refusal an X job would get). <slug> names a + allowed, and reason (the refusal an X job would get); and X's JOB CAP: + cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} - + at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON + THIS MACHINE: one count over every kind of X job, whatever the login + source, cookie spec or channel. A job past it is refused when queued, + with the time the next may start; one that meets it when its queue + starts it ends done, deferred (not failed). A library's media-only + capture is not counted. The numbers are constants of the code + (common/lib/xJobRule.ts): no setting, option or queue raises them. + <slug> names a channel whose own cookiesFromBrowser may decide the source. Nothing is asked of X: a refresh is Refresh cookies / Connect X account on /settings. Ask it before queueing fetch-posts or capture-posts on X. diff --git a/OPERATING.md b/OPERATING.md @@ -509,12 +509,63 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait `posts-state.json` from before the split has one `cursor`. It is read as the backfill's place and rewritten on the next fetch. The job log's first line names the mode (`— sync new, since …` / `— resume backfill, from its saved resume point`). +- **A resumed backfill ends only at the timeline's end, its budget (180 min) or a cap.** Posts already archived + are skipped, never taken for the end (`100 already-archived posts in a row: … it skips them and reads on`), and + the saved place is cleared only when gallery-dl walked to the timeline's end. X's timeline pages back a few + thousand posts; below that gallery-dl goes on by search (`from:<handle> max_id:<id>`), and the place saved there + is the search's (`3_<id>/`), not the last timeline page. A resume whose first posts are the timeline's newest + did not continue from its place: it stops at once with a sentence and keeps the place. If a place is lost, + `fetch-posts {"older": true}` walks down from the oldest archived post. - **Pacing is enforced, not advised** (plans/pacing-guard.md). Every job that asks a platform waits its platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, X 300 s, forums and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)`). Thirteen fetches queued in one loop run five minutes apart and stop at the first challenge. A queue override of `""` (immediate) is refused for any such job. +- **Only the editor's jobs ask X.** `pnpm archilyzer posts fetch --slug <x-channel>` is refused, in every mode + (plain, `--backfill`, `--full`, `--older`, an X search channel) and for every X fetcher, and names `pnpm ops + fetch-posts`: run directly it had no queue, no gap, no fresh-jar rule, no X alert and no cooldown. It still + fetches a Bluesky account, a forum thread (`--pages N`) and a web page, whose pacing is the fetcher's own. + `pnpm archilyzer posts check` on an X channel is refused the same way. The Add-channel form's **Fetch details** + on an X address reads the handle off the URL and asks X nothing. +- **X jobs run on X's queue only.** Every job that asks X as the connected account or with X's cookies — a + posts fetch in any mode, `resume-backfill`, a Sync, `create-channel` with a fetch, `capture-posts` on an X + channel or a library, `read-x-trending`, `import-post` of an X post, an availability check of an X channel, an + X run, an X lead archived with a fetch — is refused with a `queueKey` other than `platform:twitter`, when it is + queued and again where it runs. On another queue it ran beside the job on X's and outside the gap between X jobs. +- **An X channel's jobs that ask X nothing are not X's.** Its transcriptions (`transcribe-one`, whisper-video's + hand-off), windows cut from a saved copy (`clips:saved-video`), an import of a local file and an archive.org + import run on their own queues. Its clip windows, an import of an x.com address (into any channel) and its + kept-videos check run on X's queue. **A clip window is X's by the address it fetches, in any channel:** an + x.com or twitter.com page (`webpageUrl` on `fetch-window` / `fetch-windows`) is queued on X's queue and refused + on any other; a window that names no address is its channel's. A window of a copy (find-copy's archive.org or + Wayback) or of a mirror on another platform is not X's. A window on `clips:saved-video` whose saved copy is gone + by the time it runs fails ("the saved copy no longer covers this window; ask again and it runs on X's queue") + and asks X nothing. `fetch-copies` refuses a copy whose address is X's. A `t.co` short link is X's. `record-live` of an X channel is refused (a recording would hold X's queue + for hours), and so is `redownload-incomplete-bucket` on one (the transcription queue). +- **X's job cap: 12 in any 60 minutes, 150 in any 24 hours, on this machine.** ONE count over every kind of X + job together (each channel of an X run is one), whatever the login source, cookie spec or channel. A job past + it is refused when it is queued, with the time the next may start; nothing queues behind it. **A job that meets + it when its queue starts it ends `done`, deferred** (`[deferred] …` in its log, `deferred` on the job): it did + not run, it is not a failed sync, and nothing queues it again before that time. The scheduler skips X channels + while it is reached and a trending watch waits, as for a cooldown. `pnpm ops get x-session` shows the count + (`cap`). **What counts:** a job that can ask x.com with the login or X's cookies — every X job but a trending + library's media-only capture (screenshots, articles, avatars and context off, not a keep capture), which takes + files from X's media hosts with no cookie and no page: it runs on X's queue under X's gap, cooldown and the + watch's jar rule, and the cap neither counts nor holds it. **The two numbers are constants of the code** + (`common/lib/xJobRule.ts`): no setting, channel option, environment variable, flag or queue raises them, and + changing them is a code change. The count is kept in `transcripts/.x-session/job-starts.json`; if that file + cannot be read no X job starts until it is repaired. If it is gone, the last 24 hours are counted again from + the job records (`.jobs/<id>.meta.json`, `xStarts`); if X's queue ended a job in that time and the records + cannot be read (or none is left), no X job starts. Nor does it while nothing shows the day's records are all + there: the jobs list's retention and **Clear logs** keep every X job's record for the day it can count, and + say since when in `.jobs/x-records-kept.json`; until that is a day old, a lost count is refused, at most for a + day (a date in that file after now is no proof: said again at now). A start stamped in the future (a clock set + back) counts until the clock has passed it by the window. The scheduler queues no more X syncs than the cap has + starts left (less the X jobs already waiting); the others wait for a later tick. X's own gap (5 minutes) already means 12 jobs an hour, so + the hourly cap bites only if that gap is lowered; the daily cap bites sooner: an X run over more than 150 + channels, more than 150 X channels on a daily sync, or two topics watched at 30 minutes (a tick is a read and + usually a capture: about 96 jobs a day per topic) each reach it. - **X only on a fresh jar.** With the connected profile as the login source, a job aimed at X is refused — at enqueue and again when its queue reaches it — unless the cookies were refreshed within `social.x.maxCookieAgeMinutes` (60; 0 = off): `X cookies were last refreshed 16 days ago (limit 60 min): @@ -729,10 +780,11 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o never served or indexed. - **What a read costs**: one page load, the page's own first requests, and at most one more page of its timeline per scroll. A scroll moves to the bottom of what has loaded, then waits 4–10 s. It stops at the scroll cap - (`"scrolls"`, 1–20, default 8), at the post cap (`"posts"`, 1–200, default 60), after two scrolls that brought + (`"scrolls"`, 1–40, default 20), at the post cap (`"posts"`, 1–400, default 200), each counted per tab, after two scrolls that brought nothing new, and at once on a 429, a 403, a 401 or X's login page. Nothing retries. - **A read cannot hang.** The page's load has 75 s; a scroll, the address and the screenshot 20 s each; closing - the browser 10 s (then it is killed); the whole read 6 minutes. Past any of them the read fails with a sentence, + the browser 10 s (then it is killed); the whole read 2 minutes plus 12 s for every scroll each tab may make (both tabs at + 20 scrolls: 10 minutes; one tab: 6; both at the maximum 40: 18). Past any of them the read fails with a sentence, the browser closed and the capture kept. The channel's own caps are `xTrendingMaxScrolls` / `xTrendingMaxPosts` (Configure, or `channel-config`). - **A read lists posts**: the post's words, author, date and its media by kind, parsed from the saved file and @@ -741,6 +793,26 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o - **Topics.** `"topic"` is a topic's id or name, or a new one's name: several pages can be read into one topic. Without it the posts go to the topic that page was read into before, else to a new one named for the page. A post already in a topic stays there. +- **X's own title and summary.** A trending page carries X's title and summary of the trend. A topic you did not + name is called by the page's title (its id stays `t-<number>`); one still called `Trending <number>` takes the + title at the next read or `reparse` of a capture that has it, and the job's sentence says so. A topic made with + a name, or renamed since by you or an agent, is never renamed by a read; nor is one whose page's title another + topic already answers to. Whatever the topic is called, the page's entry in it keeps X's title, summary and when + X last updated them: the channel page, `get trending` (`sources[].title` / `summary` / `lastUpdatedAt`), + `x_trending_topics`, and umtool's library page and `umtool library topics` show them as X's. +- **A read covers both tabs, in one job.** A trending page has tabs (`Top`, `Latest`), each its own list of + posts; `Latest` is where a post that is deleted quickly shows first. A read scrolls `Top` to its stop, then + presses the page's own `Latest` tab (it never builds a request: it waits for the page's request for that tab's + timeline) and scrolls it under the same caps. `"tabs": ["top"]` or `["latest"]` reads one; a watch takes the + same option. Everything stays one capture (`responses.jsonl`), with `page-latest.png` beside `page.png`. + `read.json` says per tab (`tabs`): its posts, its scrolls, why it stopped and whether the capture shows its + end. A `Latest` that cannot be opened — no such tab on the page, or pressing it brings nothing within 20 s — + ends the read `Top read; Latest not read: <why>`: still a read, no strike against a watch, nothing retried. A + 429, a 403 or a login wall on either tab stops the whole read. +- **"Gone" is said tab by tab.** A tab read to its end marks the posts it showed before and no longer shows. A + post gone from one tab while the other still shows it is `Gone from the "Latest" tab …; another tab still shows + it` (`posts[].goneTabs`); it is `gone from the page` once every tab that showed it has dropped it. Neither says + the post was deleted. - **`"probe": true`** saves the capture and a summary (the operations' names and sizes, how many posts the parser finds) and writes no post. `{"reparse": "<readId>"}` parses a saved capture again, offline, as a `reparse-x-trending` job: X is asked nothing, so it needs no fresh jar. `read.json` is written when a read @@ -749,7 +821,7 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o 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 …: N posts on the page, M new, in topic "…" (<id>), shown by the page's "Top" tab.` - `Read saved, nothing recognised: …`: the answers held no post the parser knows. Not a failure, no X alert; the capture is kept for the parser. - `X asked to log in instead of showing the trending page …`: fails, no post written, and X's cookie alert goes diff --git a/common/architecture.test.ts b/common/architecture.test.ts @@ -316,3 +316,63 @@ test("views/ never calls a singleton getter, a disk reader or the clock", async `Found: ${offenders.join(", ")}`, ); }); + +// ── the test kit stays out of production code (review 1 of lane x-followups) ── +// +// `common/testing/` is helpers for tests only (its README: "nothing in an app +// imports from here"). One of them, testing/jobs/asEditorJob.ts, makes a call +// stand where the editor's job does — the context an X fetch asks for before +// it asks X anything (controller/fetchPosts.ts X_ONLY_AS_A_JOB). Imported by +// production code it would be a way past that rule, so the README's sentence +// is enforced here: no module that ships — under common/ outside testing/, or +// in the editor, umtool, the MCP, the export, the homepage or scripts/ — +// imports from the test kit. Tests, e2e suites and fixtures may. +const REPO = path.resolve(HERE, ".."); +const SHIPPED_ROOTS = ["common", "editor/app", "umtool/app", "umtool/lib", "umtool/components", "umtool/bin", "umtool/report-to-video", "mcp/src", "export/app", "homepage/app", "scripts"]; +const SOURCE_FILE = /\.(?:ts|tsx|mts|cts|mjs|cjs|js|jsx)$/; +// Not shipped: a test, an e2e spec's unit, a fixture, the kit itself. +const TEST_ONLY = /(?:\.test\.|\.unit\.|\.fixtures?\.|(?:^|\/)(?:__fixtures__|fixtures|e2e|testing|node_modules|\.next|test-results[^/]*)\/)/; +const TESTING_IMPORT = /(?:from\s+|import\s*\(\s*|require\s*\(\s*|import\s+)["'](?:[^"']*\/)?(?:common\/testing|yt-dlp-transcript-common\/testing|\.\.?\/(?:\.\.\/)*testing)\/[^"']*["']/; + +async function sourceFilesUnder(dir: string, out: string[] = []): Promise<string[]> { + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + const full = path.join(dir, entry.name); + const rel = path.relative(REPO, full).split(path.sep).join("/"); + if (entry.isDirectory()) { + if (!TEST_ONLY.test(`${rel}/`) && entry.name !== "node_modules" && !entry.name.startsWith(".")) await sourceFilesUnder(full, out); + } else if (SOURCE_FILE.test(entry.name) && !TEST_ONLY.test(rel)) { + out.push(full); + } + } + return out; +} + +test("no shipped module imports the test kit (common/testing)", async () => { + // The pattern sees each way of writing the import… + for (const line of [ + 'import { asEditorJob } from "../testing/jobs/asEditorJob";', + 'const kit = await import("../../testing/jobs/asEditorJob");', + 'import { x } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";', + 'import { x } from "../../common/testing/chartPixels";', + "const kit = require('./testing/makeZip');", + ]) { + assert.match(line, TESTING_IMPORT, line); + } + // …and not a module that merely has the word in its name. + for (const line of ['import { x } from "../lib/testingLibrary";', 'import { y } from "@testing-library/react";', 'import { z } from "./quiesce";']) { + assert.doesNotMatch(line, TESTING_IMPORT, line); + } + const offenders: string[] = []; + let scanned = 0; + for (const root of SHIPPED_ROOTS) { + for (const file of await sourceFilesUnder(path.join(REPO, root))) { + scanned++; + const text = await readFile(file, "utf8"); + for (const [i, line] of text.split("\n").entries()) { + if (TESTING_IMPORT.test(line)) offenders.push(`${path.relative(REPO, file)}:${i + 1}: ${line.trim()}`); + } + } + } + assert.ok(scanned > 500, `the walk found the code (${scanned} files)`); + assert.deepEqual(offenders, [], "shipped code imports common/testing:\n" + offenders.join("\n")); +}); diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -912,7 +912,7 @@ export const COMMANDS: Command[] = [ script(["duplicates"], "duplicate-shorts.ts", "[--threshold N] [--all-durations] [--blocking title|duration|both] [--near F] [--tolerance N] … on-demand duplicate detection (after index + stats)", 8192), script(["posts", "fetch"], "fetch-posts.ts", - "--slug <channel> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), + "--slug <channel> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again). An X or Instagram channel is refused here and names `pnpm ops fetch-posts`: those are asked only by the editor's jobs, on their queue, gap and cookie rules; Bluesky, a forum thread and a web page are fetched)"), { path: ["posts", "import-html"], usage: diff --git a/common/bin/fetch-posts.ts b/common/bin/fetch-posts.ts @@ -5,6 +5,12 @@ // --slug <channel-slug> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] // [--retry-on-block | --retry-minutes N --retry-tries M] // +// NOT FOR X OR INSTAGRAM: fetchPosts refuses a channel of either outside the +// editor's job (controller/fetchPosts.ts X_ONLY_AS_A_JOB, INSTAGRAM_ONLY_AS_A_JOB) +// and names `pnpm ops fetch-posts`. Run from here a fetch has no queue, no gap +// between jobs, no fresh-jar rule, no alert and no cooldown. Bluesky, a forum +// thread and a web page are fetched from here as before. +// // --pages caps how many pages one run reads, for a source read page by page (a // forum thread: its latest N pages, newest first; the next run continues where // this one stopped). diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -15,7 +15,10 @@ process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); const { getPaths } = await import("../lib/paths"); const { registerSocialFetcher } = await import("../social/fetchers"); const { readPostAvailability, writePostAvailability, writePosts } = await import("../lib/posts-server"); -const { capturePosts, NOTHING_TO_CAPTURE } = await import("./capturePosts"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { capturePosts: capturePostsDirect, NOTHING_TO_CAPTURE } = await import("./capturePosts"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const capturePosts = insideEditorJob(capturePostsDirect); type Input = import("../social/fetchers").PostCaptureInput; type Result = import("../social/fetchers").PostCaptureResult; @@ -669,3 +672,20 @@ test("an X trending library's logged-in fallback asks, per post and at that mome assert.deepEqual(logins, ["8001"]); assert.deepEqual([results["8001"].ok, results["8002"].ok], [true, false]); }); + +// Added scope R2 (lane x-followups): where X is about to be asked, only a job on X's queue stands. +test("R2a: a capture of an X channel's posts outside the editor's job, or in a job on another queue, asks its fetcher nothing; a Bluesky channel's is not X's", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + // The channel the thread-shot test made (an X channel, the X test fetcher). + const ask = { paths: getPaths(), slug: "demo-x-replies", settings: {}, ids: ["9001"] }; + const before = calls.length; + const outside = await capturePostsDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^A capture of demo-x-replies's posts asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops capture-posts/); + const elsewhere = await asEditorJob(() => capturePostsDirect(ask), { queueKey: "manual" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + assert.equal(calls.length, before, "the fetcher was not asked"); + // Bluesky: no such rule. + const sky = await capturePostsDirect({ paths: getPaths(), slug: "demo-social", settings: {}, ids: [] }); + assert.doesNotMatch(sky.error ?? "", /asks X/); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -32,6 +32,7 @@ // `contextOnly` loads one page per post for that alone (and the avatars it // shows), writing the context into the record and nothing about availability. +import { xJobContextRefusal } from "../lib/xJobRule"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; @@ -294,6 +295,12 @@ export async function capturePosts( : resolveSocialFetcher(config.postFetcher, accountUrl); const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); + // X IS ASKED ONLY BY THE EDITOR'S JOBS, ON X'S QUEUE (lib/xJobRule.ts): a + // capture of an X channel's posts, or of a library's, asked where it runs. + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`A capture of ${opts.slug}'s posts`, `pnpm ops capture-posts --json '{"slug":"${opts.slug}","ids":[…]}' --wait`); + if (refusal) return fail(refusal); + } const avatarsOnly = opts.avatarsOnly === true; if (avatarsOnly) { const nope = avatarsOnlyProblem(fetcher.platform, fetcher.label); diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -17,6 +17,7 @@ // checked first (the default, cheap and incremental), `unchecked` only covers // posts never looked at, `all` re-checks everything. +import { xJobContextRefusal } from "../lib/xJobRule"; import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; @@ -160,6 +161,12 @@ export async function checkPostAvailability( if (fetcher.platform === "instagram") { return { ok: false, ...empty, error: INSTAGRAM_NO_AVAILABILITY_CHECK }; } + // An X channel's check runs only as the editor's job, on X's queue + // (lib/xJobRule.ts): `pnpm archilyzer posts check` on one is refused. + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`An availability check of ${slug}'s posts`, `pnpm ops check-post-availability --json '{"slug":"${slug}"}' --wait`); + if (refusal) return { ok: false, ...empty, error: refusal }; + } if (!fetcher.checkAvailability) { // Better to say so than to guess. gallery-dl, for instance, has no cheap // per-post liveness probe, so its channels should switch fetcher to sweep. diff --git a/common/controller/fetchCopies.test.ts b/common/controller/fetchCopies.test.ts @@ -221,3 +221,25 @@ test("the transcription lane picks the audio up: the snapshot moves a gone video await c.close(); } }); + +// Review 3 S5: fetch-copies passes X's queue rule because it asks archive.org +// (lib/xJobRule.ts xJobAsksX). A "copy" whose address is X's is therefore +// never fetched here: it fails before any request, and the run goes on. +test("review 3 S5: a copy whose address is X's is refused before any request; the others are fetched", async () => { + const c = await corpus(); + try { + const f = fakeFetch(); + const { d } = deps({ fetchCopy: f.fetchCopy }); + const items: FetchCopyItem[] = [ + { slug: SLUG, id: GONE_A, copy: { from: "wayback", url: "https://x.com/example/status/1900000000000003001" } }, + { slug: SLUG, id: GONE_B, copy: { from: "archive.org", url: "https://t.co/AbCdEf123" } }, + { slug: SLUG, id: GONE_C, copy: wayback(GONE_C) }, + ]; + const r = await fetchCopies({ paths: c.paths, items, gapMs: 0, deps: d }); + assert.deepEqual(r.failed.map((x) => [x.item.id, x.class]), [[GONE_A, "not-a-copy"], [GONE_B, "not-a-copy"]]); + for (const x of r.failed) assert.match(x.message, /is X's: a copy is archive\.org's .* nothing was asked of X/); + assert.deepEqual(f.calls.map((x) => x.videoId), [GONE_C], "only the archive.org copy was fetched"); + } finally { + await c.close(); + } +}); diff --git a/common/controller/fetchCopies.ts b/common/controller/fetchCopies.ts @@ -34,6 +34,7 @@ import type { ChannelConfig } from "../lib/channelConfig"; import type { ClipCopy } from "../lib/clipWindow"; import type { JobProgress } from "../jobs/registry"; import { parseArchiveOrgUrl } from "../lib/archiveOrgId"; +import { isXUrl } from "../lib/xJobRule"; import { parseWaybackUrl } from "../lib/wayback"; import { ensureWaybackProvenance } from "../lib/wayback-server"; import { ensureArchiveOrgProvenanceSidecar } from "../lib/archiveOrg-server"; @@ -229,6 +230,15 @@ export async function fetchCopies({ break; } const label = fetchCopyItemLabel(item); + // A COPY IS ARCHIVE.ORG'S (review 3 S5): this job passes X's queue rule + // because it asks archive.org only (lib/xJobRule.ts xJobAsksX), so an + // address of X's is never fetched here. + if (isXUrl(item.copy.url)) { + fail(item, "not-a-copy", "its address is X's: a copy is archive.org's (the Wayback Machine or an archive.org item), and nothing was asked of X"); + done++; + progress(); + continue; + } if (!configs.has(item.slug)) configs.set(item.slug, await deps.readChannelConfig(paths, item.slug).catch(() => null)); const config = configs.get(item.slug) ?? null; if (!config) { diff --git a/common/controller/fetchForumPosts.test.ts b/common/controller/fetchForumPosts.test.ts @@ -193,3 +193,16 @@ test("the real wait ends on a cancel or a drain", async () => { assert.equal(await q, "drained"); assert.equal(await sleepOrStop(1), "slept"); }); + +// Lane x-followups: X is asked only by the editor's jobs; a forum thread keeps the direct path +// (`pnpm archilyzer posts fetch --slug <thread> --pages N`, README): its pacing is the fetcher's own. +test("a forum thread is fetched by a direct call, outside any job: the CLI's path stays", async () => { + const { currentJobContext } = await import("../lib/jobContext"); + assert.equal(currentJobContext(), undefined); + const { slug } = await channel(); + const thread = new FakeForumThread(3); + await thread.writeTo(FIXTURES); + const r = await fetchPosts({ paths: getPaths(), slug, settings: {}, pages: 1 }); + assert.equal(r.ok, true, r.error); + assert.ok(r.written > 0); +}); diff --git a/common/controller/fetchOlderPosts.test.ts b/common/controller/fetchOlderPosts.test.ts @@ -94,12 +94,15 @@ async function makeChannel(slug: string): Promise<string> { } const { - fetchPosts, + fetchPosts: fetchPostsDirect, FULL_AND_OLDER_REFUSAL, EMPTY_ACCOUNT_OLDER_REFUSAL, emptyAccountOlderProblem, olderPostsProblem, } = await import("./fetchPosts"); +// An X fetch runs only as the editor's job (X_ONLY_AS_A_JOB): these calls stand where one does. +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const fetchPosts = insideEditorJob(fetchPostsDirect); const { readPostFetchState, readSeenPostIds, diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -48,7 +48,25 @@ const tw = (n) => '[2, {"tweet_id": ' + (1899000000000000100n - BigInt(n)) + const page = (p) => { for (let i = 0; i < 3; i++) process.stdout.write(tw(p * 3 + i)); }; const log = (l) => process.stderr.write(l + "\\n"); log("[gallery-dl][debug] Version 1.32.9"); -if (process.env.FAKE_MODE === "known") { +if (process.env.FAKE_SCRIPT) { + // A walk the TEST writes (lane x-followups): FAKE_SCRIPT is a JSON file, + // {"<the cursor given, or ''>": [step, …]}; a step is {posts: [from, to]} + // (tweets from..to, newest first, a minute apart), {err: "a stderr line"}, + // {wait: ms} or {exit: code}. A cursor the script does not know exits 9. + const { readFileSync } = await import("node:fs"); + const steps = JSON.parse(readFileSync(process.env.FAKE_SCRIPT, "utf8"))[cursor ?? ""]; + if (!steps) { log("[twitter][error] the fake knows no cursor " + cursor); process.exit(9); } + const post = (n) => '[2, {"tweet_id": ' + (1899000000000000100n - BigInt(n)) + + ', "date": "' + new Date(Date.UTC(2026, 5, 28, 12) - n * 60000).toISOString().slice(0, 19).replace("T", " ") + + '", "content": "fake ' + n + '", "author": {"name": "faketester"}, "user": {"name": "faketester"}}]\\n'; + for (const step of steps) { + if (step.posts) for (let n = step.posts[0]; n <= step.posts[1]; n++) process.stdout.write(post(n)); + if (step.err) log(step.err); + if (step.wait) await new Promise((r) => setTimeout(r, step.wait)); + if (step.exit !== undefined) process.exit(step.exit); + } + process.exit(0); +} else if (process.env.FAKE_MODE === "known") { page(0); let n = 3; // Distinct tweets from before the archive's newest post: what an incremental @@ -116,7 +134,10 @@ await writeFile( }), ); -const { fetchPosts } = await import("./fetchPosts"); +// An X fetch runs only as the editor's job (X_ONLY_AS_A_JOB): these calls stand where one does. +const { fetchPosts: fetchPostsDirect, X_ONLY_AS_A_JOB } = await import("./fetchPosts"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const fetchPosts = insideEditorJob(fetchPostsDirect); const { readPostFetchState, readSeenPostIds } = await import("../lib/posts-server"); async function lastArgv(): Promise<string[]> { @@ -441,3 +462,297 @@ test("a drain before the fetch starts reads nothing and spawns nothing", async ( assert.equal((await readFile(ARGS_LOG, "utf8")).trim().split("\n").length, before); assert.equal(await readPostFetchState(root), null); }); + +// ── lane x-followups: X is asked only by the editor's jobs ───────────────── + +test("an X fetch outside the editor's job is refused, whatever the mode or the fetcher, and spawns nothing", async () => { + const paths = (await import("../lib/paths")).getPaths(); + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const spawned = async () => (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const before = await spawned(); + const stateBefore = await readFile(path.join(channelRoot, "posts-state.json"), "utf8"); + // The sentence names the door. + assert.equal( + X_ONLY_AS_A_JOB(SLUG), + `${SLUG} is an X channel, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh cookie jar, ` + + `stopped by the X alert and held after a rate limit): nothing was asked. Queue it instead: pnpm ops fetch-posts --json '{"slug":"${SLUG}"}' --wait`, + ); + for (const mode of [{}, { backfill: true }, { full: true }, { older: true }, { limit: 5 }]) { + const r = await fetchPostsDirect({ paths, slug: SLUG, settings: {}, ...mode }); + assert.deepEqual(r, { ok: false, written: 0, skipped: 0, complete: false, error: X_ONLY_AS_A_JOB(SLUG) }, JSON.stringify(mode)); + } + // Every fetcher of the twitter platform: the rule does not hang on `postFetcher`. + for (const postFetcher of ["x-playwright", "x-nitter"]) { + const slug = `fake-${postFetcher}`; + const root = path.join(ROOT, "transcripts", "channels", slug); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher, socialHandle: "faketester", platform: "twitter", name: "Fake (X)", url: "https://x.com/faketester" }), + ); + assert.equal((await fetchPostsDirect({ paths, slug, settings: {} })).error, X_ONLY_AS_A_JOB(slug)); + } + assert.equal(await spawned(), before, "gallery-dl was not started"); + assert.equal(await readFile(path.join(channelRoot, "posts-state.json"), "utf8"), stateBefore, "the fetch state was not touched"); + // Inside a job the same call runs (here: a refusal of its own, further in — no backfill is part-way). + const inside = await asEditorJob(() => fetchPostsDirect({ paths, slug: SLUG, settings: {}, backfill: true })); + assert.notEqual(inside.error, X_ONLY_AS_A_JOB(SLUG)); +}); + +test("`archilyzer posts fetch` on an X channel exits 1 with the sentence naming pnpm ops fetch-posts, and starts no gallery-dl", async () => { + const { execFile } = await import("node:child_process"); + const { createRequire } = await import("node:module"); + const tsx = createRequire(import.meta.url).resolve("tsx/cli"); + const before = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const ran = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => { + const child = execFile( + process.execPath, + [tsx, path.join(import.meta.dirname, "..", "bin", "fetch-posts.ts"), "--slug", SLUG], + { env: { ...process.env, NODE_OPTIONS: "" }, timeout: 60_000 }, + (_err, stdout, stderr) => resolve({ code: child.exitCode, stdout, stderr }), + ); + }); + assert.equal(ran.code, 1, ran.stderr); + assert.equal(ran.stderr.trim(), `Failed: ${X_ONLY_AS_A_JOB(SLUG)}`); + assert.equal(ran.stdout.trim(), ""); + assert.equal((await readFile(ARGS_LOG, "utf8")).trim().split("\n").length, before); +}); + +// ── lane x-followups: the history walk's search phase, and a resumed backfill ── + +// A channel of its own and a walk the test writes (the fake's FAKE_SCRIPT). +async function scripted(slug: string, script: Record<string, unknown[]>) { + const root = path.join(ROOT, "transcripts", "channels", slug); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", socialHandle: "faketester", platform: "twitter", name: "Fake (X)", url: "https://x.com/faketester" }), + ); + const file = path.join(ROOT, `${slug}.script.json`); + writeFileSync(file, JSON.stringify(script)); + const paths = (await import("../lib/paths")).getPaths(); + const run = async (opts: Record<string, unknown> = {}, cancelOn?: RegExp) => { + const controller = new AbortController(); + const log: string[] = []; + process.env.FAKE_SCRIPT = file; + try { + const result = await fetchPosts({ + paths, + slug, + settings: {}, + signal: controller.signal, + onLog: (line) => { + log.push(line); + if (cancelOn?.test(line)) controller.abort(); + }, + ...opts, + }); + return { result, log }; + } finally { + delete process.env.FAKE_SCRIPT; + } + }; + return { root, run }; +} +const RATE_LIMIT = { err: "[twitter][info] Waiting for 14 minutes until 15:11:22 (rate limit)" }; +const cursorArg = async () => (await lastArgv()).find((a) => a.startsWith("extractor.twitter.cursor=")); + +test("a first walk that stops in its SEARCH phase saves the search's place, and Resume backfill continues from there to the timeline's end", async () => { + const { root, run } = await scripted("search-phase", { + "": [ + // The timeline API's pages, each with its cursor… + { posts: [0, 2] }, + { err: "[twitter][debug] Cursor: 1/TL-P1" }, + { posts: [3, 5] }, + { err: "[twitter][debug] Cursor: 1/TL-P2" }, + // …then the search below it: pages by max_id, and no "Cursor:" line at all. + { posts: [6, 8] }, + { err: "[twitter][debug] Next 'max_id': 1899000000000000091" }, + { posts: [9, 11] }, + { err: "[twitter][debug] Next 'max_id': 1899000000000000088" }, + RATE_LIMIT, + { wait: 60_000 }, + ], + "3_1899000000000000088/": [{ posts: [12, 14] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000085" }, { posts: [15, 15] }], + }); + const first = await run({}, /rate limit/); + assert.equal(first.result.ok, true); + assert.equal(first.result.written, 12); + assert.equal(first.result.complete, false); + // The place is the search's last page, not the timeline phase's last cursor (which lies six posts above it). + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000088/"); + + const resumed = await run({ backfill: true }); + assert.equal(await cursorArg(), "extractor.twitter.cursor=3_1899000000000000088/"); + assert.equal(resumed.result.ok, true, resumed.log.join("\n")); + assert.equal(resumed.result.written, 4); + // gallery-dl walked to the end and exited: the timeline's real end. Only that clears the place. + assert.equal(resumed.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); + assert.equal((await readSeenPostIds(root)).size, 16); +}); + +test("a resumed backfill skips posts already archived without stopping, and never ends as \"caught up\"", async () => { + const { root, run } = await scripted("skip-known", { + "": [{ posts: [0, 149] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, RATE_LIMIT, { wait: 60_000 }], + // The place points back into what is archived (as a place saved by an older build does): 130 known posts, then new ones. + "1/TL-P1": [{ posts: [20, 149] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000001" }, { posts: [150, 152] }, RATE_LIMIT, { wait: 60_000 }], + "3_1899000000000000001/": [{ posts: [153, 153] }], + }); + await run({}, /rate limit/); + assert.equal((await readSeenPostIds(root)).size, 150); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P1"); + + const resumed = await run({ backfill: true }, /rate limit/); + assert.equal(resumed.result.ok, true, resumed.log.join("\n")); + assert.equal(resumed.result.written, 3); + assert.equal(resumed.result.complete, false); + assert.ok(!resumed.log.some((l) => /caught up/i.test(l)), resumed.log.join("\n")); + assert.ok(resumed.log.some((l) => /100 already-archived posts in a row: this walk has no watermark, so it skips them and reads on/.test(l))); + assert.ok(resumed.log.some((l) => /gallery-dl read 133 post\(s\): 3 new, 130 already archived/.test(l)), resumed.log.join("\n")); + // Stopped part-way (cancelled here; a budget is the same path): the place moved on, and is still there. + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000001/"); + // …and the next resume ends at the timeline's end. + const last = await run({ backfill: true }); + assert.equal(last.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); + assert.equal((await readSeenPostIds(root)).size, 154); +}); + +test("a resumed backfill that began again from the top stops with a sentence and keeps its place", async () => { + const { X_BACKFILL_RESTARTED_FROM_TOP } = await import("../social/xGalleryDlFetcher"); + const { root, run } = await scripted("top-restart", { + "": [{ posts: [0, 39] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [40, 59] }, { err: "[twitter][debug] Cursor: 1/TL-P2" }, RATE_LIMIT, { wait: 60_000 }], + // The cursor was not honoured: the timeline from its top — a post newer than anything archived, then the archive's newest… + "1/TL-P2": [{ posts: [-1, 30] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [31, 300] }, { wait: 60_000 }], + }); + await run({}, /rate limit/); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P2"); + const started = Date.now(); + const resumed = await run({ backfill: true }); + assert.ok(Date.now() - started < 30_000, "gallery-dl was stopped, not left to walk on"); + assert.equal(resumed.result.ok, false); + assert.equal(resumed.result.error, X_BACKFILL_RESTARTED_FROM_TOP); + assert.equal(resumed.result.complete, false); + assert.ok(!resumed.log.some((l) => /caught up/i.test(l))); + // The place is the one it had. + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/TL-P2"); + // What it read of the top that was new is kept (a post is a post); nothing else was written. + assert.equal(resumed.result.written, 1); + assert.equal((await readSeenPostIds(root)).size, 61); +}); + +test("a sync still stops at known posts, and a full re-walk still reads through them", async () => { + const { root, run } = await scripted("sync-stops", { + "": [{ posts: [0, 149] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, { posts: [150, 150] }], + }); + const first = await run({}); + assert.equal(first.result.written, 151); + assert.equal(first.result.complete, true); + // SYNC NEW: a run of archived posts is where it ends. + const sync = await run({}); + assert.ok(sync.log.some((l) => /Reached 100 already-archived posts in a row — caught up; stopping gallery-dl\./.test(l)), sync.log.join("\n")); + assert.equal(sync.result.complete, true); + assert.equal(sync.result.written, 0); + // A FULL re-walk reads through all of them, to the end. + const full = await run({ full: true }); + assert.ok(!full.log.some((l) => /caught up/i.test(l)), full.log.join("\n")); + assert.ok(full.log.some((l) => /gallery-dl read 151 post\(s\): 0 new, 151 already archived/.test(l)), full.log.join("\n")); + assert.equal(full.result.complete, true); + assert.equal((await readPostFetchState(root))?.backfill, undefined); +}); + +// ── review 1 M1: the Add-channel form's "Fetch details" asks X nothing ───── + +test("M1: no fetcher of the twitter platform probes X — the answer is read off the URL, no binary is started and no request made", async () => { + const { detectSocialFetcher } = await import("../social/fetchers"); + await import("../social/xGalleryDlFetcher"); + await import("../social/xPlaywrightFetcher"); + await import("../social/xNitterFetcher"); + const { xGalleryDlFetcher } = await import("../social/xGalleryDlFetcher"); + const { xPlaywrightFetcher } = await import("../social/xPlaywrightFetcher"); + const { xNitterFetcher } = await import("../social/xNitterFetcher"); + const spawned = async () => (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const before = await spawned(); + // Any request would throw here too: the suite runs with the network refused (lib/noNetwork.mjs). + const realFetch = globalThis.fetch; + let fetched = 0; + globalThis.fetch = (async () => { + fetched++; + throw new Error("a probe made a request"); + }) as typeof fetch; + try { + // The form's own choice for an x.com URL is the gallery-dl fetcher. + assert.equal(detectSocialFetcher("https://x.com/faketester")?.id, "x-gallery-dl"); + for (const fetcher of [xGalleryDlFetcher, xPlaywrightFetcher, xNitterFetcher]) { + assert.equal(fetcher.platform, "twitter"); + for (const url of ["https://x.com/faketester", "https://twitter.com/faketester/", "https://x.com/faketester/with_replies"]) { + assert.deepEqual(await fetcher.probe(url), { ok: true, name: "faketester", handle: "faketester", url: "https://x.com/faketester" }, `${fetcher.id} ${url}`); + } + } + // Not an account: refused from the URL alone. + for (const url of ["https://x.com/", "https://x.com/home", "https://x.com/i/trending/1900000000000000001"]) { + const r = await xGalleryDlFetcher.probe(url); + assert.equal(r.ok, false, url); + assert.match(r.error ?? "", /handle/); + } + } finally { + globalThis.fetch = realFetch; + } + assert.equal(fetched, 0); + assert.equal(await spawned(), before, "gallery-dl was not started"); +}); + +// ── review 1 S1, S2 ──────────────────────────────────────────────────────── + +test("S1: a walk resumed from a search-phase place stops when it reads a post above that place, though the archive holds newer ones", async () => { + const { X_RESUME_POINT_NOT_HONOURED } = await import("../social/xGalleryDlFetcher"); + // Post n has id 1899000000000000100 - n: the place below is "at or below post 60". + const { root, run } = await scripted("ceiling", { + "": [{ posts: [0, 59] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000040" }, RATE_LIMIT, { wait: 60_000 }], + // Not honoured, and NOT from the top either: the walk comes back ten posts above its place. + "3_1899000000000000040/": [{ posts: [50, 300] }, { wait: 60_000 }], + }); + await run({}, /rate limit/); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000040/"); + const started = Date.now(); + const resumed = await run({ backfill: true }); + assert.ok(Date.now() - started < 30_000); + assert.equal(resumed.result.ok, false); + assert.equal(resumed.result.error, X_RESUME_POINT_NOT_HONOURED); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000040/"); + assert.equal((await readSeenPostIds(root)).size, 60); +}); + +test("S2: a resumed backfill whose place is in the timeline phase says it may pass through archived posts first; a search-phase place says nothing", async () => { + const { X_TIMELINE_PHASE_PLACE_NOTE } = await import("../social/xGalleryDlFetcher"); + const { root, run } = await scripted("old-place", { + "": [{ posts: [0, 5] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, RATE_LIMIT, { wait: 60_000 }], + "1/TL-P1": [{ posts: [6, 8] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000091" }, RATE_LIMIT, { wait: 60_000 }], + "3_1899000000000000091/": [{ posts: [9, 9] }], + }); + const first = await run({}, /rate limit/); + assert.ok(!first.log.includes(X_TIMELINE_PHASE_PLACE_NOTE)); + const old = await run({ backfill: true }, /rate limit/); + assert.equal(old.log.filter((l) => l === X_TIMELINE_PHASE_PLACE_NOTE).length, 1); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000091/"); + const next = await run({ backfill: true }); + assert.ok(!next.log.includes(X_TIMELINE_PHASE_PLACE_NOTE)); + assert.equal(next.result.complete, true); +}); + +// ── added scope R2: where X is about to be asked, only a job on X's queue stands ── + +test("R2a: an availability check of an X channel outside the editor's job is refused (the `posts check` command line's path)", async () => { + const { checkPostAvailability } = await import("./checkPostAvailability"); + const paths = (await import("../lib/paths")).getPaths(); + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const outside = await checkPostAvailability({ paths, slug: SLUG }); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^An availability check of fake-x's posts asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops check-post-availability/); + const elsewhere = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG }), { queueKey: "manual" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + // On X's queue it gets as far as its own answer (this fetcher has no availability check). + const inside = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG })); + assert.doesNotMatch(inside.error ?? "", /asks X, and X/); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -94,6 +94,7 @@ import { } from "../social/instagramMedia"; import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; +import { xJobContextRefusal } from "../lib/xJobRule"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -191,6 +192,25 @@ export const INSTAGRAM_ONLY_AS_A_JOB = (slug: string) => `${slug} is an Instagram channel, and Instagram is asked only by the editor's own jobs (one at a time, ten minutes ` + `apart, held after a refusal): nothing was asked. Queue it instead: pnpm ops fetch-posts --json '{"slug":"${slug}"}' --wait`; +// AN X FETCH RUNS ONLY AS THE EDITOR'S JOB TOO (lane x-followups; found by the +// Instagram review). X's guards all live in the job funnel: X's queue (one X +// job at a time), the gap between X jobs, the fresh-jar rule, the X alert, the +// cooldown after a rate limit. A direct call — `pnpm archilyzer posts fetch +// <x-channel>`, a script — met none of them: it asked X at once, on whatever +// jar was there, beside whatever X job the editor was running. Every fetcher +// of the twitter platform is covered (the account's timeline, the older walk, +// an X search channel; gallery-dl, the Playwright fallback, Nitter), since the +// channel's `postFetcher` is the operator's to change and the rule must not +// depend on it. Bluesky, a forum thread and a web page keep the direct path: +// their pacing is the fetcher's own (a forum's page pause, its browser +// profile), and `posts fetch --pages N` on a forum thread is a documented way +// to read without an editor (README). +const X_FETCH_DOOR = (slug: string) => `pnpm ops fetch-posts --json '{"slug":"${slug}"}' --wait`; +export const X_ONLY_AS_A_JOB = (slug: string) => + `${slug} is an X channel, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh ` + + `cookie jar, stopped by the X alert and held after a rate limit): nothing was asked. ` + + `Queue it instead: pnpm ops fetch-posts --json '{"slug":"${slug}"}' --wait`; + // A channel's fetcher is of the channel's platform (review 1, M3): a config // naming X's fetcher on an Instagram channel (or the other way round) would // run one platform's requests on another's queue, past its guard. @@ -387,6 +407,15 @@ export async function fetchPosts( const mismatch = fetcherPlatformMismatch(slug, config, fetcher); if (mismatch) return { ok: false, written: 0, skipped: 0, complete: false, error: mismatch }; + // X: only inside a job of the editor's (X_ONLY_AS_A_JOB says why). Asked + // before the search, older and timeline branches, so no mode slips past. + if (fetcher.platform === "twitter") { + if (!currentJobContext()) return { ok: false, written: 0, skipped: 0, complete: false, error: X_ONLY_AS_A_JOB(slug) }; + // …and only on X's queue (added scope R2): asked where the job runs too. + const queue = xJobContextRefusal(slug, X_FETCH_DOOR(slug)); + if (queue) return { ok: false, written: 0, skipped: 0, complete: false, error: queue }; + } + // AN X SEARCH CHANNEL (release 38): its query across accounts, walked in // search windows — no handle, no timeline, no older walk (fetchXSearch.ts). if (isXSearchChannel(config) && config.xSearch) { @@ -719,7 +748,10 @@ async function fetchTimeline(ctx: { ...(config.postPagePauseSeconds ? { pagePauseMs: config.postPagePauseSeconds * 1000 } : {}), - stopAtKnown: !opts.full, + // Known posts end a SYNC. A full re-walk reads through them on purpose, + // and a resumed backfill has no watermark: it skips them and reads on. + stopAtKnown: !opts.full && !opts.backfill, + ...(plan?.mode === "backfill" ? { resumedBackfill: true } : {}), onCheckpoint, signal: effectiveSignal, drain: opts.drain, @@ -746,6 +778,11 @@ async function fetchTimeline(ctx: { }; } + // A backfill is not finished by meeting known posts (settleTimelineRun). + if (plan?.mode === "backfill" && result.complete && result.caughtUp) { + result = { ...result, complete: false }; + log("The backfill met posts already archived and stopped there: that is not the timeline's end. Its resume point is kept."); + } const final = await write(result.posts); for (const shard of final.shards) shards.add(shard); const written = { diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -911,3 +911,53 @@ test("a source-less posts channel's window is refused with its sentence, whateve assert.equal(looked, 0, "no source URL was looked up for it"); assert.equal(r.fetched.length, 1, "the run goes on"); }); + +// Review 3 M1: a window job on `clips:saved-video` is exempt from X's queue +// rule because it cuts from disk. When the saved copy is gone (or no longer +// covers) by the time it runs, an X source's window is NEVER fetched from +// that queue: it fails with a sentence, and nothing is asked of X. Off that +// queue, an X window is fetched only by a job on X's own queue. +const X_CONFIG = { url: "https://x.com/example", platform: "twitter", sourceKind: "social" } as unknown as ChannelConfig; +const jobCtx = (queueKey: string) => ({ jobId: "j-r3", kind: "fetch-windows", queueKey, onLog: () => {}, staleServices: new Set<string>() }); +const xItems = (): FetchWindowsItem[] => [ + // An X channel's window, and an x.com video filed on a YouTube channel. + { ...item("1900000000000002001", "/ok"), slug: "xc", webpageUrl: "https://x.com/example/status/1900000000000002001" }, + { ...item("v9", "/ok"), webpageUrl: "https://x.com/example/status/1900000000000002002" }, + // An X channel's window with no URL of its own: its channel's page. + { slug: "xc", id: "1900000000000002003", from: 1, to: 2 }, +]; + +test("review 3 M1: on clips:saved-video an X source's window whose saved copy is gone is refused, never fetched", async () => { + const { runInJobContext } = await import("../lib/jobContext"); + const h = harness({ + readChannelConfig: async (_p, slug) => (slug === "xc" ? X_CONFIG : CONFIG), + findVideoSourceUrl: async (_p, _slug, id) => `https://x.com/example/status/${id}`, + }); + const before = await spawns(); + // No saved copy is on disk: it was removed after the batch was planned. + const r = await runInJobContext(jobCtx("clips:saved-video"), async () => go(await corpus(), [...xItems(), item("v2", "/ok")], h)); + assert.deepEqual(r.failed.map((f) => f.class), ["cut-failed", "cut-failed", "cut-failed"]); + for (const f of r.failed) { + assert.match(f.message, /^the saved copy no longer covers this window; ask again and it runs on X's queue/); + } + assert.equal(r.fetched.length, 1, "the YouTube window is not X's: it goes on as before"); + assert.equal((await spawns()) - before, 1, "nothing was asked of X"); +}); + +test("review 3 M1/M2: off clips:saved-video an X window is fetched only by a job on X's queue", async () => { + const { runInJobContext } = await import("../lib/jobContext"); + const h = harness({ + readChannelConfig: async (_p, slug) => (slug === "xc" ? X_CONFIG : CONFIG), + findVideoSourceUrl: async (_p, _slug, id) => `https://x.com/example/status/${id}`, + }); + const before = await spawns(); + const off = await runInJobContext(jobCtx("clips:youtube"), async () => go(await corpus(), xItems(), h)); + assert.equal(off.fetched.length, 0); + for (const f of off.failed) assert.match(f.message, /X jobs run on X's queue only/); + assert.equal(off.failed.length, 3); + const none = await go(await corpus(), xItems().slice(0, 1), h); + assert.match(none.failed[0]?.message ?? "", /X is asked only by the editor's own jobs/); + assert.equal((await spawns()) - before, 0, "nothing was asked of X"); + const on = await runInJobContext(jobCtx("platform:twitter"), async () => go(await corpus(), xItems().slice(0, 1), h)); + assert.equal(on.fetched.length, 1, "on X's queue it is fetched"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -22,6 +22,9 @@ import { isSourceSideCopyFailure, recordFailedCopy, type FailedCopy } from "../l import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelMediaReachable, assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; +import { currentJobContext } from "../lib/jobContext"; +import { isXUrl, xJobContextRefusal } from "../lib/xJobRule"; +import { SAVED_VIDEO_CLIP_QUEUE } from "../lib/queueKeys"; import { findInSyncContainingClipWindow, findInSyncTieredWindowHolding, @@ -1052,6 +1055,24 @@ export async function fetchWindows({ progress(); continue; } + // AN X SOURCE IS FETCHED ONLY BY A JOB ON X'S QUEUE (review 3 M1/M2). + // A batch on `clips:saved-video` passed X's queue rule because it cuts + // from disk (lib/xJobRule.ts xJobAsksX); its saved copy gone or short by + // now, it never goes to x.com from there. Anywhere else, the rule where + // X is asked (xJobContextRefusal): inside a job, on X's queue. + if (isXUrl(url)) { + const job = currentJobContext(); + const refusal = + job?.queueKey === SAVED_VIDEO_CLIP_QUEUE + ? "the saved copy no longer covers this window; ask again and it runs on X's queue (nothing was asked of X)" + : xJobContextRefusal(`The window ${label}`, "pnpm ops fetch-windows --json '{…}' (it queues X's windows on X's queue)"); + if (refusal) { + fail(item, job?.queueKey === SAVED_VIDEO_CLIP_QUEUE ? "cut-failed" : "no-url", refusal); + done += 1; + progress(); + continue; + } + } // The cooldown's key, as the single fetch and every download path use it. const platform = detectPlatform(url) ?? "unknown"; const whole = wholeRecordingFor(settings, platform, item, wholeRecording); diff --git a/common/controller/fetchXSearch.test.ts b/common/controller/fetchXSearch.test.ts @@ -95,7 +95,10 @@ async function makeSearchChannel(slug: string, xSearch: Record<string, unknown>) return channelRoot; } -const { fetchPosts } = await import("./fetchPosts"); +// An X fetch runs only as the editor's job (X_ONLY_AS_A_JOB): these calls stand where one does. +const { fetchPosts: fetchPostsDirect, X_ONLY_AS_A_JOB } = await import("./fetchPosts"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const fetchPosts = insideEditorJob(fetchPostsDirect); const { X_SEARCH_OLDER_REFUSAL } = await import("./fetchXSearch"); const { readPostFetchState, readSeenPostIds, readAllPosts, writePosts, writePostFetchState } = await import( "../lib/posts-server" @@ -296,3 +299,16 @@ test("a post another X channel holds is kept in the search channel too, once — assert.match(full.log.join("\n"), /read 2 post\(s\), 0 new, 2 already archived/); assert.match(full.log.join("\n"), /Starting the search walk afresh, as asked/); }); + +// Lane x-followups: X is asked only by the editor's jobs — an X search channel too. +test("an X search fetch outside the editor's job is refused and spawns nothing", async () => { + const slug = "outside-search"; + await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01", until: "2025-03-01" }); + const before = (await argvLines()).length; + for (const mode of [{}, { full: true }, { older: true }, { backfill: true }]) { + const r = await fetchPostsDirect({ paths: getPaths(), slug, settings: LOGIN, olderWindowPauseMs: 0, ...mode }); + assert.equal(r.ok, false); + assert.equal(r.error, X_ONLY_AS_A_JOB(slug), JSON.stringify(mode)); + } + assert.equal((await argvLines()).length, before); +}); diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts @@ -25,8 +25,10 @@ // attach-media's walk (controller/attachMedia.ts) instead. // // The job is `import-media` on its own queue (`import-media:<slug>`): a -// multi-GB copy never holds a platform's download queue. `needsMedia`: it -// writes the container and the audio. +// multi-GB copy never holds a platform's download queue — except an import by +// an X page's address (x.com, twitter.com, t.co), which asks X for its +// metadata and so runs on X's queue on any channel (review 4 B). `needsMedia`: +// it writes the container and the audio. import { localMediaWriteRefusal } from "./localMediaDoors"; import path from "node:path"; @@ -64,6 +66,8 @@ import { } from "./landMedia"; import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; +import { X_QUEUE_KEY, isXUrl, xJobContextRefusal } from "../lib/xJobRule"; + export const IMPORT_MEDIA_JOB_KIND = "import-media"; export const IMPORT_MEDIA_RESULT_MARKER = "@@import-media "; @@ -71,6 +75,14 @@ export function importMediaQueueKey(slug: string): string { return `import-media:${slug}`; } +// THE JOB'S QUEUE (review 4 B): an import by an X page's address — x.com, +// twitter.com, t.co (lib/xJobRule.ts isXUrl) — asks X for its metadata, so it +// runs on X's queue, under the jar rule and X's job cap, on ANY channel. +// Everything else on its own queue. +export function importMediaJobQueueKey(slug: string, target: ImportTarget): string { + return target.kind === "url" && isXUrl(target.url) ? X_QUEUE_KEY : importMediaQueueKey(slug); +} + // A path the action hands to attach-media's walk rather than landing itself. export function isArchivePath(p: string, isDirectory: boolean): boolean { return isDirectory || /\.(zip|7z)$/i.test(p); @@ -101,7 +113,8 @@ export async function resolveImportTarget( if (req.id && req.id !== id) { return { error: `"id" ${req.id} is not the id ${req.url} is archived by (${id}); give one of them` }; } - const platform = detectPlatform(req.url) ?? "unknown"; + // X's addresses (t.co and X's media hosts too) are X's pace and holds. + const platform = isXUrl(req.url) ? "twitter" : (detectPlatform(req.url) ?? "unknown"); return { kind: "url", id, url: req.url, platform, exists: await hasInfo(path.join(dataDir, id)) }; } if (req.meta) { @@ -176,6 +189,15 @@ export async function importMediaRun( } else if (held || cooling > 0) { throw new Error(held ?? `${target.platform} is in a rate-limit cooldown; import once it lapses`); } else { + // THE BELT (review 4 B): an X address is asked of yt-dlp only inside + // a job on X's queue — nothing else spaces it, jars it or counts it. + if (isXUrl(target.url)) { + const outside = xJobContextRefusal( + `The metadata fetch of ${target.url}`, + `pnpm ops import-media --json '{"slug":"${req.slug}","path":"…","url":"…"}' (it queues an X page on X's queue)`, + ); + if (outside) throw new Error(outside); + } const created = !(await isDir(videoDir)); await mkdir(videoDir, { recursive: true }); try { @@ -329,7 +351,10 @@ export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<Strea } return runManagedFunction({ kind: IMPORT_MEDIA_JOB_KIND, - queueKey: importMediaQueueKey(req.slug), + // An X page's address asks X: X's queue (importMediaJobQueueKey), and the + // guards judge it by that address (lib/xJobRule.ts xJobAsksX). + queueKey: importMediaJobQueueKey(req.slug, target), + ...(target.kind === "url" ? { askParams: { url: target.url } } : {}), paths, channelSlug: req.slug, videoId: target.id, diff --git a/common/controller/landMedia.test.ts b/common/controller/landMedia.test.ts @@ -28,7 +28,7 @@ await writeFile(process.env.SETTINGS_FILE, "{}"); const { getPaths } = await import("../lib/paths"); const { landMediaFile, transcriptionHandoffLines } = await import("./landMedia"); -const { importMediaRun, resolveImportTarget } = await import("./importMedia"); +const { importMediaJobQueueKey, importMediaRun, resolveImportTarget } = await import("./importMedia"); const { mediaImportSidecar } = await import("../lib/mediaImport-server"); const { loadSavedVideo } = await import("../lib/savedVideo-server"); const { isDoNotClean } = await import("../lib/doNotClean-server"); @@ -219,6 +219,37 @@ test("import by url: one metadata pass makes the record under the URL id", async assert.match(archive, /^RumbleEmbed v8embed$/m); }); +test("review 4 B: an import by an X page's address (t.co included) is X's: X's queue on any channel, and never asked of yt-dlp outside an X job", async () => { + const urlTarget = (url: string) => ({ kind: "url" as const, id: "1", url, platform: "unknown", exists: false }); + for (const url of ["https://t.co/AbC123", "https://x.com/u/status/1", "https://mobile.twitter.com/u/status/1"]) { + assert.equal(importMediaJobQueueKey(SLUG, urlTarget(url)), "platform:twitter", url); + } + assert.equal(importMediaJobQueueKey(SLUG, urlTarget("https://rumble.com/v9abcde-a-stream.html")), `import-media:${SLUG}`); + assert.equal(importMediaJobQueueKey(SLUG, { kind: "id", id: "1" }), `import-media:${SLUG}`); + // The belt: outside a job on X's queue, no metadata pass is asked of an X address. + const calls: string[][] = []; + const refresh = async (_cwd: string, args: string[]): Promise<AttemptOutcome> => { + calls.push(args); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; + const req = { slug: SLUG, path: await fake("x.mp4", "mov,mp4,m4a", 30), url: "https://t.co/AbC123" }; + await assert.rejects( + importMediaRun({ + paths, + request: req, + channelConfig: CONFIG, + cookiePolicy: { cookies: undefined, mode: "when-required" }, + target: { kind: "url", id: "AbC123", url: req.url, platform: "unknown", exists: false } as never, + onLog, + signal, + deps: { refresh, land: deps }, + }), + /asks X, and X is asked only by the editor's own jobs/, + ); + assert.equal(calls.length, 0, "yt-dlp was not asked"); + await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "AbC123")), "no record dir was made"); +}); + test("the store's root: the corpus default is made when missing; an override or a dangling link is refused", async () => { const { ensureStoreRoot } = await import("./landMedia"); const { symlink } = await import("node:fs/promises"); diff --git a/common/controller/publishXTrending.test.ts b/common/controller/publishXTrending.test.ts @@ -631,3 +631,42 @@ test("S8: a file whose bytes are no longer what its capture recorded is not publ await deleteChannel(paths, "zzlibs8"); await deleteChannel(paths, "s8-channel"); }); + +// Review 1 S5. +test("S5: a dry run says when the topic is named by X's page, not by a person; the slug is still the caller's to name; a rename ends it", async () => { + const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); + const lib = "zzpagetitledlib"; + const libRoot = path.join(paths.channelsDir, lib); + await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); + await writeXTrendingPosts(libRoot, [post(lib, "901", "words of 901"), post(lib, "902", "words of 902")]); + // Nobody named the topic: it took the page's title. + await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["901"], added: 1, page: { title: "Kettle festival opens" } }); + await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["902"], added: 1 }); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "901", state: "keep" }, { id: "902", state: "keep" }] }); + const ask = { slug: lib, topic: `t-${REF.trendId}`, deriveSlug: derive, busy: IDLE }; + const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(dry.ok, dry.ok ? "" : dry.error); + assert.equal(dry.result.titleFrom, "page"); + assert.equal(dry.result.channel, "kettle-festival-opens"); + assert.equal( + dry.result.sentence, + 'Publishing "Kettle festival opens" would make the channel "kettle-festival-opens", on no site, writing 1 post and 0 files (0 B); 0 of the 1 kept post are there already. ' + + `The topic is named by X's page: "Kettle festival opens" — the channel would carry that name. Rename the topic first to publish under your own name; "channel" names another slug than "kettle-festival-opens".` + + " 1 post has no capture yet and is published as its words alone: a later publish adds the files.", + ); + // The slug is the caller's to name, as before. + const named = await publishXTrendingTopic(paths, { ...ask, channel: "my-kettles", dryRun: true }); + assert.ok(named.ok && named.result.channel === "my-kettles" && named.result.titleFrom === "page"); + // A topic made under a name asked for: said to be so, and no such sentence. + const cups = await publishXTrendingTopic(paths, { ...ask, topic: "cups", dryRun: true }); + assert.ok(cups.ok); + assert.equal(cups.result.titleFrom, "ask"); + assert.doesNotMatch(cups.result.sentence, /named by X's page/); + // Renamed by a person: the name is theirs. + assert.equal((await renameXTrendingTopic(libRoot, { topic: `t-${REF.trendId}`, title: "Kettles, my pick", by: "operator", readInFlight: IDLE })).ok, true); + const after = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(after.ok); + assert.equal(after.result.titleFrom, "rename"); + assert.doesNotMatch(after.result.sentence, /named by X's page/); + rmSync(libRoot, { recursive: true, force: true }); +}); diff --git a/common/controller/publishXTrending.ts b/common/controller/publishXTrending.ts @@ -83,6 +83,8 @@ import { readXTrendingPosts, readXTrendingTopics, resolveXTrendingTopic, + xTrendingTitleFrom, + type XTrendingTitleFrom, xTrendingPostsMediaDir, xTrendingPostsRoot, } from "../lib/xTrending/store"; @@ -313,6 +315,11 @@ export type PublishXTrendingResult = { dryRun: boolean; library: string; topic: { id: string; title: string }; + // WHERE THE TOPIC'S NAME CAME FROM (review 1 S5): "page" — nobody named it + // and it carries its trending page's title, X's words; "ask" or "rename" — + // a person or an agent set it. Absent for the fallback name. The channel a + // first publish makes is called by the topic's name. + titleFrom?: XTrendingTitleFrom; // The channel the posts go into, and whether this publish makes it. channel: string; creates: boolean; @@ -409,10 +416,16 @@ export function publishSentence(r: Omit<PublishXTrendingResult, "sentence">): st const gone = r.noLongerKept.length ? ` ${n(r.noLongerKept.length, "post")} published before ${r.noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${r.noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).` : ""; + // A channel about to be made under X's own words for the page (review 1 S5). + const named = + r.creates && r.titleFrom === "page" + ? ` The topic is named by X's page: "${r.topic.title}" — the channel ${would ? "would carry" : "carries"} that name. ` + + (would ? `Rename the topic first to publish under your own name; "channel" names another slug than "${r.channel}".` : "A rename of the channel is its own step.") + : ""; const copies = r.files > 0 ? " The files are copies: the library keeps its own." : ""; const site = r.creates && !would && r.sites.length === 0 ? " Adding the channel to a site is a separate step." : ""; const waits = r.inFlight ? " A read or a capture of this library is queued or running: the publish waits for it." : ""; - return `${head}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; + return `${head}${named}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; } // ── the plan ─────────────────────────────────────────────────────────────── @@ -655,11 +668,13 @@ export async function publishXTrendingTopic( const look = async () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, record: (await readXTrendingPublished(libRoot))[topic.id], digests }); const digest = (p: Plan) => xTrendingPublishConfirm({ library: ask.slug, topic: topic.id, channel, ids: p.fresh.map((x) => x.id), files: p.files.map((f) => `${f.id}/${f.name}`), sites: p.sites }); + const titleFrom = xTrendingTitleFrom(topic); const answer = (p: Plan, dryRun: boolean, inFlight: boolean): PublishXTrendingResult => { const r: Omit<PublishXTrendingResult, "sentence"> = { dryRun, library: ask.slug, topic: { id: topic.id, title: topic.title }, + ...(titleFrom ? { titleFrom } : {}), channel, creates: p.creates, sites: p.sites, diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -12,7 +12,14 @@ import type { Paths } from "../lib/paths"; import { listXTrending, readXTrendingPosts, readXTrendingReadRecord } from "../lib/xTrending/store"; import { fakeTrendingPage, type FakeTrendingPage } from "../social/fakeXProfileBrowser"; import { + FIXTURE_LATEST_PAGE, + fixtureLatestContinuation, + fixtureLatestFirst, + fixtureTwoTabResponses, + FIXTURE_LAST_UPDATED_MS, + FIXTURE_SUMMARY, FIXTURE_TIMELINE_OP, + FIXTURE_TITLE, FIXTURE_TREND_ID, FIXTURE_TREND_URL, fixtureContinuation, @@ -23,14 +30,19 @@ import { NO_X_PROFILE_FOR_TRENDING, planReadXTrending, reparseXTrendingRead, - runXTrendingRead, + runXTrendingRead as runXTrendingReadDirect, type ReadXTrendingAsk, type ReadXTrendingResult, } from "./readXTrending"; +import { insideEditorJob } from "../testing/jobs/asEditorJob"; + +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const TMP = mkdtempSync(path.join(tmpdir(), "read-x-trending-")); after(() => rmSync(TMP, { recursive: true, force: true })); +const FIXTURE_FIRST_PAGE_0 = { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] as Array<"photo"> }; const READ_1 = "tr-01JA0000000000000000000000"; const READ_2 = "tr-01JB0000000000000000000000"; @@ -52,9 +64,18 @@ async function run( paths: Paths, trending: FakeTrendingPage, ask: Partial<ReadXTrendingAsk> = {}, - over: { readId?: string; at?: string; profileBusy?: () => string | null; held?: () => Promise<string | null>; ingest?: never; openPage?: never } = {}, + over: { + readId?: string; + at?: string; + profileBusy?: () => string | null; + held?: () => Promise<string | null>; + ingest?: never; + openPage?: never; + timeouts?: { call?: number; read?: number }; + } = {}, ): Promise<{ result: ReadXTrendingResult; notes: Array<Record<string, unknown>>; log: string[]; limited: number; cleaned: number }> { - const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, ...ask }, withProfile); + // One tab unless a test asks for both: the page's other tab is R3's tests' (at the end). + const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["top"], ...ask }, withProfile); assert.ok(planned.ok, planned.ok ? "" : planned.error); assert.equal(planned.plan.mode, "read"); const notes: Array<Record<string, unknown>> = []; @@ -76,6 +97,7 @@ async function run( pause: async () => {}, now: () => Date.parse(over.at ?? "2026-11-17T10:00:00.000Z"), readId: over.readId ?? READ_1, + ...(over.timeouts ? { timeouts: over.timeouts } : {}), ...(over.profileBusy ? { profileBusy: over.profileBusy } : {}), noteOutcome: async (_p, outcome) => { notes.push(outcome as Record<string, unknown>); @@ -102,8 +124,8 @@ test("every refusal before a job is a sentence", async () => { assert.match(await error(plan({})), /Give "url" .* or "reparse"/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, reparse: READ_1 })), /holds no saved read/); assert.match(await error(plan({ url: "https://x.com/example/status/1" })), /not a trending page URL/); - assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 21 })), /"scrolls" is a whole number, 1–20/); - assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 201 })), /"posts" is a whole number, 1–200/); + assert.match(await error(plan({ url: FIXTURE_TREND_URL, scrolls: 41 })), /"scrolls" is a whole number, 1–40/); + assert.match(await error(plan({ url: FIXTURE_TREND_URL, posts: 401 })), /"posts" is a whole number, 1–400/); assert.match(await error(plan({ url: FIXTURE_TREND_URL, topic: " " })), /topic/); assert.equal(await error(plan({ url: FIXTURE_TREND_URL }, { hasProfile: async () => false })), NO_X_PROFILE_FOR_TRENDING); assert.match(await error(plan({ reparse: "nope" })), /not a trending read id/); @@ -125,7 +147,7 @@ test("a read writes the page's posts, records the read against a topic, and says assert.deepEqual(result.topic, { id: "kettle-festival", title: "Kettle Festival", created: true }); assert.equal( result.sentence, - `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival).`, + `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab.`, ); // A clean request was noted; no alert. assert.deepEqual(notes, [{ url: FIXTURE_TREND_URL, channel: "trending" }]); @@ -185,7 +207,19 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit const listing = await listXTrending(root(paths)); assert.equal(listing.total, 4); assert.deepEqual(listing.topics[0].sources, [ - { trendId: FIXTURE_TREND_ID, url: FIXTURE_TREND_URL, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" }, + // X's own words and tabs, from the first read's capture; the second read's capture had no page answer. + { + trendId: FIXTURE_TREND_ID, + url: FIXTURE_TREND_URL, + title: FIXTURE_TITLE, + summary: FIXTURE_SUMMARY, + lastUpdatedAt: new Date(FIXTURE_LAST_UPDATED_MS).toISOString(), + tabs: ["Top", "Latest"], + // The second capture named only a timeline id: the source's known tabs say which tab that is. + lastReadTab: "Top", + reads: 2, + lastReadAt: "2026-11-17T12:00:00.000Z", + }, ]); const twice = listing.posts.find((p) => p.id === "1900000000000001004"); assert.deepEqual(twice?.reads.map((r) => r.read), [READ_1, READ_2]); @@ -437,7 +471,7 @@ test("a reparse updates the topic's record of the read: what the capture holds, await reparseXTrendingRead({ plan: planned.plan as never }); const { readXTrendingTopics } = await import("../lib/xTrending/store"); const [topic] = await readXTrendingTopics(root(paths)); - assert.deepEqual(topic.sources[0].reads, [{ id: READ_1, at: "2026-11-17T10:00:00.000Z", posts: 4, added: 4 }]); + assert.deepEqual(topic.sources[0].reads, [{ id: READ_1, at: "2026-11-17T10:00:00.000Z", posts: 4, added: 4, tab: "Top" }]); }); test("the captures are never committed: the reads directory ignores everything under it", async () => { @@ -595,3 +629,330 @@ test("S2: a read that went idle without the capture showing the page's end marks const ended = await reread("s2-end", { load: [timeline], scrolls: [[fixtureContinuation()], []] }); assert.deepEqual([...(ended.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); }); + +// ── lane x-followups: the real page's shape ──────────────────────────────── + +test("the real shape: a read with no topic named makes one called by the page's title, and says which tab it saw", async () => { + const real = await import("../social/__fixtures__/xTrendingRealShape"); + const paths = corpus("real-read"); + const all = real.realCaptureResponses(); + // The real read's order: the page's answers on load, one continuation per scroll. + const { result } = await run(paths, { load: all.slice(0, 6), scrolls: all.slice(6).map((r) => [r]) }, { url: real.INVENTED_TREND_URL }); + assert.equal(result.outcome, "read"); + assert.deepEqual(result.posts, { onPage: 6, added: 6 }); + assert.deepEqual(result.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: true }); + assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 4, stop: "idle", pageEnd: false }]); + assert.equal( + result.sentence, + `Read ${real.INVENTED_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), shown by the page's "Top" tab.`, + ); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.deepEqual(record?.tabs, result.tabs); + // read.json: names, labels and sizes — no timeline id, no summary, no post. + const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8"); + for (const never of [real.INVENTED_TOP_TIMELINE, real.INVENTED_LATEST_TIMELINE, real.INVENTED_SUMMARY, "festival opens today", "teapot_news", real.realBottomCursor(1)]) { + assert.ok(!recordText.includes(never), `read.json carries no "${never}"`); + } + const listing = await listXTrending(root(paths)); + assert.deepEqual(listing.topics[0].sources, [ + { + trendId: real.INVENTED_TREND_ID, + url: real.INVENTED_TREND_URL, + title: real.INVENTED_TITLE, + summary: real.INVENTED_SUMMARY, + lastUpdatedAt: new Date(real.INVENTED_LAST_UPDATED_MS).toISOString(), + tabs: ["Top", "Latest"], + lastReadTab: "Top", + reads: 1, + lastReadAt: "2026-11-17T10:00:00.000Z", + }, + ]); + assert.ok(listing.posts.every((p) => p.reads.length === 1 && p.reads[0].tab === "Top")); + // The scrolls all brought new posts: the read asserts nothing about what the page no longer shows. + assert.equal(result.gone, undefined); +}); + +test("the real shape: a library read before titles were parsed is put right by a reparse — the name, X's words, the tab — and a renamed topic is left alone", async () => { + const real = await import("../social/__fixtures__/xTrendingRealShape"); + const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); + const all = real.realCaptureResponses(); + const fallback = `Trending ${real.INVENTED_TREND_ID}`; + const topicsFile = (paths: Paths) => path.join(root(paths), "trending", "topics.json"); + const membersFile = (paths: Paths) => path.join(root(paths), "trending", "membership.json"); + // What slice 1 left of such a read: the fallback name, a source with no words, sightings with no tab. + const asSlice1Left = (paths: Paths) => { + const topics = JSON.parse(readFileSync(topicsFile(paths), "utf8")); + topics.topics[0].title = fallback; + for (const key of ["title", "summary", "lastUpdatedAt", "tabs"]) delete topics.topics[0].sources[0][key]; + for (const r of topics.topics[0].sources[0].reads) delete r.tab; + writeFileSync(topicsFile(paths), JSON.stringify(topics)); + const members = JSON.parse(readFileSync(membersFile(paths), "utf8")); + for (const m of Object.values(members.posts) as Array<{ seen: Array<{ tab?: string }> }>) for (const s of m.seen) delete s.tab; + writeFileSync(membersFile(paths), JSON.stringify(members)); + }; + const reparse = async (paths: Paths) => { + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.ok(planned.ok && planned.plan.mode === "reparse", planned.ok ? "" : planned.error); + return reparseXTrendingRead({ plan: planned.plan as never, now: () => Date.parse("2026-11-18T09:00:00.000Z") }); + }; + + const paths = corpus("real-reparse"); + await run(paths, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); + asSlice1Left(paths); + const done = await reparse(paths); + assert.equal(done.ok, true); + assert.deepEqual(done.posts, { onPage: 6, added: 0 }); + assert.deepEqual(done.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: false, renamed: { was: fallback } }); + assert.equal( + done.sentence, + `Parsed ${READ_1} again (${real.INVENTED_TREND_URL}): 6 posts in the capture, 0 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), ` + + `shown by the page's "Top" tab. X was asked nothing. The topic was "${fallback}" until now: it took the page's title.`, + ); + const topic = JSON.parse(readFileSync(topicsFile(paths), "utf8")).topics[0]; + assert.equal(topic.title, real.INVENTED_TITLE); + assert.equal(topic.sources[0].summary, real.INVENTED_SUMMARY); + assert.equal(topic.sources[0].reads[0].tab, "Top"); + const members = JSON.parse(readFileSync(membersFile(paths), "utf8")).posts as Record<string, { seen: Array<{ tab?: string }> }>; + assert.ok(Object.values(members).every((m) => m.seen.length === 1 && m.seen[0].tab === "Top")); + const record = await readXTrendingReadRecord(root(paths), READ_1); + // The reparse keeps what the read knew of the tab (its scrolls, why it stopped) and says again what the capture holds. + assert.deepEqual(record?.tabs, [{ tab: "Top", asked: "top", posts: 6, scrolls: 2, stop: "idle", pageEnd: false }]); + assert.deepEqual(record?.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE }); + // A second reparse renames nothing and says nothing of a rename. + assert.doesNotMatch((await reparse(paths)).sentence, /until now/); + + // The operator (or an agent) renamed the topic first: the reparse fills X's words on the source and leaves the name. + const named = corpus("real-reparse-named"); + await run(named, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); + asSlice1Left(named); + assert.equal((await renameXTrendingTopic(root(named), { topic: `t-${real.INVENTED_TREND_ID}`, title: "Kettles, my pick", by: "operator", readInFlight: () => false })).ok, true); + const kept = await reparse(named); + assert.equal(kept.topic?.title, "Kettles, my pick"); + assert.equal(kept.topic?.renamed, undefined); + const after = JSON.parse(readFileSync(topicsFile(named), "utf8")).topics[0]; + assert.equal(after.title, "Kettles, my pick"); + assert.equal(after.sources[0].title, real.INVENTED_TITLE); +}); + +test("the real shape: gone from the page is said after a read whose bottom continuation (cursors in TimelineReplaceEntry) brought nothing new, and never after a capped or failed one", async () => { + const real = await import("../social/__fixtures__/xTrendingRealShape"); + const base = real.realCaptureResponses({ later: [] }).slice(0, -1); + // First read: the three posts of the first page and the two of the second. + const seed = async (name: string) => { + const paths = corpus(name); + await run(paths, { load: [...base, real.realContinuation(real.INVENTED_SECOND, { n: 2 })], scrolls: [] }, { url: real.INVENTED_TREND_URL }); + return paths; + }; + const second = (paths: Paths, scrolls: FakeTrendingPage["scrolls"]) => + run(paths, { load: base, scrolls }, { url: real.INVENTED_TREND_URL }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + // To the end: the continuation from the first answer's bottom cursor brings one post, the one after it none. + const ended = await second(await seed("real-gone-end"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [real.realContinuation([], { n: 3 })], []]); + assert.equal(ended.result.stop, "idle"); + assert.deepEqual(ended.result.gone, ["1900000000000003005"]); + // Capped (the scroll cap, with posts still arriving): nothing. + const capped = await second(await seed("real-gone-capped"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })]]); + assert.equal(capped.result.gone, undefined); + // The last answer failed: nothing. + const last = real.realContinuation([], { n: 3 }); + const failed = await second(await seed("real-gone-failed"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [{ url: last.url, status: 500, text: "upstream error" }], []]); + assert.equal(failed.result.stop, "idle"); + assert.equal(failed.result.gone, undefined); +}); + +// Review 1 S3. +test("S3: a post first seen in an answer that named no timeline does not drop the read's tab; it inherits the one named tab", async () => { + const real = await import("../social/__fixtures__/xTrendingRealShape"); + const { readTabOf } = await import("./readXTrending"); + assert.equal(readTabOf([{ tab: "Top" }, {}]), "Top"); + assert.equal(readTabOf([{ tab: "Top" }, { tab: "Latest" }, {}]), undefined); + assert.equal(readTabOf([{}]), undefined); + assert.equal(readTabOf([]), undefined); + const paths = corpus("s3-untagged"); + // One more answer listing a post, whose request names no timeline at all. + const stray = { url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline?variables=%7B%7D", status: 200, body: fixtureTimelineBody([{ id: "1900000000000003099", handle: "stray_post", text: "Listed by an answer that names no timeline." }]) }; + const { result } = await run(paths, { load: [...real.realCaptureResponses({ later: [] }), stray], scrolls: [] }, { url: real.INVENTED_TREND_URL }); + assert.deepEqual(result.tabs, [{ tab: "Top", asked: "top", posts: 3, scrolls: 2, stop: "idle", pageEnd: false }, { posts: 1, pageEnd: false }]); + assert.match(result.sentence, /shown by the page's "Top" tab\.$/); + const topic = JSON.parse(readFileSync(path.join(root(paths), "trending", "topics.json"), "utf8")).topics[0]; + assert.equal(topic.sources[0].reads[0].tab, "Top"); + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.equal(members["1900000000000003099"].seen[0].tab, "Top"); + assert.equal(members["1900000000000003001"].seen[0].tab, "Top"); +}); + +// ── added scope R3: Top and Latest in one job ────────────────────────────── + +test("R3: \"tabs\" is top, latest or both (the default); anything else is refused, and a reparse takes none", async () => { + const { xTrendingTabsAsked, X_TRENDING_TABS_PROBLEM } = await import("./readXTrending"); + assert.deepEqual(xTrendingTabsAsked(undefined), { ok: true, tabs: ["top", "latest"] }); + assert.deepEqual(xTrendingTabsAsked(["latest", "top", "TOP"]), { ok: true, tabs: ["top", "latest"] }); + assert.deepEqual(xTrendingTabsAsked(["latest"]), { ok: true, tabs: ["latest"] }); + for (const bad of [[], ["media"], "top", [1], {}]) assert.deepEqual(xTrendingTabsAsked(bad), { ok: false, error: X_TRENDING_TABS_PROBLEM }); + const paths = corpus("r3-plan"); + const plan = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); + assert.ok(plan.ok && plan.plan.mode === "read"); + assert.deepEqual(plan.plan.tabs, ["top", "latest"]); + const refused = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL, tabs: ["all"] }, withProfile); + assert.deepEqual(refused, { ok: false, error: X_TRENDING_TABS_PROBLEM }); +}); + +test("R3: one job reads Top, then Latest: one capture, each post's sightings per tab, read.json tab by tab", async () => { + const paths = corpus("r3-both"); + const { result, log } = await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + // Five posts: Top's four and the one only Latest shows. + assert.deepEqual(result.posts, { onPage: 5, added: 5 }); + assert.deepEqual(result.tabs, [ + { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, + { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, + ]); + assert.equal(result.sentence, `Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); + assert.ok(log.some((l) => /Top, then Latest/.test(l))); + const record = await readXTrendingReadRecord(root(paths), READ_1); + assert.deepEqual(record?.tabs, result.tabs); + assert.equal(record?.scrolls, 5); + assert.deepEqual(readdirSync(path.join(root(paths), "trending", "reads", READ_1)).sort(), ["page-latest.png", "page.png", "read.json", "responses.jsonl"]); + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.deepEqual(members["1900000000000001001"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Top", 1], ["Latest", 2]]); + assert.deepEqual(members["1900000000000001009"].seen.map((s: { tab: string; rank: number }) => [s.tab, s.rank]), [["Latest", 1]]); + const listing = await listXTrending(root(paths)); + assert.deepEqual(listing.topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); + // A reparse of the two-tab capture says the same of each tab and adds nothing. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.ok(planned.ok && planned.plan.mode === "reparse"); + const again = await reparseXTrendingRead({ plan: planned.plan as never }); + assert.deepEqual(again.posts, { onPage: 5, added: 0 }); + assert.deepEqual(again.tabs, result.tabs); + // A probe covers both tabs too, and writes no post. + const probe = await run(corpus("r3-probe"), fixtureTwoTabResponses(), { tabs: ["top", "latest"], probe: true }); + assert.equal(probe.result.outcome, "probe"); + assert.deepEqual(probe.result.tabs?.map((t) => [t.tab, t.posts, t.stop]), [["Top", 4, "idle"], ["Latest", 3, "idle"]]); +}); + +test("R3: a Latest tab that cannot be opened ends the read \"Top read; Latest not read: <why>\" — a read, not a failure, and nothing is retried", async () => { + const never = fixtureTwoTabResponses(); + never.tabs.Latest = {}; + const paths = corpus("r3-never"); + const { result, notes } = await run(paths, never, { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + assert.deepEqual(result.posts, { onPage: 4, added: 4 }); + assert.equal( + result.sentence, + `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab. ` + + `Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.`, + ); + assert.deepEqual(result.tabs?.[1], { tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); + // A clean request: the X alert it could clear is cleared, none is raised. + assert.deepEqual(notes.map((n) => n.kind), [undefined]); + // Top's read stands by itself: a later read may say what Top no longer shows. + const hidden = fixtureTwoTabResponses(); + hidden.tabs.Latest.hidden = true; + hidden.load = [hidden.load[0], { ...hidden.load[1], body: fixtureTimelineBody([FIXTURE_FIRST_PAGE_0]) }]; + hidden.scrolls = [[fixtureContinuation([], 5)], []]; + const second = await run(paths, hidden, { tabs: ["top", "latest"], topic: "Kettle Festival" }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(second.result.outcome, "read"); + assert.deepEqual([...(second.result.gone ?? [])].sort(), ["1900000000000001002", "1900000000000001004", "1900000000000001005"]); + assert.match(second.result.sentence, /Top read; Latest not read: the page shows no tab named "Latest" in its tab list\./); +}); + +test("R3: a post that leaves Latest between two reads is said gone from that tab while Top still shows it; gone from the page once Top drops it too", async () => { + const paths = corpus("r3-leaves"); + await run(paths, fixtureTwoTabResponses(), { tabs: ["top", "latest"], topic: "Kettle Festival" }); + // Second read: Latest no longer lists 1001 (Top does) nor 1009 (which only Latest showed). + const latestNow = [FIXTURE_LATEST_PAGE[2]]; + const second = await run(paths, fixtureTwoTabResponses(latestNow), { tabs: ["top", "latest"] }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + assert.deepEqual(second.result.gone, ["1900000000000001009"]); + assert.deepEqual(second.result.goneFromTab, [{ id: "1900000000000001001", tab: "Latest" }]); + assert.equal( + second.result.sentence, + `Read ${FIXTURE_TREND_URL}: 4 posts on the page, 0 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs. ` + + `1 post this page showed before is gone from the page at 12:00 UTC. 1 post is gone from the "Latest" tab and still shown by another.`, + ); + const listing = await listXTrending(root(paths)); + assert.deepEqual(listing.posts.find((p) => p.id === "1900000000000001001")?.goneTabs, [{ tab: "Latest", at: "2026-11-17T12:00:00.000Z", read: READ_2 }]); + assert.equal(listing.posts.find((p) => p.id === "1900000000000001001")?.gone, undefined); + // A read of Latest that was CAPPED says nothing of what Latest no longer shows. + const capped = fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[0]]); + capped.tabs.Latest.scrolls = [[fixtureLatestContinuation([{ id: "1900000000000001010", handle: "lid_watch", text: "One more." }])]]; + const third = await run(paths, capped, { tabs: ["top", "latest"], scrolls: 3 }, { readId: "tr-01JC0000000000000000000000", at: "2026-11-17T13:00:00.000Z" }); + assert.deepEqual(third.result.tabs?.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + assert.equal(third.result.goneFromTab, undefined); + void fixtureLatestFirst; +}); + +// Added scope R2: where X is about to be asked, only a job on X's queue stands. +test("R2a: a trending read outside the editor's job, or in a job on another queue, opens no browser", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const paths = corpus("r2-outside"); + const planned = await planReadXTrending(paths, { slug: "trending", url: FIXTURE_TREND_URL }, withProfile); + assert.ok(planned.ok && planned.plan.mode === "read"); + let opened = 0; + const ask = { paths, plan: planned.plan as never, deps: { openPage: async () => (opened++, assert.fail("a browser was opened")), held: async () => null } }; + const outside = await runXTrendingReadDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.sentence, /^A read of https:\/\/x\.com\/i\/trending\/\d+ asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops read-x-trending/); + const elsewhere = await asEditorJob(() => runXTrendingReadDirect(ask), { queueKey: "manual" }); + assert.match(elsewhere.sentence, /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused/); + assert.equal(opened, 0); + assert.equal(existsSync(path.join(root(paths), "trending", "reads")), false); +}); + +// ── review 2 (lane x-followups): S1, S2 at the read's end ────────────────── + +test("S1: a press that takes the page off the trending page ends \"Top read; Latest not read: the page changed\" — a read, no strike, Top ingested", async () => { + const away = fixtureTwoTabResponses(); + away.tabs.Latest.navigatesTo = "https://x.com/explore"; + const paths = corpus("s1-changed"); + const { result } = await run(paths, away, { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + assert.deepEqual(result.posts, { onPage: 4, added: 4 }); + assert.match(result.sentence, / Top read; Latest not read: the page changed\.$/); + assert.deepEqual(result.tabs?.[1], { tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: "the page changed" }); +}); + +test("S2: a deadline during Latest keeps Top's result — \"Top read; Latest stopped at the deadline\", pageEnd false for Latest, a read and no strike", async () => { + const stuck = fixtureTwoTabResponses(); + stuck.tabs.Latest.scrollHangs = true; + const paths = corpus("s2-deadline"); + const { result } = await run(paths, stuck, { tabs: ["top", "latest"], topic: "Kettle Festival" }, { timeouts: { call: 50 } }); + assert.equal(result.ok, true); + assert.equal(result.outcome, "read"); + assert.match(result.sentence, / Top read; Latest stopped at the deadline \(3 posts read\)\.$/); + assert.deepEqual( + result.tabs?.map((t) => [t.tab, t.stop, t.pageEnd]), + [["Top", "idle", true], ["Latest", "deadline", false]], + ); + // What Latest had is in the library. + assert.equal(result.posts.onPage, 5); + // An ending of "read" is what the watch counts no strike for (xTrendingWatch.ts noteXTrendingWatchRead). +}); + +// Review 3 S8: after the press took the page elsewhere, the answers the +// other page sent (its own timelines) are kept in the capture and never +// ingested as this topic's — on the read and on a reparse alike. +test("review 3 S8: after the page changed, an answer for any other timeline is kept in the capture and not ingested", async () => { + const away = fixtureTwoTabResponses(); + away.tabs.Latest.navigatesTo = "https://x.com/explore"; + const STRAY = "1900000000000003991"; + const strayUrl = `https://x.com/i/api/graphql/q/${FIXTURE_TIMELINE_OP}?variables=${encodeURIComponent(JSON.stringify({ timelineId: "fixture-timeline-elsewhere", count: 20 }))}`; + away.tabs.Latest.load = [{ url: strayUrl, status: 200, body: fixtureTimelineBody([{ id: STRAY, handle: "elsewhere", text: "A post of the page the press went to." }]) }]; + const paths = corpus("s8-elsewhere"); + const { result } = await run(paths, away, { tabs: ["top", "latest"], topic: "Kettle Festival" }); + assert.equal(result.outcome, "read"); + assert.match(result.sentence, / Top read; Latest not read: the page changed\.$/); + assert.deepEqual(result.posts, { onPage: 4, added: 4 }, "Top's four, not the other page's post"); + assert.ok(!(await readXTrendingPosts(root(paths))).some((p) => p.id === STRAY)); + // It is in the capture all the same. + const capture = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "responses.jsonl"), "utf8"); + assert.ok(capture.includes(STRAY)); + // A reparse of the same read reads the record's tabs and does the same. + const planned = await planReadXTrending(paths, { slug: "trending", reparse: READ_1 }); + assert.ok(planned.ok && planned.plan.mode === "reparse"); + const reparsed = await reparseXTrendingRead({ plan: planned.plan as never }); + assert.equal(reparsed.ok, true); + assert.equal(reparsed.posts.onPage, 4); + assert.ok(!(await readXTrendingPosts(root(paths))).some((p) => p.id === STRAY)); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -69,8 +69,10 @@ import { type XTrendingReadOperation, type XTrendingReadOutcome, type XTrendingReadRecord, + type XTrendingReadTab, } from "../lib/xTrending/store"; import { ulid } from "../jobs/ulid"; +import { xJobContextRefusal } from "../lib/xJobRule"; import { readXSessionStatus } from "../social/xSessionBroker"; import { xRequestPauseMs } from "../social/xGalleryDlFetcher"; import type { ChromiumLike } from "../social/playwrightRuntime"; @@ -78,8 +80,12 @@ import { parseTrendingCapture, readCaptureLines } from "../social/xTrendingParse import { openXTrendingPage, readXTrendingPage, + TRENDING_PAGE_CHANGED, + TRENDING_TAB_ASKS, type TrendingPageRead, type TrendingPageSession, + type TrendingTabAsk, + type TrendingTabRead, } from "../social/xTrendingRead"; import { isValidChannelSlug, readChannelConfig } from "./channels"; @@ -128,6 +134,9 @@ export type ReadXTrendingAsk = { posts?: unknown; probe?: boolean; headed?: boolean; + // The page's tabs to read: ["top"], ["latest"] or both (the default). Both + // are read in ONE job: Top, then the page's Latest tab is pressed. + tabs?: unknown; // 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 @@ -135,6 +144,18 @@ export type ReadXTrendingAsk = { watch?: boolean; }; +// The tabs a read is asked for: "top", "latest" or both; absent, both. In the +// page's order, each once. Anything else is refused with a sentence. +export const X_TRENDING_TABS_PROBLEM = `"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)`; +export function xTrendingTabsAsked(v: unknown): { ok: true; tabs: TrendingTabAsk[] } | { ok: false; error: string } { + if (v === undefined || v === null) return { ok: true, tabs: [...TRENDING_TAB_ASKS] }; + if (!Array.isArray(v) || v.length === 0 || !v.every((t) => typeof t === "string" && (TRENDING_TAB_ASKS as readonly string[]).includes(t.toLowerCase()))) { + return { ok: false, error: X_TRENDING_TABS_PROBLEM }; + } + const asked = new Set(v.map((t: string) => t.toLowerCase())); + return { ok: true, tabs: TRENDING_TAB_ASKS.filter((t) => asked.has(t)) }; +} + export type ReadXTrendingPlan = | { mode: "read"; @@ -145,6 +166,7 @@ export type ReadXTrendingPlan = topic?: string; probe: boolean; headed: boolean; + tabs: TrendingTabAsk[]; watch?: boolean; } | { mode: "reparse"; slug: string; channelRoot: string; record: XTrendingReadRecord; topic?: string }; @@ -209,8 +231,8 @@ export async function planReadXTrending( } const topic = ask.topic?.trim(); if (hasReparse) { - if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined) { - return fail(`"probe", "headed", "scrolls" and "posts" apply to a read of a page, not to "reparse" (which asks X nothing).`); + if (ask.probe || ask.headed || ask.scrolls !== undefined || ask.posts !== undefined || ask.tabs !== undefined) { + return fail(`"probe", "headed", "scrolls", "posts" and "tabs" apply to a read of a page, not to "reparse" (which asks X nothing).`); } if (!isXTrendingReadId(ask.reparse)) return fail(`"${String(ask.reparse)}" is not a trending read id (tr-…)`); let record = await readXTrendingReadRecord(channelRoot, ask.reparse); @@ -246,6 +268,8 @@ export async function planReadXTrending( if (!ref) return fail(NOT_A_TRENDING_URL); const limits = xTrendingLimits(config.xTrending, { scrolls: ask.scrolls, posts: ask.posts }); if (!limits.ok) return fail(limits.error); + const tabs = xTrendingTabsAsked(ask.tabs); + if (!tabs.ok) return fail(tabs.error); const hasProfile = deps.hasProfile ?? (async () => (await readXSessionStatus(paths)).hasProfile); if (!(await hasProfile())) return fail(NO_X_PROFILE_FOR_TRENDING); // X cooling down after a rate limit: refused before a job exists. @@ -262,6 +286,7 @@ export async function planReadXTrending( ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, + tabs: tabs.tabs, ...(ask.watch === true ? { watch: true } : {}), }, }; @@ -284,7 +309,11 @@ export type ReadXTrendingResult = { // Operation names and sizes — never a body. operations: XTrendingReadOperation[]; posts: { onPage: number; added: number }; - topic?: { id: string; title: string; created?: boolean }; + topic?: { id: string; title: string; created?: boolean; renamed?: { was: string } }; + // The read, tab by tab (store.ts XTrendingReadTab): the posts each listed, + // its scrolls, why it stopped, whether the capture shows its end; a tab + // asked for and not opened is "not-read" with `why`. + tabs?: XTrendingReadTab[]; // 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). @@ -294,6 +323,8 @@ export type ReadXTrendingResult = { // read that reached the page's end, and never meaning deleted. newIds?: string[]; gone?: string[]; + // Posts ONE TAB read to its end no longer shows, while another still does. + goneFromTab?: Array<{ id: string; tab: string }>; // What happened, as one sentence (the refusal, when `ok` is false). sentence: string; error?: string; @@ -318,13 +349,62 @@ type Ingested = { responses: number; onPage: number; added: number; - topic?: { id: string; title: string; created: boolean }; + topic?: { id: string; title: string; created: boolean; renamed?: { was: string } }; // 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[]; + // Posts a tab read to its end no longer shows while another tab still does. + goneFromTab?: Array<{ id: string; tab: string }>; + // Tab by tab (store.ts XTrendingReadRecord.tabs). + tabs?: XTrendingReadTab[]; }; +// The tab a capture's posts are the page's, when its timelines name exactly one. +export function readTabOf(timelines: ReadonlyArray<{ tab?: string }>): string | undefined { + const named = [...new Set(timelines.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; + return named.length === 1 ? named[0] : undefined; +} + +// `, shown by the page's "Top" tab` — what a read saw, in a sentence; "" when the +// capture does not say. +function tabText(tabs: Ingested["tabs"]): string { + // The tabs that listed posts (one asked for and not read listed none). + const named = (tabs ?? []).filter((t) => t.tab && t.stop !== "not-read" && (t.posts > 0 || t.stop !== undefined)); + if (named.length === 0) return ""; + return `, shown by the page's ${named.map((t) => `"${t.tab}"`).join(" and ")} tab${named.length === 1 ? "" : "s"}`; +} + +// "Top read; Latest not read: <why>." — a tab that was asked for and could +// not be opened. Not a failure: what the other tab showed stands. +// "Top read; Latest stopped at the deadline." — the read's deadline fell +// inside the second tab (review 2 S2): what that tab had is kept, and it +// says nothing of the page's end. +function notReadText(tabs: Ingested["tabs"]): string { + const missed = (tabs ?? []).filter((t) => t.stop === "not-read" || (t.asked === "latest" && t.stop === "deadline")); + if (missed.length === 0) return ""; + const read = (tabs ?? []).filter((t) => t.tab && !missed.includes(t) && t.stop !== "not-asked").map((t) => t.tab); + const name = (t: XTrendingReadTab) => t.tab ?? (t.asked === "latest" ? "Latest" : "Top"); + const what = (t: XTrendingReadTab) => + t.stop === "deadline" + ? `${name(t)} stopped at the deadline (${plural(t.posts, "post")} read)` + : `${name(t)} not read: ${t.why ?? "it could not be opened"}`; + return ` ${read.length ? `${read.join(" and ")} read; ` : ""}${missed.map(what).join("; ")}.`; +} + +// "2 posts are gone from the "Latest" tab and still shown by another." +function goneFromTabText(goneFromTab: Ingested["goneFromTab"]): string { + if (!goneFromTab?.length) return ""; + const by = new Map<string, number>(); + for (const g of goneFromTab) by.set(g.tab, (by.get(g.tab) ?? 0) + 1); + return [...by].map(([tab, count]) => ` ${plural(count, "post")} ${count === 1 ? "is" : "are"} gone from the "${tab}" tab and still shown by another.`).join(""); +} + +// A topic that took the page's title in this pass, said once. +function renamedText(topic: Ingested["topic"]): string { + return topic?.renamed ? ` The topic was "${topic.renamed.was}" until now: it took the page's title.` : ""; +} + // The saved capture → the library: its posts written, the read recorded. // `write: false` (a probe) parses and counts and writes nothing. async function ingestCapture(o: { @@ -335,14 +415,96 @@ 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; + // THE READ, TAB BY TAB (the page reader's): which tabs were scrolled and why + // each stopped. A tab is read to its end — the only read that may say a + // post is gone from it — when its scrolling went idle, no answer of the + // read failed (`clean`), and the capture itself shows that timeline's end. + // Absent for a reparse, which says nothing of what a page no longer shows. + pageTabs?: ReadonlyArray<TrendingTabRead>; + clean?: boolean; + // A reparse: the tabs the read's record already has (their scrolls and stops are kept). + recordedTabs?: ReadonlyArray<XTrendingReadTab>; }): 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 }; + // THE PAGE CHANGED (a press took it elsewhere): only the trend answer's own + // timelines are the page's (review 3 S8) — whatever the other page sent + // stays in the capture, unread. Said by the reader's tabs, or by the + // record's on a reparse. + const pageChanged = [...(o.pageTabs ?? []), ...(o.recordedTabs ?? [])].some((t) => t.why === TRENDING_PAGE_CHANGED); + const whole = parseTrendingCapture(lines, o.slug, pageChanged ? { pageTabsOnly: true } : {}); + // A TAB THE READ SAYS WAS NOT READ gives the library nothing (review 2 + // S1): answers for its timeline that came in before the read stopped — a + // press that took the page elsewhere — stay in the capture, unread. A post + // another timeline listed too is kept. + const notRead = (t: { timelineId?: string; tab?: string }) => + t.timelineId !== undefined && + ((o.pageTabs ?? []).some((r) => r.timelineId === t.timelineId && r.stop === "not-read") || + (o.recordedTabs ?? []).some((r) => r.tab !== undefined && r.tab === t.tab && r.stop === "not-read")); + const parsed = (() => { + const dropped = whole.timelines.filter(notRead); + if (dropped.length === 0) return whole; + const keptIds = new Set(whole.timelines.filter((t) => !notRead(t)).flatMap((t) => t.postIds)); + const droppedIds = new Set(dropped.flatMap((t) => t.postIds).filter((id) => !keptIds.has(id))); + return { + ...whole, + timelines: whole.timelines.filter((t) => !notRead(t)), + posts: whole.posts.filter((p) => !droppedIds.has(p.id)), + media: Object.fromEntries(Object.entries(whole.media).filter(([id]) => !droppedIds.has(id))), + }; + })(); + const named = parsed.timelines.filter((t) => t.timelineId); + const untagged = parsed.timelines.find((t) => !t.timelineId); + const scrolled = (timelineId: string | undefined) => o.pageTabs?.find((t) => t.timelineId !== undefined && t.timelineId === timelineId); + // What read.json says, tab by tab: the reader's tabs in the order it read + // them (with what the capture holds of each), then any timeline the capture + // lists that the reader did not name. + const tabs: XTrendingReadTab[] = []; + // The timeline each entry is of (never written: read.json holds labels). + const timelineOf = new Map<XTrendingReadTab, string>(); + const said = new Set<string>(); + for (const t of o.pageTabs ?? []) { + const listed = t.timelineId ? named.find((x) => x.timelineId === t.timelineId) : named.length === 0 ? untagged : undefined; + if (t.timelineId) said.add(t.timelineId); + const entry: XTrendingReadTab = { + ...(t.tab ?? listed?.tab ? { tab: t.tab ?? listed?.tab } : {}), + asked: t.asked, + posts: listed?.postIds.length ?? 0, + scrolls: t.scrolls, + stop: t.stop, + // A tab cut by the read's deadline never shows the page's end. + pageEnd: Boolean(listed?.pageEnd) && t.stop !== "deadline", + ...(t.why ? { why: t.why } : {}), + }; + if (t.timelineId) timelineOf.set(entry, t.timelineId); + tabs.push(entry); + } + const unnamedByReader = (o.pageTabs ?? []).some((t) => !t.timelineId) && named.length === 0; + for (const t of parsed.timelines) { + if (t.timelineId ? said.has(t.timelineId) : unnamedByReader) continue; + const before = o.recordedTabs?.find((r) => r.tab !== undefined && r.tab === t.tab); + const entry: XTrendingReadTab = { + ...(t.tab ? { tab: t.tab } : {}), + ...(before?.asked ? { asked: before.asked } : {}), + posts: t.postIds.length, + ...(before?.scrolls !== undefined ? { scrolls: before.scrolls } : {}), + ...(before?.stop ? { stop: before.stop } : {}), + pageEnd: t.pageEnd, + ...(before?.why ? { why: before.why } : {}), + }; + if (t.timelineId) timelineOf.set(entry, t.timelineId); + tabs.push(entry); + } + // A tab the record says was not read stays said (a reparse cannot know it otherwise). + for (const r of o.recordedTabs ?? []) { + if (r.stop === "not-read" && !tabs.some((t) => t.tab === r.tab && t.asked === r.asked)) tabs.push({ ...r, posts: 0, pageEnd: false }); + } + const base = { + operations: parsed.operations, + responses: parsed.responses, + onPage: parsed.posts.length, + ...(tabs.length ? { tabs } : {}), + }; 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)); @@ -352,11 +514,26 @@ async function ingestCapture(o: { 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); + // THE TABS' READS: each named timeline's posts in its own order, and whether + // it was read to its end. Posts an answer listed without naming a timeline + // (review 1 S3) go with the ONE named tab when there is exactly one (they + // never make it complete or incomplete), else stand by themselves. + const tabReads = named.map((t) => { + const tab = scrolled(t.timelineId); + const complete = Boolean(o.clean && t.pageEnd && tab?.stop === "idle"); + return { ...(t.tab ? { tab: t.tab } : {}), timelineId: t.timelineId!, postIds: [...t.postIds], ...(complete ? { complete: true } : {}) }; + }); + if (untagged) { + if (tabReads.length === 1) tabReads[0].postIds.push(...untagged.postIds.filter((id) => !tabReads[0].postIds.includes(id))); + else if (tabReads.length === 0) { + // No request named a timeline (a page from before tabs were read): the opening tab's, whatever it is called. + const only = (o.pageTabs ?? []).length <= 1 ? o.pageTabs?.[0] : undefined; + const complete = Boolean(o.clean && untagged.pageEnd && only?.stop === "idle"); + tabReads.push({ timelineId: "", postIds: [...untagged.postIds], ...(complete ? { complete: true } : {}) }); + } else tabReads.push({ timelineId: "", postIds: [...untagged.postIds] }); + } 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, @@ -364,8 +541,22 @@ async function ingestCapture(o: { postIds: parsed.posts.map((p) => p.id), added: written.written, media: parsed.media, + ...(parsed.page ? { page: parsed.page } : {}), + tabReads: tabReads.map(({ timelineId, ...t }) => ({ ...t, ...(timelineId ? { timelineId } : {}) })), }); - return { ...base, added: written.written, topic: recorded.topic, newIds, gone: recorded.gone }; + // The labels the source knew for timelines the capture itself did not name. + for (const t of tabs) { + const label = recorded.tabLabels?.[timelineOf.get(t) ?? ""]; + if (!t.tab && label) t.tab = label; + } + return { + ...base, + added: written.written, + topic: recorded.topic, + newIds, + gone: recorded.gone, + ...(recorded.goneFromTab?.length ? { goneFromTab: recorded.goneFromTab } : {}), + }; } export type ReadXTrendingDeps = { @@ -393,6 +584,8 @@ export type ReadXTrendingDeps = { // through what a watch must not. A plan marked `watch` with no check here // does not run. watchRefusal?: () => Promise<{ reason: string; sentence: string } | null>; + // For tests: the page reader's deadlines (xTrendingRead.ts readXTrendingPage). + timeouts?: { load?: number; call?: number; close?: number; read?: number; tab?: number }; }; export async function runXTrendingRead(o: { @@ -419,6 +612,10 @@ export async function runXTrendingRead(o: { const none = { responses: 0, operations: [], posts: { onPage: 0, added: 0 } }; // A Connect or a Refresh holds the profile: asked again here, at the start. + // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts): + // asked here, where the browser is about to be opened. + const outside = xJobContextRefusal(`A read of ${plan.ref.url}`, `pnpm ops read-x-trending --json '{"slug":"${plan.slug}","url":"${plan.ref.url}"}' --wait`); + if (outside) return { ...base, ...none, ok: false, outcome: "error", sentence: outside, error: outside }; const busy = deps.profileBusy?.() ?? null; if (busy) return { ...base, ...none, ok: false, outcome: "error", sentence: busy, error: busy }; if (plan.watch) { @@ -466,7 +663,8 @@ export async function runXTrendingRead(o: { await writeXTrendingReadRecord(plan.channelRoot, started); log( `Reading ${plan.ref.url} for ${plan.slug} (${plan.headed ? "in a window" : "headless"}; ` + - `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")})` + + `at most ${plural(plan.limits.scrolls, "scroll")}, ${plural(plan.limits.posts, "post")} per tab; ` + + `${plan.tabs.length === 2 ? "Top, then Latest" : plan.tabs[0] === "latest" ? "Latest only" : "Top only"})` + (plan.probe ? " — a probe: the capture is saved, no post is written." : ".") + (plan.watch ? " A watch's tick." : ""), ); @@ -483,11 +681,13 @@ export async function runXTrendingRead(o: { ...(deps.chromium ? { chromium: deps.chromium } : {}), })), limits: plan.limits, + tabs: plan.tabs, pauseMs: deps.pauseMs ?? (() => xRequestPauseMs()), ...(deps.pause ? { pause: deps.pause } : {}), signal, onLog: log, now, + ...(deps.timeouts ? { timeouts: deps.timeouts } : {}), }); // What was read is kept whatever stopped it — except behind a login wall, @@ -506,13 +706,12 @@ 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)), + // A tab's "idle" is two scrolls that brought no new post: its end, OR a + // next page that did not load. So also: no answer that failed, none + // that was not kept (`clean`); and the capture itself must show that + // tab's end (ingestCapture). + pageTabs: page.tabs, + clean: 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]; @@ -597,10 +796,14 @@ 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})` + + tabText(ingested.tabs) + (page.stop === "cancelled" ? "; the read was stopped early." : ".") + + notReadText(ingested.tabs) + + renamedText(ingested.topic) + (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.` - : ""); + : "") + + goneFromTabText(ingested.goneFromTab); // 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); @@ -630,6 +833,7 @@ export async function runXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), shot: page.shot, ...(page.stoppedBy ? { stoppedBy: page.stoppedBy } : {}), sentence, @@ -647,8 +851,10 @@ export async function runXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), ...(ingested.newIds?.length ? { newIds: ingested.newIds } : {}), ...(ingested.gone?.length ? { gone: ingested.gone } : {}), + ...(ingested.goneFromTab?.length ? { goneFromTab: ingested.goneFromTab } : {}), sentence, ...(ok ? {} : { error: sentence }), }; @@ -701,6 +907,7 @@ export async function reparseXTrendingRead(o: { ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !walled, + ...(record.tabs ? { recordedTabs: record.tabs } : {}), }); const kept = captureAt(record.id); let outcome: XTrendingReadOutcome; @@ -717,7 +924,8 @@ export async function reparseXTrendingRead(o: { outcome = "read"; sentence = `Parsed ${record.id} again (${record.url}): ${plural(ingested.onPage, "post")} in the capture, ${ingested.added} new, ` + - `in topic "${ingested.topic?.title}" (${ingested.topic?.id}). X was asked nothing.`; + `in topic "${ingested.topic?.title}" (${ingested.topic?.id})${tabText(ingested.tabs)}. X was asked nothing.` + + renamedText(ingested.topic); } const ok = outcome !== "login-wall"; if (ok) { @@ -727,6 +935,7 @@ export async function reparseXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: record.posts.added + ingested.added }, ...(ingested.topic ? { topic: { id: ingested.topic.id, title: ingested.topic.title } } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), reparsedAt: new Date((o.now ?? Date.now)()).toISOString(), }); } @@ -743,6 +952,7 @@ export async function reparseXTrendingRead(o: { operations: ingested.operations, posts: { onPage: ingested.onPage, added: ingested.added }, ...(ingested.topic ? { topic: ingested.topic } : {}), + ...(ingested.tabs ? { tabs: ingested.tabs } : {}), sentence, ...(ok ? {} : { error: sentence }), }; diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -665,6 +665,8 @@ export function defaultXRunDeps(paths: Paths, jobId: string): XRunDeps { paths, channelSlug: slug, job: { id: jobId }, + // Each channel's fetch is one X job against X's job cap. + countStart: true, }); return res.ok ? { ok: true, notes: res.notes } : { ok: false, error: res.error }; }, diff --git a/common/controller/xTrendingCooldown.test.ts b/common/controller/xTrendingCooldown.test.ts @@ -47,7 +47,10 @@ test("no cooldown: a read may start; after a 429: refused until the minute it na test("N4: a clean read leaves the download lane's X backoff exactly as it was", async () => { const { mkdirSync, writeFileSync: write } = await import("node:fs"); const { recordDownloadBackoff } = await import("../jobs/downloadBackoff"); - const { planReadXTrending, runXTrendingRead } = await import("./readXTrending"); + const { planReadXTrending, runXTrendingRead: runXTrendingReadDirect } = await import("./readXTrending"); + // X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. + const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); + const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const { fakeTrendingPage } = await import("../social/fakeXProfileBrowser"); const { FIXTURE_TREND_URL, fixtureTrendingResponses } = await import("../social/__fixtures__/xTrendingCapture"); const paths = getPaths(); diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts @@ -386,6 +386,7 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting maxAgeMinutes: 60, ageChecked: true, alert: null, + cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: false }, // What the guard says of a person's job: allowed, in every case below. allowed: true, reason: null, @@ -396,6 +397,24 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting const old = new Date(now - 3 * 60 * MIN).toISOString(); // The control: a fresh jar ticks. assert.equal(await ask({}), null); + // Added scope R2: X's job cap is reached — a pause like a cooldown's (the tick is skipped, no strike, it goes on by itself), not the jar's. + const cap = "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …"; + assert.deepEqual(await ask({ allowed: false, reason: cap, cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never), { reason: "cooldown", sentence: cap }); + // Review 2, ruling R-a: a job that does not count (a library's media-only capture) is not held by the cap — + // the report it is asked with says so (`counts: false` reaches xSessionReport), and the cap clause stands aside. + let asked: unknown; + const notCounted = await watchRefusal({} as Paths, "lib", now, { + report: (async (o: unknown) => ((asked = o), report({ cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never)())) as never, + settingsReadable: () => true, + held: async () => null, + counts: false, + }); + assert.equal(notCounted, null); + assert.equal((asked as { counts?: boolean }).counts, false); + assert.deepEqual(await ask({ allowed: false, reason: "X's job count cannot be read (f): no X job starts while it is unreadable", cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: true, unreadable: true } } as never), { + reason: "cooldown", + sentence: "X's job count cannot be read (f): no X job starts while it is unreadable", + }); // 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"); diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -68,7 +68,8 @@ 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 }; +// `tabs`: the one tab the watch reads, when it does not read both. +export type WatchTick = { slug: string; topic: string; url: string; trendId: string; tabs?: Array<"top" | "latest"> }; export type WatchScanDeps = { paths: Paths; @@ -112,6 +113,10 @@ export type WatchRefusalDeps = { // Whether settings.json can be read at all. settingsReadable?: () => boolean; held?: (paths: Paths, now: number) => Promise<string | null>; + // False: the job asked about does not count against X's job cap (a + // library's media-only capture, lib/xJobRule.ts xJobCounts — review 2, + // ruling R-a), so the cap does not hold it. Every other rule here does. + counts?: boolean; }; function settingsCanBeRead(): boolean { @@ -137,7 +142,7 @@ function settingsCanBeRead(): boolean { // 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 }); + const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now, ...(deps.counts === false ? { counts: false } : {}) }); if (!report.hasProfile) { return { reason: "no-profile", @@ -169,6 +174,12 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps 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.`, }; } + // X'S JOB CAP IS REACHED (lib/xJobRule.ts): like a cooldown — the tick is + // skipped, the watch waits, and it goes on by itself once the cap has room. + // Not the jar's fault and not a failed read. + if (deps.counts !== false && !report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) { + return { reason: "cooldown", sentence: report.reason ?? "X's job cap is reached." }; + } // 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); @@ -324,7 +335,7 @@ export async function scanXTrendingWatches(deps: WatchScanDeps): Promise<WatchSc 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 tick: WatchTick = { slug: pick.slug, topic: pick.topic.id, url: page.url, trendId: page.trendId, ...(pick.watch.tabs ? { tabs: pick.watch.tabs } : {}) }; 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) => { diff --git a/common/controller/xTrendingWatchJob.test.ts b/common/controller/xTrendingWatchJob.test.ts @@ -21,7 +21,10 @@ 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 { planReadXTrending, runXTrendingRead: runXTrendingReadDirect } = await import("./readXTrending"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const runXTrendingRead = insideEditorJob(runXTrendingReadDirect); const { FIXTURE_TREND_ID, FIXTURE_TREND_URL } = await import("../social/__fixtures__/xTrendingCapture"); const paths = getPaths(); diff --git a/common/jobs/instagramSchedule.test.ts b/common/jobs/instagramSchedule.test.ts @@ -72,3 +72,25 @@ test("an Instagram channel told only by its URL (no platform in its config) is h // Its cadence is Instagram's too. assert.equal(view[0]!.intervalMinutes, 720); }); + +// Added scope R2 (lane x-followups): X's job cap is reached — the scheduler skips X's channels, like a cooldown. +test("R2b: while X's job cap is reached every X posts channel is skipped with the sentence and takes no slot; Instagram is not X's business", async () => { + const { xSyncHold } = await import("./syncScheduler"); + const CAP = "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …"; + const r = selectDueChannels({ ...base, xCapHeld: CAP }); + assert.ok(!r.due.includes("x-chan")); + assert.ok(r.due.includes("ig-ready")); + assert.deepEqual(r.skipped.filter((s) => s.slug === "x-chan"), [{ slug: "x-chan", reason: CAP }]); + const view = buildScheduleView({ ...base, xCapHeld: CAP }); + const x = view.find((v) => v.slug === "x-chan")!; + assert.deepEqual([x.autoSyncEligible, x.heldReason], [false, CAP]); + assert.equal(view.find((v) => v.slug === "ig-ready")!.autoSyncEligible, true); + // With room under the cap nothing is held. + assert.ok(selectDueChannels(base).due.includes("x-chan")); + // The predicate: an X posts channel by its platform or its URL; never a video channel. + assert.equal(xSyncHold({ sourceKind: "social", platform: "twitter" }, CAP), CAP); + assert.equal(xSyncHold({ sourceKind: "social", url: "https://x.com/example" }, CAP), CAP); + assert.equal(xSyncHold({ sourceKind: "social", platform: "bluesky" }, CAP), null); + assert.equal(xSyncHold({ sourceKind: "video", url: "https://x.com/example" } as never, CAP), null); + assert.equal(xSyncHold({ sourceKind: "social", platform: "twitter" }, null), null); +}); diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -3,6 +3,7 @@ import { readFile, writeFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { JobRecord, JobStatus } from "./registry"; import { parseJobSpec, type JobSpec } from "./jobSpec"; +import { X_QUEUE_KEY } from "../lib/xJobRule"; // A serializable sidecar (`<id>.meta.json`) written alongside each job's // `<id>.log`. The in-memory registry keeps only the 100 most-recent finished @@ -44,6 +45,13 @@ export type JobMeta = { // On an interrupted job's meta: the job that resumed it. Written only by the // resume pass, so it is never resumed twice. resumedAs?: string; + // The starts X's job cap counted this job for (JobRecord.xStarts): written + // on every meta of X's queue, [] for a job that counted none, so the count + // can be rebuilt from the records (jobs/xJobCap.ts). Absent on metas from + // before it. + xStarts?: number[]; + // The job ended deferred by X's job cap (JobRecord.deferred). + deferred?: { until: number; sentence: string }; }; export function metaPath(paths: Paths, id: string): string { @@ -74,6 +82,8 @@ export async function writeJobMeta( ...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), + ...(record.queueKey === X_QUEUE_KEY ? { xStarts: [...(record.xStarts ?? [])] } : {}), + ...(record.deferred ? { deferred: { ...record.deferred } } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); } catch { @@ -105,6 +115,9 @@ export async function readJobMeta( if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo; if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; + if (m.xStarts !== undefined && !(Array.isArray(m.xStarts) && m.xStarts.every((t) => typeof t === "number" && Number.isFinite(t)))) delete meta.xStarts; + const d = m.deferred as { until?: unknown; sentence?: unknown } | undefined; + if (d !== undefined && !(d && typeof d === "object" && typeof d.until === "number" && typeof d.sentence === "string")) delete meta.deferred; if ( m.resumeCount !== undefined && !(typeof m.resumeCount === "number" && Number.isInteger(m.resumeCount) && m.resumeCount > 0) diff --git a/common/jobs/listJobs.test.ts b/common/jobs/listJobs.test.ts @@ -195,3 +195,48 @@ test("readLogTail returns the last N lines, read from the end, never a half line await rm(dir, { recursive: true, force: true }); } }); + +// Review 3 M3: X's job count is rebuilt from the job records when its file is +// gone (jobs/xJobCap.ts), so retention never deletes the record of an X job +// that may still count — by count, by age, or "Clear logs → all". +test("review 3 M3: pruning keeps every X-queue record that may still count, and says since when it has", async () => { + await withJobs(async (paths, seed) => { + const DAY = 24 * 60 * 60 * 1000; + const now = BASE + 40 * DAY; + const xRecord = async (t: number, extra: Record<string, unknown>) => { + const id = ulid(t); + await writeFile(path.join(paths.jobsDir, `${id}.log`), "x\n"); + await writeFile(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, kind: "fetch-posts", queueKey: "platform:twitter", status: "done", queuedAt: t, ...extra })); + return id; + }; + // Counted an hour ago; queued two days ago and counted an hour ago (it waited); started an hour ago (a record from before xStarts). + const young = await xRecord(now - 60 * 60 * 1000, { startedAt: now - 60 * 60 * 1000, xStarts: [now - 60 * 60 * 1000] }); + const waited = await xRecord(now - 2 * DAY, { startedAt: now - 60 * 60 * 1000, xStarts: [now - 60 * 60 * 1000] }); + const legacy = await xRecord(now - 2 * 60 * 60 * 1000, { startedAt: now - 2 * 60 * 60 * 1000 }); + // Counted 25 hours ago: it cannot count any more, so it goes. + const old = await xRecord(now - 25 * 60 * 60 * 1000, { startedAt: now - 25 * 60 * 60 * 1000, xStarts: [now - 25 * 60 * 60 * 1000] }); + // A young record that cannot be read: it may be an X job's. + const tornId = ulid(now - 60_000); + await writeFile(path.join(paths.jobsDir, `${tornId}.log`), "x\n"); + await writeFile(path.join(paths.jobsDir, `${tornId}.meta.json`), "{torn"); + const other = await seed(9, now - 60_000); + const { deleted } = await pruneJobLogs(paths, { all: true, now }); + const left = await readdir(paths.jobsDir); + for (const id of [young, waited, legacy, tornId]) { + assert.ok(left.includes(`${id}.log`) && left.includes(`${id}.meta.json`), `kept ${id}`); + } + for (const id of [old, other]) assert.ok(!left.includes(`${id}.meta.json`), `deleted ${id}`); + assert.equal(deleted, 2); + // By count and by age the same. + assert.equal((await pruneJobLogs(paths, { keepLast: 0, now })).deleted, 0); + assert.equal((await pruneJobLogs(paths, { olderThanMs: 1, now })).deleted, 0); + // The pruner says since when it has kept them (jobs/xJobCap.ts reads it). + const kept = JSON.parse(await (await import("node:fs/promises")).readFile(path.join(paths.jobsDir, "x-records-kept.json"), "utf8")); + assert.equal(kept.since, now); + // A day later the same records can no longer count: they go. + assert.equal((await pruneJobLogs(paths, { all: true, now: now + DAY })).deleted, 4); + // The first "since" is kept. + const again = JSON.parse(await (await import("node:fs/promises")).readFile(path.join(paths.jobsDir, "x-records-kept.json"), "utf8")); + assert.equal(again.since, now); + }); +}); diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts @@ -9,6 +9,7 @@ const ENTRY_READ_CONCURRENCY = 32; import { metaPath, readJobMeta } from "./jobMeta"; import { jobSpecDetail } from "./jobDetail"; import { jobIdTime } from "./ulid"; +import { noteXRecordsKept, xRecordMayCount } from "./xJobCap"; export type JobListEntry = { id: string; @@ -37,6 +38,9 @@ export type JobListEntry = { cancelReason?: string; // The job this one handed its work on to (JobRecord.handedOffTo). handedOffTo?: string; + // The job ended `done` DEFERRED by X's job cap (JobRecord.deferred): it did + // not run; when the next X job may start, and the sentence. + deferred?: { until: number; sentence: string }; }; export type JobsPage = { @@ -117,6 +121,7 @@ async function buildEntry( replayable: Boolean(live_.spec), detail: jobSpecDetail(live_.kind, live_.spec), ...(live_.handedOffTo ? { handedOffTo: live_.handedOffTo } : {}), + ...(live_.deferred ? { deferred: { ...live_.deferred } } : {}), logPath, logSize, }; @@ -149,6 +154,7 @@ async function buildEntry( ? { cancelReason: meta.cancelReason } : {}), ...(meta.handedOffTo ? { handedOffTo: meta.handedOffTo } : {}), + ...(meta.status === "done" && meta.deferred ? { deferred: meta.deferred } : {}), logPath, logSize, }; @@ -315,6 +321,7 @@ export async function pruneJobLogs( const cutoff = opts.olderThanMs != null ? now - opts.olderThanMs : null; let deleted = 0; + let keepingNoted = false; for (let i = 0; i < items.length; i++) { const { id, t } = items[i]; if (protectedIds.has(id)) continue; @@ -325,6 +332,26 @@ export async function pruneJobLogs( // keepLast so we never delete something whose age we can't establish. if (!doDelete && cutoff != null && t > 0 && t < cutoff) doDelete = true; if (!doDelete) continue; + // NEVER THE RECORD OF AN X JOB THAT MAY STILL COUNT (review 3 M3): X's + // job count is rebuilt from these records when its file is gone + // (jobs/xJobCap.ts). Kept until it cannot count — a day after its last + // start — by count, by age and by "Clear logs" alike. + if (!keepingNoted) { + await noteXRecordsKept(paths, now).catch(() => {}); + keepingNoted = true; + } + const meta = await readFile(metaPath(paths, id), "utf8").then( + (text) => { + try { + const v = JSON.parse(text) as unknown; + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; + } catch { + return null; + } + }, + (err: NodeJS.ErrnoException) => (err?.code === "ENOENT" ? ({} as Record<string, unknown>) : null), + ); + if (xRecordMayCount(id, meta, now)) continue; await rm(path.join(paths.jobsDir, `${id}.log`), { force: true }); await rm(metaPath(paths, id), { force: true }); diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -47,15 +47,39 @@ import { } from "../social/xSessionBroker"; import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource"; import { jobKindLabel, kindIsNetwork } from "./jobKinds"; -import { queueGapPlatform } from "./queueGap"; +import { xJobAsksX, xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule"; +import { isXTrendingChannel } from "../lib/xTrending/config"; +import { recordXJobStart, xJobCapStatus } from "./xJobCap"; +import { writeJobMeta } from "./jobMeta"; +import type { JobSpec } from "./jobSpec"; +import { getRegistry } from "./registry"; +import { queueGapClock, queueGapPlatform } from "./queueGap"; export type NetworkJobOpts = { kind: string; queueKey: string; paths: Paths; channelSlug?: string; + // THE LAST GUARD BEFORE THE JOB'S WORK (jobs/streamCommand.ts; an X run's + // guard before each channel): an X job that passes it is COUNTED against + // X's job cap (lib/xJobRule.ts), checked and recorded in one step. The + // guards before it — at enqueue, and at the start before the queue's gap — + // only look. + countStart?: boolean; + // The job's replay descriptor — what its function runs with. X's job cap + // reads its PLAN from it (lib/xJobRule.ts xJobCounts): never a flag. + spec?: JobSpec; + // What a job with NO replay descriptor will ask (import-media's page + // address, review 4 B): read by the guards in place of `spec.params`, and + // never recorded (a spec would offer a Retry the kind does not have). + askParams?: Readonly<Record<string, unknown>>; }; +// The params the guards judge a job by: its spec's, else what it will ask. +function planParams(opts: Pick<NetworkJobOpts, "spec" | "askParams">): Record<string, unknown> | undefined { + return (opts.spec?.params ?? opts.askParams) as Record<string, unknown> | undefined; +} + // ── 1. the empty queue ───────────────────────────────────────────────────── export function emptyQueueRefusal(kind: string, queueKey: string): string | null { @@ -89,6 +113,45 @@ export async function networkJobPlatform(opts: NetworkJobOpts): Promise<string | } } +async function channelPlatformOf(opts: NetworkJobOpts): Promise<string | null> { + if (!opts.channelSlug) return null; + try { + return await channelPlatform(opts.paths, opts.channelSlug); + } catch { + return null; + } +} + +// Whether a job asks X: its queue is X's, OR it is an X channel's job whose +// work asks X (lane x-followups, R2: a job moved to another platform's queue +// used to be taken for that platform's and met none of X's rules), OR it +// imports an x.com URL. An X channel's job that asks no platform at all — +// its transcription, windows cut from disk, a local file's import — is not +// X's (review 2 S5). One predicate: lib/xJobRule.ts xJobAsksX. +// +// A WINDOW IS X'S BY ITS URL (review 3 M2), on any channel; a window that +// names no URL is fetched from its channel's page, so each such item's +// channel is read here (a batch may span channels). +export async function jobAsksX(opts: NetworkJobOpts): Promise<boolean> { + const params = planParams(opts); + const itemChannelPlatforms: Record<string, string | null> = {}; + if (opts.kind === "fetch-windows" && Array.isArray(params?.items)) { + for (const raw of params.items as unknown[]) { + const it = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {}; + const named = typeof it.webpageUrl === "string" && it.webpageUrl.trim() !== ""; + if (named || typeof it.slug !== "string" || Object.hasOwn(itemChannelPlatforms, it.slug)) continue; + itemChannelPlatforms[it.slug] = await channelPlatform(opts.paths, it.slug).catch(() => null); + } + } + return xJobAsksX({ + kind: opts.kind, + queueKey: opts.queueKey, + channelPlatform: await channelPlatformOf(opts), + ...(params ? { params } : {}), + ...(Object.keys(itemChannelPlatforms).length ? { itemChannelPlatforms } : {}), + }); +} + // ── 2 + 3. X ─────────────────────────────────────────────────────────────── // "16 days", "3 h", "45 min". @@ -179,9 +242,11 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting return resolveCookiePolicy(settings, config).cookies; } +// `capped`: the refusal is the job cap's (no cookie banner is raised for it), +// with `nextAt`, when the next X job may start. export type XGuardResult = | { ok: true; note?: string } - | { ok: false; message: string; alert: boolean }; + | { ok: false; message: string; alert: boolean; capped?: true; nextAt?: number }; // WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and // its verdict in one record, for `pnpm ops get x-session` (an agent asks it @@ -207,6 +272,11 @@ export type XSessionReport = { ageChecked: boolean; // The X cookie alert, when it is up (a challenge or a login wall). alert: { raisedAt: string; line: string } | null; + // X'S JOB CAP (lib/xJobRule.ts): the X jobs started ON THIS MACHINE in + // the last 60 minutes and 24 hours — one count, whatever the login source, + // cookie spec or channel (review 2 M1) — the caps (constants of the code), + // and, when the cap is reached, when the next may start. + cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true }; // Would an X job start now? `reason` is the refusal it would get. allowed: boolean; reason: string | null; @@ -217,6 +287,10 @@ export async function xSessionReport(opts: { paths: Paths; channelSlug?: string; now?: number; + // False: the job asked about does not count against X's job cap (ruling + // R-a: xJobCounts), so the cap does not refuse it. The count is reported + // all the same. + counts?: boolean; }): Promise<XSessionReport> { const now = opts.now ?? Date.now(); const status = await readXSessionStatus(opts.paths); @@ -230,7 +304,23 @@ export async function xSessionReport(opts: { const ageMinutes = status.cookiesUpdatedAt ? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000)) : null; + // The count's clock is the queue gap's (jobs/queueGap.ts): the two rules + // that space X jobs read one clock. + const capStatus = await xJobCapStatus(opts.paths, opts.now ?? queueGapClock().now()); + const cap = { + lastHour: capStatus.lastHour, + perHour: capStatus.perHour, + lastDay: capStatus.lastDay, + perDay: capStatus.perDay, + reached: !capStatus.ok, + ...(capStatus.nextAt !== undefined ? { nextAt: new Date(capStatus.nextAt).toISOString() } : {}), + ...(capStatus.unreadable ? { unreadable: true as const } : {}), + }; + // The cap refuses whatever else would let the job through. + const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T => + r.allowed && !capStatus.ok && opts.counts !== false ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r; const base = { + cap, source: resolved.source, sourceChosen: resolved.chosen, ...(resolved.browserSpec ? { browserSpec: resolved.browserSpec } : {}), @@ -261,36 +351,106 @@ export async function xSessionReport(opts: { }; } // Settings unreadable: the guard has nothing to apply and lets the job run. - if (!settings) return { ...base, alert: null, allowed: true, reason: null }; + if (!settings) return capped({ ...base, alert: null, allowed: true, reason: null }); const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok - ? { ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) } + ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) : { ...base, alert: null, allowed: false, reason: verdict.message }; } +// Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count), +// or null: for the scheduler, which then skips X's channels rather than +// queue syncs that would each be refused. +export async function xCapHeldReason(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<string | null> { + const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); + return status.ok ? null : (status.sentence ?? "X's job cap is reached."); +} + +// HOW MANY X JOBS MAY START NOW under X's job cap (0 when it is reached or +// its count cannot be read): for the scheduler, which queues no more X syncs +// than that (review 3 N9). A look: nothing is counted. +export async function xCapRoom(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<number> { + const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); + if (!status.ok) return 0; + return Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); +} + export async function xJobGuard(opts: { paths: Paths; channelSlug?: string; now?: number; + counts?: boolean; }): Promise<XGuardResult> { const r = await xSessionReport(opts); - if (r.allowed) return r.note ? { ok: true, note: r.note } : { ok: true }; - return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null }; + if (r.allowed) return { ok: true, ...(r.note ? { note: r.note } : {}) }; + const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason); + const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : undefined; + return { + ok: false, + message: r.reason ?? "X job refused.", + alert: r.alert !== null, + ...(capped ? { capped: true as const } : {}), + ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}), + }; +} + +// THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its +// spec's params, and whether its channel is a trending library (read here, +// never taken from the caller). +async function xJobPlanOf(opts: NetworkJobOpts): Promise<XJobPlan> { + const params = planParams(opts); + let channel: XJobPlan["channel"]; + if (opts.channelSlug) { + const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null); + const config = read?.ok ? channelConfigSchema.parse(read.value) : null; + if (config) channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) }; + } + return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) }; } // ── the one entry point ──────────────────────────────────────────────────── +// `deferUntil`: the refusal is X's job cap, reached — at a job's start the +// job ends DEFERRED (not failed; review 2, ruling R-b), and this is when the +// next X job may start. export type NetworkGuardResult = | { ok: true; notes: string[] } - | { ok: false; error: string }; + | { ok: false; error: string; deferUntil?: number }; // One platform's guard: asked with the job's options, at enqueue and at start. type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promise<NetworkGuardResult>; // X's (rules 2 and 3 above). async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> { - const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug }); + // X's queue only, whatever the job and whoever named the queue. + const queue = xQueueRefusal(`${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`, opts.queueKey); + if (queue) return { ok: false, error: queue }; + // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that + // does not count is not refused by the cap either; everything else of X's + // guard holds for it. + const counts = xJobCounts(await xJobPlanOf(opts)); + const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts }); if (x.ok) { + // THE START, COUNTED: checked and recorded in one step. An X run's own + // start asks X nothing: each of its channels is a start (it is guarded, + // with its slug, before each one). + if (counts && opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) { + const counted = await recordXJobStart(opts.paths, queueGapClock().now()); + if (!counted.ok) { + return { + ok: false, + error: counted.sentence ?? "X's job cap is reached.", + ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}), + }; + } + // The start on the job's own record (and its sidecar), so a lost count + // is rebuilt from the records (jobs/xJobCap.ts). + const record = getRegistry().get(opts.job.id); + if (record && counted.at !== undefined) { + (record.xStarts ??= []).push(counted.at); + await writeJobMeta(opts.paths, record); + } + } // The jar passed at a job's START: a jar-age banner from an earlier // refusal clears. (Not at enqueue — the start follows, and enqueue stays // as cheap as it was.) @@ -299,7 +459,7 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); - } else if (!x.alert) { + } else if (!x.alert && !x.capped) { // The fresh-jar rule refused it: X's cookie banner says so on the // dashboard (kind jar-age), and a job refused at its start is offered for // "Re-run stopped jobs" once the jar is fresh. @@ -309,7 +469,7 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}), }); } - return { ok: false, error: x.message }; + return { ok: false, error: x.message, ...(x.capped && x.nextAt !== undefined ? { deferUntil: x.nextAt } : {}) }; } // Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). @@ -338,7 +498,10 @@ export async function guardNetworkJob( if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; const empty = emptyQueueRefusal(opts.kind, opts.queueKey); if (empty) return { ok: false, error: empty }; - const platform = await networkJobPlatform(opts); + // A job that asks X meets X's guard whatever queue it is on. One that does + // not is never taken for X's by its channel: its queue's platform decides. + const fromChannel = await networkJobPlatform(opts); + const platform = (await jobAsksX(opts)) ? "twitter" : fromChannel === "twitter" ? queueGapPlatform(opts.queueKey) : fromChannel; const guard = platform && Object.hasOwn(PLATFORM_GUARDS, platform) ? PLATFORM_GUARDS[platform] : undefined; return guard ? guard(opts) : { ok: true, notes: [] }; } diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -82,6 +82,7 @@ const { runManagedFunction } = await import("./streamCommand"); const { fetchPosts } = await import("../controller/fetchPosts"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); +const { xJobStartsFile } = await import("./xJobCap"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); await import("../social/xGalleryDlFetcher"); @@ -126,6 +127,10 @@ async function reset(): Promise<void> { await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + // X's job count (jobs/xJobCap.ts): each test starts from none. (Deleting + // the file would not: it is rebuilt from the earlier tests' job records.) + await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); } async function readLog(jobId: string): Promise<string> { @@ -345,3 +350,343 @@ test("a network job is never run unqueued: the override \"\" is refused", async assert.equal(local.ok, true); if (local.ok) assert.equal((await local.done).status, "done"); }); + +// ── added scope R2 (lane x-followups): X's queue only, and X's job cap ───── + +const { guardNetworkJob, jobAsksX, xSessionReport: xReport } = await import("./networkGuard"); +const { recordXJobStart, xJobCapStatus } = await import("./xJobCap"); +const { xQueueRefusal } = await import("../lib/xJobRule"); +const { runInJobContext } = await import("../lib/jobContext"); + +test("R2a: a job that asks X is refused on any queue but X's — at enqueue for every kind, and where it runs", async () => { + await reset(); + await writeJar(5 * 60_000); + const before = await runCount(); + // A named queue, another platform's queue: no job is made. + for (const queueKey of ["manual", "platform:youtube", "x-second-lane"]) { + const res = await fetchJob(SLUGS[0], new Map(), queueKey); + assert.equal(res.ok, false, queueKey); + assert.equal(res.ok ? "" : res.error, xQueueRefusal(`Fetch posts for ${SLUGS[0]}`, queueKey) ?? "?"); + } + // Every kind that asks X, by its channel: the queue it was moved to no longer hides that it is X's. + for (const kind of ["fetch-posts", "capture-posts", "check-post-availability", "import-post"]) { + assert.equal(await jobAsksX({ kind, queueKey: "manual", paths, channelSlug: SLUGS[0] }), true); + const g = await guardNetworkJob({ kind, queueKey: "platform:youtube", paths, channelSlug: SLUGS[0] }); + assert.equal(g.ok, false, kind); + assert.match(g.ok ? "" : g.error, /asks X, and X jobs run on X's queue only \(platform:twitter\): the queue "platform:youtube" is refused/); + } + // …and the kinds that have no channel are X's by their queue (a trending read, an X run). + assert.equal(await jobAsksX({ kind: "read-x-trending", queueKey: "platform:twitter", paths }), true); + assert.equal(await jobAsksX({ kind: "download-missing", queueKey: "platform:youtube", paths }), false); + // WHERE IT RUNS: a job that is on another queue anyway (a context made by hand) is refused by the fetch itself. + const ran = await runInJobContext({ jobId: "by-hand", kind: "fetch-posts", queueKey: "manual", onLog: () => {}, staleServices: new Set() }, () => + fetchPosts({ paths, slug: SLUGS[0], settings: getSettings() }), + ); + assert.equal(ran.ok, false); + assert.match(ran.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused\..* Nothing was asked\.$/); + assert.equal(await runCount(), before, "gallery-dl was never started"); +}); + +test("R2b: X's job cap — the 13th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { + await reset(); + await writeJar(5 * 60_000); + const before = await runCount(); + // Eleven starts on record, of whatever kinds; then one fetch through the funnel is the twelfth. + for (let i = 0; i < 11; i++) await recordXJobStart(paths, fakeNow); + const twelfth = await fetchJob(SLUGS[0], new Map()); + assert.equal(twelfth.ok, true, twelfth.ok ? "" : twelfth.error); + if (twelfth.ok) assert.equal((await twelfth.done).status, "done"); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); + // The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. + for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) { + const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); + assert.equal(res.ok, false, kind); + assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); + } + assert.equal(await runCount(), before + 1); + // The cap raises no cookie banner: it is not the jar's fault. + assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); + // get x-session: the count, the caps, and the refusal. + const report = await xReport({ paths }); + assert.equal(report.allowed, false); + assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true, nextAt: "string" }); + assert.match(report.reason ?? "", /^X's job cap is reached/); + // An hour on, the oldest starts have left the window and X jobs start again. + fakeNow += 61 * 60_000; + await writeJar(5 * 60_000); + const after = await fetchJob(SLUGS[3], new Map()); + assert.equal(after.ok, true, after.ok ? "" : after.error); + if (after.ok) assert.equal((await after.done).status, "done"); +}); + +test("R2b: the start is counted once, by the last guard before the work; a look counts nothing; a job that met the cap while it waited is refused at its start", async () => { + await reset(); + await writeJar(5 * 60_000); + const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; + const job = { id: "job-1" }; + const opts = { kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0] }; + // Enqueue, and the start's first guard: looks. + assert.equal((await guardNetworkJob(opts)).ok, true); + assert.equal((await guardNetworkJob({ ...opts, job })).ok, true); + assert.equal(await count(), 0); + // The last guard before the work: one start. + assert.equal((await guardNetworkJob({ ...opts, job, countStart: true })).ok, true); + assert.equal(await count(), 1); + // An X run's own start asks X nothing; each channel's turn in it is a start. + assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); + assert.equal(await count(), 1); + assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: SLUGS[1], job, countStart: true })).ok, true); + assert.equal(await count(), 2); + // A job that is no X job is not counted. + assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); + assert.equal(await count(), 2); + // The cap fills while a job waits its turn: its start is refused, and the refused start is not counted. + for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + const late = await guardNetworkJob({ ...opts, job, countStart: true }); + assert.equal(late.ok, false); + assert.match(late.ok ? "" : late.error, /^X's job cap is reached/); + assert.equal(await count(), 12); + // A count that cannot be read refuses every X job, at enqueue and at the start. + await writeFile(path.join(transcripts, ".x-session", "job-starts.json"), "{broken"); + for (const g of [await guardNetworkJob(opts), await guardNetworkJob({ ...opts, job, countStart: true })]) { + assert.equal(g.ok, false); + assert.match(g.ok ? "" : g.error, /^X's job count cannot be read .*no X job starts while it is unreadable/); + } + await reset(); +}); + +// ── review 2 (lane x-followups): one bucket, what counts, deferred ───────── + +const { getRegistry } = await import("./registry"); +const { readJobMeta } = await import("./jobMeta"); + +async function writeSettings(x: Record<string, unknown>, top: Record<string, unknown> = {}): Promise<void> { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ ...top, social: { x } })); +} +async function channelSpec(slug: string, spec: string | undefined): Promise<void> { + const file = path.join(transcripts, "channels", slug, "config.json"); + const config = JSON.parse(await readFile(file, "utf8")); + if (spec === undefined) delete config.cookiesFromBrowser; + else config.cookiesFromBrowser = spec; + await writeFile(file, JSON.stringify(config)); +} + +test("M1: ONE count for the machine — a flipped login source, a respelled cookie spec, a channel's own spec and an X run over channels of different specs all fill the same cap", async () => { + await reset(); + await writeJar(5 * 60_000); + const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; + const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true }); + try { + // Three starts on the connected profile. + for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 3); + // The login source flipped to the browser: the same count, not a fresh one. + await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }); + assert.equal((await xReport({ paths })).cap.lastHour, 3); + for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 6); + // The same browser spelled another way: still the same count. + await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: " firefox:default " }); + assert.equal((await xReport({ paths })).cap.lastHour, 6); + assert.equal((await start("capture-posts", SLUGS[1])).ok, true); + // A channel with a cookie spec of its own: the same count. + await channelSpec(SLUGS[2], "chromium"); + assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 7); + assert.equal((await start("check-post-availability", SLUGS[2])).ok, true); + // An X run over channels of different specs: each channel one start, in the one count. + await channelSpec(SLUGS[3], "brave"); + await channelSpec(SLUGS[4], "chromium:Profile 2"); + for (const slug of [SLUGS[3], SLUGS[4], SLUGS[5], SLUGS[6]]) assert.equal((await start("x-run", slug)).ok, true); + assert.equal(await count(), 12); + // The thirteenth is refused whatever it uses. + for (const [x, top, slug] of [ + [{ cookieSource: "profile" }, {}, SLUGS[7]], + [{ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], + [{ cookieSource: "browser" }, { cookiesFromBrowser: "safari" }, SLUGS[3]], + ] as const) { + await writeSettings(x, top); + const refused = await start("fetch-posts", slug); + assert.equal(refused.ok, false); + assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + } + // get x-session names no login: the count is the machine's. + const report = await xReport({ paths }); + assert.equal("login" in report, false); + assert.deepEqual([report.cap.lastHour, report.cap.reached], [12, true]); + } finally { + await writeSettings({ cookieSource: "profile" }); + for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined); + await reset(); + } +}); + +test("R-a: a trending library's media-only capture is not counted and not refused by the cap; its keep capture and a capture with shots are", async () => { + await reset(); + await writeJar(5 * 60_000); + const lib = "x-trending-lib"; + await mkdir(path.join(transcripts, "channels", lib), { recursive: true }); + await writeFile( + path.join(transcripts, "channels", lib, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: lib, xTrending: {} }), + ); + const mediaOnly = { ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; + const capture = (params: Record<string, unknown>, countStart = true) => + guardNetworkJob({ kind: "capture-posts", queueKey: "platform:twitter", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params }, job: { id: "ra" }, ...(countStart ? { countStart: true } : {}) }); + const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; + assert.equal((await capture(mediaOnly)).ok, true); + assert.equal(await count(), 0, "the media-only capture is not a start"); + assert.equal((await capture({ ...mediaOnly, keptMedia: true })).ok, true); + assert.equal((await capture({ ...mediaOnly, shots: true })).ok, true); + assert.equal(await count(), 2, "the keep capture and the capture with shots are"); + // The cap reached: the media-only capture still starts (it asks x.com nothing); the others are refused. + for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + assert.equal((await capture(mediaOnly, false)).ok, true); + assert.equal((await capture(mediaOnly)).ok, true); + for (const params of [{ ...mediaOnly, keptMedia: true }, { ...mediaOnly, shots: true }, { ...mediaOnly, articles: undefined }]) { + const refused = await capture(params, false); + assert.equal(refused.ok, false); + assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached/); + } + // It still meets the rest of X's guard: the queue, and the jar. + const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "manual", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params: mediaOnly } }); + assert.equal(moved.ok, false); + await writeJar(5 * 60 * 60_000); + const stale = await capture(mediaOnly, false); + assert.equal(stale.ok, false); + assert.doesNotMatch(stale.ok ? "" : stale.error, /job cap/); + await rm(path.join(transcripts, "channels", lib), { recursive: true, force: true }); + await reset(); +}); + +test("R-b: a job that meets the cap AT ITS START ends deferred — done, not failed, the sentence and when the next may start, no banner, nothing asked", async () => { + await reset(); + await writeJar(5 * 60_000); + const before = await runCount(); + // An X job holds the queue (it is the first start). + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate }); + assert.equal(blocker.ok, true); + for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20)); + // Ten more: eleven. The next passes its enqueue (a slot is left)… + for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + const late = await fetchJob(SLUGS[1], new Map()); + assert.equal(late.ok, true, late.ok ? "" : late.error); + // …and the cap fills while it waits behind the first. + await recordXJobStart(paths, fakeNow); + release(); + if (!blocker.ok || !late.ok) return; + await blocker.done; + const end = await late.done; + assert.equal(end.status, "done"); + const record = getRegistry().get(late.jobId)!; + assert.ok(record.deferred, "the record says it was deferred"); + assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt); + assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m); + assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m); + const meta = await readJobMeta(paths, late.jobId); + assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]); + // Nothing was asked, no start was counted, and no cookie banner was raised. + assert.equal(await runCount(), before); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); + assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); + // The first job's own record carries its start (the count can be rebuilt from it). + assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1); + await reset(); +}); + +test("S5: an X channel's jobs that ask x.com nothing pass off X's queue; those that ask it are X's — refused elsewhere, on X's queue by default", async () => { + await reset(); + // A stale jar and a full cap: nothing that is X's would start. + await writeJar(5 * 60 * 60_000); + for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); + const slug = SLUGS[0]; + const g = (kind: string, queueKey: string, params?: Record<string, unknown>, channelSlug: string | undefined = slug) => + guardNetworkJob({ kind, queueKey, paths, ...(channelSlug ? { channelSlug } : {}), ...(params ? { spec: { kind, slug, params } as never } : {}) }); + // They ask no platform: they pass, whatever X's jar and cap say. + for (const [kind, queueKey, params] of [ + ["transcribe-one", `transcribe-one:${slug}:1`], + ["fetch-windows", "clips:saved-video"], + ["fetch-window", "clips:saved-video"], + ["import-media", `import-media:${slug}`], + ["import-archive-org", "platform:archiveorg"], + ["import-one", "platform:archiveorg", { url: "https://archive.org/details/example" }], + ] as const) { + const r = await g(kind, queueKey, params); + assert.equal(r.ok, true, `${kind} on ${queueKey}: ${r.ok ? "" : r.error}`); + } + // They ask x.com: X's, so refused off X's queue (and by the jar on it). + for (const [kind, queueKey, params, channelSlug] of [ + ["fetch-window", "clips:twitter", undefined, slug], + ["fetch-windows", "clips:twitter", undefined, undefined], + ["record-live", `record-live:${slug}:1`, undefined, slug], + ["check-kept-deleted", `channel:${slug}`, undefined, slug], + ["redownload-incomplete-bucket", "transcription", undefined, slug], + ["import-one", "platform:youtube", { url: "https://x.com/example/status/1" }, "not-an-x-channel"], + ] as const) { + const r = await g(kind, queueKey, params, channelSlug); + assert.equal(r.ok, false, `${kind} on ${queueKey}`); + assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, `${kind} on ${queueKey}`); + } + // Where they are queued by default for an X channel: X's queue. + const { clipWindowQueueKey } = await import("../lib/queueKeys"); + const { platformQueueKey } = await import("../lib/platform"); + assert.equal(clipWindowQueueKey(platformQueueKey("twitter")), "platform:twitter"); + assert.equal(clipWindowQueueKey(platformQueueKey("youtube")), "clips:youtube"); + await reset(); +}); + +test("review 4 B: an import of a file by an X page's address is X's on any channel — refused off X's queue; a local file's or another page's passes", async () => { + await reset(); + await writeJar(5 * 60 * 60_000); + for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); + const yt = "yt-chan-r4"; + await mkdir(path.join(transcripts, "channels", yt), { recursive: true }); + await writeFile(path.join(transcripts, "channels", yt, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: yt, url: "https://www.youtube.com/@example" })); + // import-media has no replay descriptor: what it will ask is given to the guards alone. + const g = (slug: string, url?: string) => + guardNetworkJob({ kind: "import-media", queueKey: `import-media:${slug}`, paths, channelSlug: slug, ...(url ? { askParams: { url } } : {}) }); + for (const [slug, url] of [[yt, "https://t.co/AbC"], [yt, "https://x.com/example/status/1"], [SLUGS[0], "https://t.co/AbC"]] as const) { + const r = await g(slug, url); + assert.equal(r.ok, false, `${url} on ${slug}`); + assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, `${url} on ${slug}`); + } + for (const [slug, url] of [[yt, "https://www.youtube.com/watch?v=a"], [SLUGS[0], "https://www.youtube.com/watch?v=a"], [SLUGS[0], undefined]] as const) { + const r = await g(slug, url); + assert.equal(r.ok, true, `${url ?? "a local file"} on ${slug}: ${r.ok ? "" : r.error}`); + } + await reset(); +}); + +test("review 3 M2/S5: a window job is X's by its URLs on any channel; a URL-less item by its own channel, in a batch across channels", async () => { + await reset(); + await writeJar(5 * 60 * 60_000); + for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); + const yt = "yt-chan-r3"; + await mkdir(path.join(transcripts, "channels", yt), { recursive: true }); + await writeFile(path.join(transcripts, "channels", yt, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: yt, url: "https://www.youtube.com/@example" })); + const xs = SLUGS[0]; + const g = (kind: string, queueKey: string, params: Record<string, unknown>, channelSlug?: string) => + guardNetworkJob({ kind, queueKey, paths, ...(channelSlug ? { channelSlug } : {}), spec: { kind, slug: channelSlug ?? yt, params } as never }); + const it = (slug: string, webpageUrl?: string) => ({ slug, id: "1", from: 1, to: 2, ...(webpageUrl ? { webpageUrl } : {}) }); + const refusedOffX = (r: Awaited<ReturnType<typeof g>>, what: string) => { + assert.equal(r.ok, false, what); + assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, what); + }; + // An x.com video on a YouTube channel: X's (POST /api/media/fetch-window with a body webpageUrl). + refusedOffX(await g("fetch-window", "clips:youtube", { webpageUrl: "https://x.com/example/status/1" }, yt), "a single x.com window on a non-X channel"); + refusedOffX(await g("fetch-windows", "clips:youtube", { items: [it(yt, "https://x.com/example/status/1")] }, yt), "a batch item's x.com URL"); + // A multi-channel batch under a queue override: one URL-less item of an X channel makes it X's. + refusedOffX(await g("fetch-windows", "manual", { items: [it(yt, "https://www.youtube.com/watch?v=a"), it(xs)] }), "a URL-less X item in a multi-channel batch"); + // Passes: no URL of X's and no item of an X channel without one. + for (const [what, r] of [ + ["find-copy's windows on archive.org's clip queue, for an X channel", await g("fetch-windows", "clips:archiveorg", { items: [it(xs, "https://archive.org/details/example")] }, xs)], + ["a mirror on another platform", await g("fetch-windows", "clips:rumble", { items: [it(xs, "https://rumble.com/v-example.html")] }, xs)], + ["a multi-channel batch of YouTube pages", await g("fetch-windows", "manual", { items: [it(yt, "https://www.youtube.com/watch?v=a"), it(yt)] })], + ["fetch-copies of one X channel's gone videos", await g("fetch-copies", "platform:archiveorg", {}, xs)], + ] as const) { + assert.equal(r.ok, true, `${what}: ${r.ok ? "" : r.error}`); + } + await reset(); +}); diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -181,6 +181,15 @@ export type JobRecord = { resumeCount?: number; // The line the job's log opens with when it is a resume (what it resumes). resumeNote?: string; + // X'S JOB CAP (lib/xJobRule.ts, jobs/xJobCap.ts): the starts this job was + // counted for (one for a job; one per channel for an X run). Kept on its + // sidecar, so a count file that is lost is rebuilt from the records. + xStarts?: number[]; + // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached + // when its queue started it, so it did not run — not a failure. It ends + // `done` with this: the sentence, and when the next X job may start. + // Nothing re-queues it by itself. + deferred?: { until: number; sentence: string }; }; // Store a progress snapshot on the record, stamping `progressAt` only when the diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -77,6 +77,9 @@ type CommonOpts = { // When set, recorded on the job (and its meta sidecar) so the job can be // re-launched (retried) later. See common/jobs/jobSpec.ts. spec?: JobSpec; + // What a job with no `spec` will ask, for the network guard alone + // (jobs/networkGuard.ts askParams): never recorded on the job. + askParams?: Readonly<Record<string, unknown>>; // Background jobs queue BEHIND any foreground (default) job on the same // queueKey: a manually-triggered job (sync, manual download) jumps ahead of // queued background work without interrupting a running one. The auto-download @@ -419,6 +422,18 @@ async function refuseForUnreachableMedia( } } +// A job its queue started that may not run yet (X's job cap): it ends +// deferred, not failed (JobRecord.deferred). +export class JobDeferredError extends Error { + constructor( + message: string, + readonly until: number, + ) { + super(message); + this.name = "JobDeferredError"; + } +} + export async function runManagedFunction( opts: RunManagedFunctionOpts, ): Promise<StreamActionResult> { @@ -530,9 +545,9 @@ export async function runManagedFunction( // go stale during a five-minute wait. Only a job that reached its work // counts as an end for the next one's gap. const network = opts.network !== false && kindIsNetwork(opts.kind); - const guard = async () => { - const res = await guardNetworkJob({ ...opts, job: { id } }); - if (!res.ok) throw new Error(res.error); + const guard = async (countStart = false) => { + const res = await guardNetworkJob({ ...opts, job: { id }, ...(countStart ? { countStart: true } : {}) }); + if (!res.ok) throw res.deferUntil !== undefined ? new JobDeferredError(res.error, res.deferUntil) : new Error(res.error); return res.notes; }; const run = async () => { @@ -561,7 +576,9 @@ export async function runManagedFunction( } throw err; } - for (const note of await guard()) onLog(note); + // The last guard before the work: an X job that passes it is counted + // against X's job cap (lib/xJobRule.ts). + for (const note of await guard(true)) onLog(note); reachedWork = true; } await runInJobContext(jobCtx, () => opts.fn(onLog, abort.signal, setProgress, ctx)); @@ -587,6 +604,15 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + // X'S JOB CAP, MET AT THE START (review 2, ruling R-b): the job did + // not run and did not fail. It ends `done`, DEFERRED, with the + // sentence and when the next X job may start; nothing re-queues it. + if (err instanceof JobDeferredError) { + record.deferred = { until: err.until, sentence: err.message }; + onLog(`[deferred] ${err.message}`); + registry.finalize(id, "done"); + return; + } onLog(`[error] ${(err as Error).message}`); // A job that met a stale service's cookies (a cookie refresh alert) // ends naming the cause and the fix, after its own error line. diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts @@ -7,7 +7,7 @@ import { } from "../lib/channelPriority"; import { defaultSyncScheduler } from "../lib/settings"; import type { SyncSchedulerSettings } from "../lib/settings"; -import { emptySchedulerState } from "./syncSchedulerState"; +import { emptyChannelSyncState, emptySchedulerState } from "./syncSchedulerState"; import { buildScheduleView, selectDueChannels, @@ -15,6 +15,7 @@ import { syncJitterMs, SYNC_JITTER_CAP_MS, nextEligibleAfterFailure, + foldScheduledSyncOutcome, } from "./syncScheduler"; // Run with: @@ -294,3 +295,77 @@ test("a remote-only channel never syncs, even with a url, and the console says s const view = buildScheduleView({ channels, scheduler: scheduler(), state: emptySchedulerState(), now: NOW, priority: NO_MODEL }); assert.deepEqual(view.map((v) => [v.slug, v.autoSyncEligible]), [["own", true], ["remote", false]]); }); + +// REVIEW 2, RULING R-b (lane x-followups): a scheduled sync X's job cap +// deferred at its start did not run. It is no failure (no strike, no growing +// backoff) and no success, and nothing queues it again before the next X job +// may start. +test("R-b: a sync deferred by X's job cap is not a failure, and the channel waits until the time the next X job may start", () => { + const sched = scheduler({ backoffBaseMinutes: 10, backoffMaxMinutes: 600 }); + const now = NOW; + const until = now + 40 * 60_000; + const cs = { ...emptyChannelSyncState(), consecutiveFailures: 2, lastQueuedJobId: "j1", lastOutcome: "failed" as const, lastOutcomeAt: now - 3_600_000 }; + assert.equal(foldScheduledSyncOutcome(cs, { status: "done", endedAt: now, deferred: { until } }, now, sched, 0), true); + assert.deepEqual( + { f: cs.consecutiveFailures, next: cs.nextEligibleAt, job: cs.lastQueuedJobId, outcome: cs.lastOutcome, at: cs.lastOutcomeAt }, + { f: 2, next: until, job: null, outcome: "failed", at: now - 3_600_000 }, + ); + // The scheduler does not pick it before then — and does after. + const state = { ...emptySchedulerState(), channels: { "x-chan": cs } }; + const pick = (at: number) => selectDueChannels({ channels: [channel("x-chan", DAY)], scheduler: sched, state, activeSlugs: new Set<string>(), now: at, priority: NO_MODEL }).due.map((d) => (typeof d === "string" ? d : (d as { slug: string }).slug)); + assert.deepEqual(pick(until - 1), []); + assert.deepEqual(pick(until + 1), ["x-chan"]); + // A plain end is folded as before: done resets, failed grows, cancelled is neutral, queued/running wait. + const done = { ...emptyChannelSyncState(), consecutiveFailures: 2, lastQueuedJobId: "j" }; + foldScheduledSyncOutcome(done, { status: "done", endedAt: now }, now, sched, 0); + assert.deepEqual([done.consecutiveFailures, done.nextEligibleAt, done.lastOutcome], [0, null, "ok"]); + const failed = { ...emptyChannelSyncState(), lastQueuedJobId: "j" }; + foldScheduledSyncOutcome(failed, { status: "failed", endedAt: now }, now, sched, 0); + assert.deepEqual([failed.consecutiveFailures, failed.nextEligibleAt, failed.lastOutcome], [1, nextEligibleAfterFailure(now, 1, sched, 0), "failed"]); + const cancelled = { ...emptyChannelSyncState(), lastQueuedJobId: "j" }; + foldScheduledSyncOutcome(cancelled, { status: "cancelled" }, now, sched, 0); + assert.deepEqual([cancelled.consecutiveFailures, cancelled.nextEligibleAt, cancelled.lastQueuedJobId], [0, null, null]); + const running = { ...emptyChannelSyncState(), lastQueuedJobId: "j" }; + assert.equal(foldScheduledSyncOutcome(running, { status: "running" }, now, sched, 0), false); + assert.equal(running.lastQueuedJobId, "j"); +}); + +// Review 3 N9: at X's hour cap with one start left, queueing every due X +// channel would start one and defer the rest, each a job for nothing. The +// tick queues at most the starts the cap has left — less the X jobs already +// waiting on X's queue — and holds the rest for a later tick. A look: no +// start is recorded. +test("review 3 N9: no more X syncs are queued than the cap has starts left; the others wait, and the rest are untouched", async () => { + const { limitXSyncs } = await import("./syncScheduler"); + const isX = (slug: string) => slug.startsWith("x-"); + const due = ["x-a", "yt-a", "x-b", "x-c", "yt-b"]; + // One start left, none waiting: one X channel, every other channel. + const one = limitXSyncs(due, isX, { room: 1, waiting: 0 }); + assert.deepEqual(one.queue, ["x-a", "yt-a", "yt-b"]); + assert.deepEqual(one.held.map((h) => h.slug), ["x-b", "x-c"]); + assert.match(one.held[0].reason, /^X's job cap: 1 X job may start now and 0 are waiting on X's queue — queued on a later tick/); + // The start left is taken by an X job already waiting: none. + assert.deepEqual(limitXSyncs(due, isX, { room: 1, waiting: 1 }).queue, ["yt-a", "yt-b"]); + // Room enough: all. + assert.deepEqual(limitXSyncs(due, isX, { room: 12, waiting: 2 }).queue, due); + assert.deepEqual(limitXSyncs(due, isX, { room: 12, waiting: 2 }).held, []); +}); + +// Review 4 D: a running X job whose start is not counted yet (waiting out +// X's gap before its guard) takes the cap's room as surely as a queued one. +test("review 4 D: X jobs waiting are the queued ones and the running ones that have not recorded a start", async () => { + const { xJobsWaiting } = await import("./syncScheduler"); + const X = "platform:twitter"; + assert.equal( + xJobsWaiting([ + { status: "queued", queueKey: X }, + { status: "running", queueKey: X }, + { status: "running", queueKey: X, xStarts: [] }, + { status: "running", queueKey: X, xStarts: [1] }, + { status: "done", queueKey: X }, + { status: "queued", queueKey: "platform:youtube" }, + { status: "running", queueKey: "platform:youtube" }, + ]), + 3, + ); +}); diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -1,5 +1,7 @@ import { isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; +import { X_QUEUE_KEY } from "../lib/xJobRule"; import type { SyncSchedulerSettings } from "../lib/settings"; import { type ChannelPriority, @@ -9,7 +11,7 @@ import { tierOrder, } from "../lib/channelPriority"; import { resolveFullSweepIntervalMinutes } from "./deepSync"; -import type { SchedulerSkip, SchedulerState } from "./syncSchedulerState"; +import type { ChannelSyncState, SchedulerSkip, SchedulerState } from "./syncSchedulerState"; import { jitterUp, stableUnit } from "../lib/jitter.mjs"; // Pure, side-effect-free scheduling logic for the cron-driven sync system. It @@ -53,8 +55,61 @@ export type SelectDueInput = { // so the tick asks and hands the sentence in). Every Instagram channel is // then skipped with it, and takes no sync slot. instagramHeld?: string | null; + // WHY NO X JOB STARTS NOW, when X's job cap is reached (lib/xJobRule.ts; + // the tick asks jobs/networkGuard.ts xCapHeldReason and hands the sentence + // in). Every X posts channel is then skipped with it and takes no sync + // slot: a sync queued anyway would be refused, each tick, as a failed job. + xCapHeld?: string | null; }; +// Why an X posts channel is not synced now, or null: X's job cap is reached. +export function xSyncHold( + config: Pick<ChannelConfig, "sourceKind" | "platform"> & Partial<Pick<ChannelConfig, "url">>, + held: string | null | undefined, +): string | null { + if (!held || config.sourceKind !== "social") return null; + return (config.platform ?? detectPlatform(config.url)) === "twitter" ? held : null; +} + +// NO MORE X SYNCS THAN X'S CAP HAS STARTS LEFT (review 3 N9). With one start +// left in the hour, queueing every due X channel would start one and defer +// the rest at their start — a job each for nothing. `room`: the starts the +// cap has left now (jobs/networkGuard.ts xCapRoom, a look: nothing counted); +// `waiting`: X jobs already waiting on X's queue (xJobsWaiting), which take that room first. +// The X channels past it are held for a later tick; every other channel is +// queued as it was. +// THE X JOBS THAT WILL TAKE THE CAP'S ROOM BEFORE A SYNC QUEUED NOW (review 4 +// D): every one queued on X's queue, and every one running there that has not +// recorded a start yet (waiting out X's gap before its guard counts it). A +// running job that counts nothing is taken for one that will — more rather +// than fewer: a sync held a tick, never one deferred at its start. +export function xJobsWaiting(records: ReadonlyArray<{ status: string; queueKey: string; xStarts?: readonly number[] }>): number { + return records.filter( + (r) => r.queueKey === X_QUEUE_KEY && (r.status === "queued" || (r.status === "running" && !(r.xStarts?.length))), + ).length; +} + +export function limitXSyncs( + toQueue: readonly string[], + isX: (slug: string) => boolean, + cap: { room: number; waiting: number }, +): { queue: string[]; held: Array<{ slug: string; reason: string }> } { + let left = Math.max(0, cap.room - cap.waiting); + const queue: string[] = []; + const held: Array<{ slug: string; reason: string }> = []; + const reason = + `X's job cap: ${cap.room} X job${cap.room === 1 ? "" : "s"} may start now and ${cap.waiting} ${cap.waiting === 1 ? "is" : "are"} waiting on X's queue — ` + + "queued on a later tick, not deferred at its start"; + for (const slug of toQueue) { + if (!isX(slug)) queue.push(slug); + else if (left > 0) { + queue.push(slug); + left--; + } else held.push({ slug, reason }); + } + return { queue, held }; +} + // WHY AN INSTAGRAM CHANNEL IS NOT SYNCED NOW, or null (review 1, S10). A // channel with no cookie source of its own would be refused by its fetch // before anything is asked; one while Instagram is held, by the guard. Either @@ -135,6 +190,38 @@ export function isInQuietHours( return hour >= start || hour < end; } +// ONE SCHEDULED SYNC'S END, FOLDED INTO ITS CHANNEL'S BACKOFF (the tick's +// reconcile, editor/app/scheduler/runTick.ts). `done` resets the failures; +// `failed` grows them and the backoff; `cancelled` is neutral. A job that +// ended DEFERRED by X's job cap (review 2, ruling R-b: it did not run) is no +// failure and no success: the failures stay as they were, and the channel is +// not eligible again before the time the next X job may start — nothing +// re-queues it earlier. True when the job had ended (and was folded). +export function foldScheduledSyncOutcome( + cs: ChannelSyncState, + job: { status: string; endedAt?: number; deferred?: { until: number } }, + now: number, + scheduler: SyncSchedulerSettings, + spread: number, +): boolean { + if (job.status === "queued" || job.status === "running") return false; + if (job.status === "done" && job.deferred) { + cs.nextEligibleAt = Math.max(cs.nextEligibleAt ?? 0, job.deferred.until); + } else if (job.status === "done") { + cs.consecutiveFailures = 0; + cs.nextEligibleAt = null; + cs.lastOutcome = "ok"; + cs.lastOutcomeAt = job.endedAt ?? now; + } else if (job.status === "failed") { + cs.consecutiveFailures += 1; + cs.nextEligibleAt = nextEligibleAfterFailure(now, cs.consecutiveFailures, scheduler, spread); + cs.lastOutcome = "failed"; + cs.lastOutcomeAt = job.endedAt ?? now; + } + cs.lastQueuedJobId = null; + return true; +} + // Exponential backoff (minutes) after N consecutive failures: base * 2^(N-1), // capped at max. 0 failures => no backoff. export function backoffMinutes( @@ -207,6 +294,12 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult { if (igHold !== INSTAGRAM_SYNC_NO_COOKIES) skipped.push({ slug, reason: igHold }); continue; } + // X's job cap is reached: its channels wait, like a cooldown. + const xHold = xSyncHold(config, input.xCapHeld); + if (xHold) { + skipped.push({ slug, reason: xHold }); + continue; + } if (activeSlugs.has(slug)) { skipped.push({ slug, reason: "already running" }); @@ -313,10 +406,12 @@ export function buildScheduleView(input: { jitter?: number; // SelectDueInput.instagramHeld: the same sentence, for the same skip. instagramHeld?: string | null; + // SelectDueInput.xCapHeld: the same. + xCapHeld?: string | null; }): ChannelScheduleView[] { const { channels, scheduler, state, now, priority } = input; return channels.map(({ slug, config }) => { - const igHold = instagramSyncHold(config, input.instagramHeld); + const igHold = instagramSyncHold(config, input.instagramHeld) ?? xSyncHold(config, input.xCapHeld); const interval = resolveIntervalMinutes(config, scheduler); const sweepInterval = resolveFullSweepIntervalMinutes(config, scheduler); const cs = state.channels[slug]; diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts @@ -0,0 +1,266 @@ +// X's job count on disk (jobs/xJobCap.ts): one bucket for the machine (review +// 2 M1), kept across a restart, failing closed, and rebuilt from the job +// records when its file is gone (ruling R-c). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xJobCap.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { X_RECORDS_KEPT_FILE, rebuildXJobStarts, recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap"; +import { ulid } from "./ulid"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-job-cap-")); +after(() => rmSync(TMP, { recursive: true, force: true })); +const corpus = (name: string) => { + const transcriptsDir = path.join(TMP, name); + return { transcriptsDir, jobsDir: path.join(transcriptsDir, ".jobs") }; +}; +const T0 = Date.parse("2026-11-18T12:00:00.000Z"); +const MIN = 60_000; +const HOUR = 60 * MIN; +const fileOf = (paths: ReturnType<typeof corpus>) => JSON.parse(readFileSync(xJobStartsFile(paths), "utf8")); +const meta = (paths: ReturnType<typeof corpus>, m: Record<string, unknown>, at: number = T0) => { + mkdirSync(paths.jobsDir, { recursive: true }); + const id = (m.id as string | undefined) ?? ulid(at); + writeFileSync(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, queuedAt: at, status: "done", ...m })); + return id; +}; + +// The pruner's word that it keeps every X record that may still count, since `since` (review 3 M3). +const keptSince = (paths: ReturnType<typeof corpus>, since: number) => { + mkdirSync(paths.jobsDir, { recursive: true }); + writeFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), JSON.stringify({ version: 1, since })); +}; + +test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { + const paths = corpus("disk"); + for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); + const refused = await recordXJobStart(paths, T0 + 12 * MIN); + assert.equal(refused.ok, false); + assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + // A refused start records nothing; the file is one list, with no login in it. + assert.deepEqual(Object.keys(fileOf(paths)).sort(), ["starts", "version"]); + assert.equal(fileOf(paths).version, 2); + assert.equal(fileOf(paths).starts.length, 12); + // "Restart": nothing is in memory; the file is the count. + const again = await xJobCapStatus(paths, T0 + 13 * MIN); + assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); + // A start recorded with the clock set back is recorded at the clock's time + // (review 3 S4); the later start on record still counts, and is kept. + const p2 = corpus("disk-back"); + await recordXJobStart(p2, T0); + await recordXJobStart(p2, T0 - 600 * MIN); + assert.deepEqual(fileOf(p2).starts, [T0, T0 - 600 * MIN]); + // Starts older than a day are dropped when the next is recorded. + await recordXJobStart(p2, T0 + 25 * HOUR); + assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); + // Two at once: both recorded, neither lost. + const p3 = corpus("disk-race"); + await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, T0 + i))); + assert.equal(fileOf(p3).starts.length, 12); + assert.equal((await recordXJobStart(p3, T0 + 20)).ok, false); +}); + +test("M1: a count of the first shape (one list per login key) is the SUM of its lists, and is rewritten as one", async () => { + const paths = corpus("migrate"); + mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); + // 7 starts under the profile, 5 under a browser spec: the same machine's twelve. + const logins = { + profile: Array.from({ length: 7 }, (_, i) => T0 + i * MIN), + "browser:firefox": Array.from({ length: 5 }, (_, i) => T0 + (10 + i) * MIN), + }; + writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 1, logins })); + const status = await xJobCapStatus(paths, T0 + 20 * MIN); + assert.deepEqual([status.ok, status.lastHour], [false, 12]); + assert.equal(fileOf(paths).version, 2); + assert.equal(fileOf(paths).starts.length, 12); + assert.equal((await recordXJobStart(paths, T0 + 21 * MIN)).ok, false); +}); + +test("a count that cannot be read fails closed: no X job starts, and nothing is written over it", async () => { + for (const [name, text] of [ + ["garbage", "{not json"], + ["shape", '{"version":2,"starts":{}}'], + ["v1-shape", '{"version":1,"logins":[]}'], + ["version", '{"version":3,"starts":[]}'], + ["times", '{"version":2,"starts":["soon"]}'], + ] as const) { + const paths = corpus(`closed-${name}`); + mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); + writeFileSync(xJobStartsFile(paths), text); + const status = await xJobCapStatus(paths, T0); + assert.equal(status.ok, false, name); + assert.equal(status.unreadable, true); + assert.match(status.sentence ?? "", /^X's job count cannot be read \(.*job-starts\.json\): no X job starts while it is unreadable/); + assert.equal((await recordXJobStart(paths, T0)).ok, false); + assert.equal(readFileSync(xJobStartsFile(paths), "utf8"), text); + } +}); + +test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { + const paths = corpus("fresh"); + assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 12, perDay: 150 }); + // Records of other queues only: still zero. + const p2 = corpus("fresh-other-queues"); + meta(p2, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); + assert.equal((await xJobCapStatus(p2, T0)).lastDay, 0); +}); + +test("R-c: deleting job-starts.json does not reset the count — the last day is rebuilt from the job records", async () => { + const paths = corpus("rebuild"); + keptSince(paths, T0 - 25 * HOUR); + // Jobs that ran through the funnel: each meta says the starts it was counted for. + for (let i = 0; i < 10; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, xStarts: [T0 - i * MIN] }, T0 - i * MIN); + // An X run's channels: one start each. + meta(paths, { kind: "x-run", queueKey: "platform:twitter", startedAt: T0 - 30 * MIN, xStarts: [T0 - 30 * MIN, T0 - 25 * MIN] }, T0 - 30 * MIN); + // An X job that counted nothing (deferred, or a media-only capture): []. + meta(paths, { kind: "capture-posts", queueKey: "platform:twitter", startedAt: T0 - 2 * MIN, xStarts: [] }, T0 - 2 * MIN); + // Older than a day: not counted. + meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - 25 * HOUR, xStarts: [T0 - 25 * HOUR] }, T0 - 25 * HOUR); + // Twelve in the hour: the cap is reached although the file is gone. + const status = await xJobCapStatus(paths, T0 + MIN); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [false, 12, 12]); + assert.match(status.sentence ?? "", /^X's job cap is reached on this machine/); + // …and the rebuilt count is written. + assert.equal(fileOf(paths).starts.length, 12); + // Deleted again, then a start asked for: rebuilt under the lock, then refused. + rmSync(xJobStartsFile(paths)); + assert.equal((await recordXJobStart(paths, T0 + MIN)).ok, false); + assert.equal(fileOf(paths).starts.length, 12); +}); + +test("R-c: a record from before `xStarts` counts once at its start when its kind counts", async () => { + const paths = corpus("legacy"); + keptSince(paths, T0 - 25 * HOUR); + meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - MIN }, T0 - MIN); + meta(paths, { kind: "read-x-trending", queueKey: "platform:twitter", startedAt: T0 - 2 * MIN }, T0 - 2 * MIN); + // A library's media-only capture of that time: its channel is not read, so it counts (more rather than fewer). + meta(paths, { kind: "capture-posts", queueKey: "platform:twitter", startedAt: T0 - 3 * MIN, spec: { kind: "capture-posts", params: { shots: false, articles: false, avatars: false, context: false } } }, T0 - 3 * MIN); + // Not network (a reparse), never started, another queue: not counted. + meta(paths, { kind: "reparse-x-trending", queueKey: "platform:twitter", startedAt: T0 - 4 * MIN }, T0 - 4 * MIN); + meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", status: "cancelled" }, T0 - 5 * MIN); + meta(paths, { kind: "fetch-posts", queueKey: "platform:bluesky", startedAt: T0 - 6 * MIN }, T0 - 6 * MIN); + const rebuilt = await rebuildXJobStarts(paths, T0); + assert.equal(rebuilt.ok, true); + assert.deepEqual(rebuilt.ok ? rebuilt.starts : [], [T0 - 3 * MIN, T0 - 2 * MIN, T0 - MIN]); +}); + +test("R-c: X activity whose records cannot be read is refused — fail closed", async () => { + const gaps = (paths: ReturnType<typeof corpus>, end: number) => { + mkdirSync(paths.jobsDir, { recursive: true }); + writeFileSync(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": end } })); + }; + // X's queue ended a job an hour ago, and no record of an X job is left. + const gone = corpus("closed-no-records"); + gaps(gone, T0 - HOUR); + meta(gone, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); + const refused = await xJobCapStatus(gone, T0); + assert.equal(refused.ok, false); + assert.equal(refused.unreadable, true); + assert.match( + refused.sentence ?? "", + /^X's job count is not on disk \(.*job-starts\.json\) and cannot be rebuilt from the job records: X's queue ended a job within the last 24 hours and no record of an X job is left\. No X job starts .* at the latest until 2026-11-19 11:00 UTC/, + ); + assert.equal((await recordXJobStart(gone, T0)).ok, false); + // Nothing is written on a guess. + assert.throws(() => readFileSync(xJobStartsFile(gone))); + // A day after that end, nothing on record can still count: zero. + assert.equal((await xJobCapStatus(gone, T0 + 24 * HOUR)).ok, true); + // A record of the last day that cannot be read may be an X job's. + const torn = corpus("closed-torn"); + mkdirSync(torn.jobsDir, { recursive: true }); + writeFileSync(path.join(torn.jobsDir, `${ulid(T0 - MIN)}.meta.json`), "{torn"); + const tornStatus = await xJobCapStatus(torn, T0); + assert.equal(tornStatus.ok, false); + assert.match(tornStatus.sentence ?? "", /cannot be rebuilt from the job records: the job record .*\.meta\.json cannot be read/); + // …but one older than a day cannot count, and is passed over. + const old = corpus("old-torn"); + mkdirSync(old.jobsDir, { recursive: true }); + writeFileSync(path.join(old.jobsDir, `${ulid(T0 - 30 * HOUR)}.meta.json`), "{torn"); + assert.equal((await xJobCapStatus(old, T0)).ok, true); + // The records' directory refuses to be listed. + if (process.getuid?.() !== 0) { + const locked = corpus("closed-locked"); + mkdirSync(locked.jobsDir, { recursive: true }); + chmodSync(locked.jobsDir, 0o000); + try { + const status = await xJobCapStatus(locked, T0); + assert.equal(status.ok, false); + assert.match(status.sentence ?? "", /the job records cannot be listed \(EACCES\)/); + } finally { + chmodSync(locked.jobsDir, 0o755); + } + } +}); + +test("review 3 S4: a start in the future counts in both windows and never prunes the real ones", async () => { + const paths = corpus("future"); + mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); + // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). + const real = Array.from({ length: 10 }, (_, i) => T0 + i * MIN); + writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); + const status = await xJobCapStatus(paths, T0 + 10 * MIN); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 11, 11]); + const r = await recordXJobStart(paths, T0 + 10 * MIN); + assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 12]); + // The real starts are kept beside the future one. + assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); + assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds twelve"); +}); + +test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { + const xs = (paths: ReturnType<typeof corpus>) => { + for (let i = 0; i < 5; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, endedAt: T0 - i * MIN + 1000, xStarts: [T0 - i * MIN] }, T0 - i * MIN); + }; + // X jobs ran today; nothing says the records of the day are all there. + const paths = corpus("m3-unshown"); + xs(paths); + const refused = await xJobCapStatus(paths, T0 + MIN); + assert.equal(refused.ok, false); + assert.equal(refused.unreadable, true); + assert.match(refused.sentence ?? "", /cannot be rebuilt from the job records: records of the last 24 hours may have been deleted .* at the latest until 2026-11-19 12:01 UTC/); + assert.equal((await recordXJobStart(paths, T0 + MIN)).ok, false); + assert.throws(() => readFileSync(xJobStartsFile(paths)), "nothing is written on a guess"); + // The refusal itself starts the day after which the records are known kept. + assert.equal(JSON.parse(readFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), "utf8")).since, T0 + MIN); + // A day later the count is rebuilt (the five can no longer count). + const later = await xJobCapStatus(paths, T0 + MIN + 24 * HOUR); + assert.deepEqual([later.ok, later.lastDay], [true, 0]); + + // A FINISHED JOB THAT ENDED OVER A DAY AGO IS NO PROOF (review 4 A): a + // record of a job cancelled while queued has no log and is never pruned, and + // retention goes by id and queue time, not start time. + const shown = corpus("m3-old-finished-no-proof"); + xs(shown); + meta(shown, { kind: "sync", queueKey: "platform:youtube", status: "done", startedAt: T0 - 26 * HOUR, endedAt: T0 - 25 * HOUR }, T0 - 26 * HOUR); + meta(shown, { kind: "fetch-posts", queueKey: "platform:twitter", status: "cancelled", endedAt: T0 - 30 * HOUR }, T0 - 30 * HOUR); + const s = await xJobCapStatus(shown, T0 + MIN); + assert.equal(s.ok, false); + assert.throws(() => readFileSync(xJobStartsFile(shown)), "nothing is written on a guess"); + // SHOWN BY THE PRUNER: it has kept X's records for over a day. + const pruner = corpus("m3-shown-by-pruner"); + xs(pruner); + keptSince(pruner, T0 - 25 * HOUR); + assert.deepEqual([(await xJobCapStatus(pruner, T0 + MIN)).ok, (await xJobCapStatus(pruner, T0 + MIN)).lastDay], [true, 5]); + // …for less than a day: not yet. + const recent = corpus("m3-pruner-recent"); + xs(recent); + keptSince(recent, T0 - 2 * HOUR); + const r = await xJobCapStatus(recent, T0 + MIN); + assert.equal(r.ok, false); + assert.match(r.sentence ?? "", /at the latest until 2026-11-19 10:00 UTC/); + // A MARKER IN THE FUTURE IS NO PROOF (review 4 A): refused, as with none, + // and the refusal ends within a day. + const ahead = corpus("m3-pruner-future"); + xs(ahead); + keptSince(ahead, T0 + 365 * 24 * HOUR); + const f = await xJobCapStatus(ahead, T0 + MIN); + assert.equal(f.ok, false); + assert.match(f.sentence ?? "", /at the latest until 2026-11-19 12:01 UTC/); + assert.throws(() => readFileSync(xJobStartsFile(ahead)), "nothing is written on a guess"); + const aheadLater = await xJobCapStatus(ahead, T0 + MIN + 24 * HOUR); + assert.deepEqual([aheadLater.ok, aheadLater.lastDay], [true, 0]); +}); diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts @@ -0,0 +1,277 @@ +// X'S JOB COUNT, ON DISK (lane x-followups, R2; review 2 M1 and ruling R-c): +// every counted X job's start on this machine, ONE list, in +// `<transcripts>/.x-session/job-starts.json`: +// { "version": 2, "starts": [<ms>, …] } +// The rule and its numbers are lib/xJobRule.ts. Here: +// - the file is read and written under its lock (one check-and-record at a +// time) and survives a restart; +// - ONE BUCKET: the count is the machine's, whatever login source, cookie +// spec or channel a job uses. A file of the first shape (version 1, one +// list per login key) is read as the SUM of its lists and rewritten as one; +// - it FAILS CLOSED: a file that is there and cannot be read or parsed +// refuses every X job until it is repaired; +// - A FILE THAT IS NOT THERE IS NOT AN EMPTY COUNT (ruling R-c): the last +// 24 hours of counted starts are rebuilt from the job records (each job's +// `<id>.meta.json` carries the starts it was counted for, `xStarts`) and +// written. When X jobs ran (X's queue gap names an end in the last day) +// but their records cannot be read — the directory refuses, a record of +// the day is unreadable, or none is left — every X job is refused. A +// corpus where no X job ever ran starts at zero. +// +// SERVER-ONLY (node:fs). In jobs/ (not lib/) because it reads the job records. + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { + X_JOB_CAP, + X_QUEUE_KEY, + xJobCapSentence, + xJobCapUnreadableSentence, + xJobCapUnrebuildableSentence, + xJobCapVerdict, + xJobCounts, + type XJobCapVerdict, +} from "../lib/xJobRule"; +import { kindIsNetwork } from "./jobKinds"; +import { QUEUE_GAPS_FILE } from "./queueGap"; +import { jobIdTime } from "./ulid"; + +type CapPaths = Pick<Paths, "transcriptsDir" | "jobsDir">; + +export function xJobStartsFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "job-starts.json"); +} + +type StartsFile = { version: 2; starts: number[] }; + +const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); + +// The file as it is: absent, unreadable (fail closed), or its starts (a +// version-1 file's lists summed into one — `migrated`). +async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; starts: number[]; migrated: boolean }> { + const read = await readJsonFile(xJobStartsFile(paths)); + if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" }; + const v = read.value as { version?: unknown; starts?: unknown; logins?: unknown } | null; + if (!v || typeof v !== "object") return { state: "bad" }; + if (v.version === 2) { + if (!Array.isArray(v.starts) || !v.starts.every(finite)) return { state: "bad" }; + return { state: "ok", starts: [...v.starts], migrated: false }; + } + if (v.version === 1) { + // THE FIRST SHAPE, ONE LIST PER LOGIN KEY: every login's starts are the + // machine's, so they are summed. + if (!v.logins || typeof v.logins !== "object" || Array.isArray(v.logins)) return { state: "bad" }; + const starts: number[] = []; + for (const list of Object.values(v.logins as Record<string, unknown>)) { + if (!Array.isArray(list) || !list.every(finite)) return { state: "bad" }; + starts.push(...list); + } + return { state: "ok", starts: starts.sort((a, b) => a - b), migrated: true }; + } + return { state: "bad" }; +} + +// ── the records are kept (review 3 M3) ───────────────────────────────────── + +// RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT +// (jobs/listJobs.ts pruneJobLogs asks xRecordMayCount), and says since when it +// has kept them: `<jobsDir>/x-records-kept.json`, {version: 1, since: <ms>}, +// written once, by the first prune (or rebuild) of code that keeps them. A +// rebuild trusts the records of the last day only when that is over a day +// old. The marker is the ONLY proof (review 4 A): an old finished record on +// disk shows nothing (a job cancelled while queued has no log and is never +// pruned; retention goes by id and queue time, not start time). A "since" +// after now is no proof either: it is said again, at now. +export const X_RECORDS_KEPT_FILE = "x-records-kept.json"; + +export async function readXRecordsKeptSince(paths: Pick<Paths, "jobsDir">): Promise<number | undefined> { + const read = await readJsonFile(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE)); + const since = read.ok ? (read.value as { since?: unknown } | null)?.since : undefined; + return finite(since) ? since : undefined; +} + +// Said once: a "since" already on disk is never moved later. One after `now` +// (a clock that jumped) proves nothing and is said again at `now`, so the +// refusal it causes ends within a day (review 4 A). +export async function noteXRecordsKept(paths: Pick<Paths, "jobsDir">, now: number): Promise<number> { + const had = await readXRecordsKeptSince(paths); + if (had !== undefined && had <= now) return had; + await writeJsonAtomic(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), { version: 1, since: now }, { mkdir: true }); + return now; +} + +// MAY THIS RECORD STILL COUNT AGAINST X'S CAP? An X-queue record (or one that +// says it was counted) with a start, a counted start or its queueing inside +// the last day — or after `now`; and a record that cannot be read whose id +// is of the last day (or of no known day). Kept by retention while it may. +export function xRecordMayCount(id: string, meta: Record<string, unknown> | null, now: number): boolean { + const since = now - X_JOB_CAP.dayMs; + const born = jobIdTime(id); + if (!meta) return born === 0 || born > since; + const xStarts = Array.isArray(meta.xStarts) ? meta.xStarts.filter(finite) : []; + if (meta.queueKey !== X_QUEUE_KEY && xStarts.length === 0) return false; + return [...xStarts, meta.startedAt, born].some((t) => finite(t) && t > since); +} + +// ── the rebuild (ruling R-c) ─────────────────────────────────────────────── + +export type XJobStartsRebuild = + | { ok: true; starts: number[]; records: number } + | { ok: false; why: string; until?: number }; + +// The last day's counted X starts, from the job records. A record written by +// this code says its starts (`xStarts`, [] for an X job that counted none); a +// record of X's queue from before it is counted once at its start when its +// kind and plan count (lib/xJobRule.ts xJobCounts) — more rather than fewer. +export async function rebuildXJobStarts(paths: Pick<Paths, "jobsDir">, now: number): Promise<XJobStartsRebuild> { + const since = now - X_JOB_CAP.dayMs; + // The evidence that X jobs ran in the last day: X's queue gap's last end. + let lastXEnd: number | undefined; + const gaps = await readJsonFile(path.join(paths.jobsDir, QUEUE_GAPS_FILE)); + if (gaps.ok) { + const end = (gaps.value as { ends?: Record<string, unknown> } | null)?.ends?.[X_QUEUE_KEY]; + if (finite(end) && end > since) lastXEnd = end; + } + const until = lastXEnd !== undefined ? lastXEnd + X_JOB_CAP.dayMs : undefined; + let names: string[]; + try { + names = await readdir(paths.jobsDir); + } catch (err) { + const code = (err as NodeJS.ErrnoException)?.code; + if (code === "ENOENT" || code === "ENOTDIR") return { ok: true, starts: [], records: 0 }; + return { ok: false, why: `the job records cannot be listed (${code ?? (err as Error).message})`, ...(until ? { until } : {}) }; + } + const starts: number[] = []; + let records = 0; + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + const id = name.slice(0, -".meta.json".length); + const born = jobIdTime(id); + let m: Record<string, unknown> | null = null; + try { + const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown; + m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null; + } catch { + m = null; + } + if (!m) { + // A record of the last day (or of no known day) that cannot be read may + // be an X job's: nothing is counted on a guess. + if (born === 0 || born > since) return { ok: false, why: `the job record ${name} cannot be read`, ...(until ? { until } : {}) }; + continue; + } + if (m.queueKey !== X_QUEUE_KEY) continue; + if (Array.isArray(m.xStarts)) { + records++; + for (const t of m.xStarts) if (finite(t) && t > since) starts.push(t); + continue; + } + // A record from before `xStarts`: once, at its start, when it would count. + const kind = typeof m.kind === "string" ? m.kind : ""; + const at = finite(m.startedAt) ? m.startedAt : undefined; + if (!kindIsNetwork(kind) || at === undefined) continue; + records++; + const spec = m.spec as { params?: Record<string, unknown> } | undefined; + // The channel is not read: a record of a library's media-only capture is + // counted (more rather than fewer). + if (at > since && xJobCounts({ kind, ...(spec?.params ? { params: spec.params } : {}) })) starts.push(at); + } + // X jobs ran, and not one record of them is left. + if (lastXEnd !== undefined && records === 0) { + return { ok: false, why: "X's queue ended a job within the last 24 hours and no record of an X job is left", ...(until ? { until } : {}) }; + } + // X JOBS RAN TODAY: THE RECORDS MUST BE SHOWN TO COVER THE DAY (review 3 + // M3). A count from records retention may have thinned is a guess, and + // nothing is counted on a guess. + if (lastXEnd !== undefined || starts.length > 0) { + const kept = await noteXRecordsKept(paths, now); + if (!(kept <= since)) { + const ends = [kept + X_JOB_CAP.dayMs, ...(until !== undefined ? [until] : [])]; + return { + ok: false, + why: + "records of the last 24 hours may have been deleted (by the jobs list's retention or Clear logs, before it kept X's): " + + "nothing shows they are all there", + until: Math.min(...ends), + }; + } + } + return { ok: true, starts: starts.sort((a, b) => a - b), records }; +} + +// ── the count ────────────────────────────────────────────────────────────── + +export type XJobCapStatus = XJobCapVerdict & { + perHour: number; + perDay: number; + // The count could not be read or rebuilt: `ok` is false and nothing starts. + unreadable?: true; + // The refusal, when `ok` is false. + sentence?: string; +}; + +function statusOf(starts: ReadonlyArray<number>, now: number): XJobCapStatus { + const v = xJobCapVerdict(starts, now); + return { ...v, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, ...(v.ok ? {} : { sentence: xJobCapSentence(v, now) }) }; +} + +function closed(sentence: string): XJobCapStatus { + return { ok: false, lastHour: 0, lastDay: 0, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence }; +} + +// What a day can still count (the longer window), as of `now`: a start in +// the future is kept, and never a reason to drop the real ones (review 3 S4). +function keptOf(starts: ReadonlyArray<number>, now: number): number[] { + return starts.filter((t) => t > now - X_JOB_CAP.dayMs); +} + +async function writeStarts(paths: CapPaths, starts: number[]): Promise<void> { + await writeJsonAtomic(xJobStartsFile(paths), { version: 2, starts } satisfies StartsFile, { mkdir: true }); +} + +// The starts, HOLDING THE FILE'S LOCK: a version-1 file rewritten as one +// list; an absent one rebuilt from the job records and written; or the +// refusal's sentence. +async function loadLocked(paths: CapPaths, now: number): Promise<{ ok: true; starts: number[] } | { ok: false; sentence: string }> { + const file = await readStartsFile(paths); + if (file.state === "bad") return { ok: false, sentence: xJobCapUnreadableSentence(xJobStartsFile(paths)) }; + if (file.state === "ok") { + if (file.migrated) await writeStarts(paths, keptOf(file.starts, now)); + return { ok: true, starts: file.starts }; + } + const rebuilt = await rebuildXJobStarts(paths, now); + if (!rebuilt.ok) return { ok: false, sentence: xJobCapUnrebuildableSentence(xJobStartsFile(paths), rebuilt.why, rebuilt.until) }; + await writeStarts(paths, keptOf(rebuilt.starts, now)); + return { ok: true, starts: rebuilt.starts }; +} + +// Would an X job start now? Nothing is counted (a file to migrate or rebuild +// is written, under the lock). +export async function xJobCapStatus(paths: CapPaths, now: number = Date.now()): Promise<XJobCapStatus> { + const file = await readStartsFile(paths); + if (file.state === "ok" && !file.migrated) return statusOf(file.starts, now); + if (file.state === "bad") return closed(xJobCapUnreadableSentence(xJobStartsFile(paths))); + const loaded = await withJsonFileLock(xJobStartsFile(paths), () => loadLocked(paths, now)); + return loaded.ok ? statusOf(loaded.starts, now) : closed(loaded.sentence); +} + +// ONE X JOB STARTS: checked and recorded in one step, under the file's lock. +// `ok: false` — the cap is reached, or the count cannot be read — records +// nothing, and the job does not start. `at` is the time recorded: the +// clock's (a start already on record later than it still counts — S4). +export async function recordXJobStart(paths: CapPaths, now: number = Date.now()): Promise<XJobCapStatus & { at?: number }> { + return withJsonFileLock(xJobStartsFile(paths), async () => { + const loaded = await loadLocked(paths, now); + if (!loaded.ok) return closed(loaded.sentence); + const before = statusOf(loaded.starts, now); + if (!before.ok) return before; + const at = now; + const starts = [...keptOf(loaded.starts, now), at]; + await writeStarts(paths, starts); + // This start was within the cap: said so, with the count it leaves. + const after = statusOf(starts, now); + return { ok: true, lastHour: after.lastHour, lastDay: after.lastDay, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, at }; + }); +} 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?, 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.', + '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–40 scrolls, default 20; 1–400 posts, default 200; each of the page\'s two tabs has both); 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/clipWindow.ts b/common/lib/clipWindow.ts @@ -446,3 +446,16 @@ export function tightestClipWindow<T extends ClipWindowSpan>( } return best; } + +// A CALLER'S PAGE ADDRESS FOR A LOCAL CHANNEL IS A FULL http(s) ADDRESS +// (review 4 C; POST /api/media/fetch-window, a fetch-windows item): one written +// without its scheme ("x.com/…") is read by no rule the same way twice. A +// remote-only channel's is parsed and written back instead (lib/remoteArchives.ts +// recordPage). +export function isFullPageAddress(raw: string): boolean { + return /^https?:\/\//i.test(raw.trim()); +} + +export function pageAddressRefusal(raw: string): string { + return `webpageUrl must be an http(s) address (https://…): ${JSON.stringify(raw.trim())} is not one. Nothing was asked.`; +} diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts @@ -141,7 +141,12 @@ export function downloadQueueKey(config: ChannelConfig): string { // Takes the platform queue a window would otherwise have run on // (`downloadQueueKey`, `queueKeyForUrl`), so an unrecognized host keeps its // per-domain key: `platform:vimeo.com` → `clips:vimeo.com`. +// +// EXCEPT X's (lane x-followups, review 2 S5): an X window asks x.com with X's +// cookies, and X jobs run on X's queue only (lib/xJobRule.ts) — spaced by +// X's gap and counted under X's job cap like every other X job. export function clipWindowQueueKey(platformQueue: string): string { + if (platformQueue === "platform:twitter") return platformQueue; return `clips:${platformQueue.replace(/^platform:/, "")}`; } diff --git a/common/lib/timelineWalk.test.ts b/common/lib/timelineWalk.test.ts @@ -157,3 +157,16 @@ test("the status lines say a backfill is unfinished, and what continues a stoppe assert.equal(describeTimelineSync({}), null); assert.match(describeTimelineSync({ sync: { cursor: "1/S", since: WATERMARK } }) ?? "", /down to 2026-11-01/); }); + +// Lane x-followups: a resumed backfill re-read archived posts, was taken for finished ("caught up") +// and lost its resume point. +test("a backfill is never finished by meeting known posts: its resume point is kept", () => { + const walks = { backfill: { cursor: "3_1899000000000000041/", savedAt: "2026-11-17T00:00:00.000Z" }, sync: { cursor: "1/S", since: "2026-11-01T00:00:00.000Z" } }; + const plan = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true, caughtUp: true }, NOW), walks); + // The timeline's real end clears it, as before. + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), { sync: walks.sync }); + // A SYNC that caught up is finished: that is what catching up means for it. + const sync = planTimelineRun("sync", walks, "2026-11-10T00:00:00.000Z") as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(sync, walks, { complete: true, caughtUp: true }, NOW), { backfill: walks.backfill }); +}); diff --git a/common/lib/timelineWalk.ts b/common/lib/timelineWalk.ts @@ -163,16 +163,23 @@ export function planTimelineRun( // clears its own slot (a full re-walk that finished clears both: it read // everything); one that stopped part-way saves its resume point there, or // keeps the one it had when it learned none. The other slot is never touched. +// +// A BACKFILL IS NEVER FINISHED BY MEETING KNOWN POSTS (lane x-followups): a +// run that ended "caught up" (`caughtUp`: a run of posts already archived, a +// sync's stop) says nothing of the history below them. A resumed backfill +// that ends so keeps the resume point it had. A resumed walk once re-read +// archived posts, was taken for finished, and its point was cleared. export function settleTimelineRun( plan: TimelineRunPlan, prior: TimelineWalks, - outcome: { complete: boolean; cursor?: string }, + outcome: { complete: boolean; cursor?: string; caughtUp?: boolean }, now: string, ): TimelineWalks { const next: TimelineWalks = { ...(prior.backfill ? { backfill: prior.backfill } : {}), ...(prior.sync ? { sync: prior.sync } : {}), }; + if (outcome.complete && outcome.caughtUp && plan.mode === "backfill") return next; if (outcome.complete) { if (plan.mode === "full") return {}; if (plan.saveTo === "sync") delete next.sync; diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -0,0 +1,280 @@ +// X's two rules (lib/xJobRule.ts) and what counts. The count on disk is jobs/xJobCap.test.ts. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xJobRule.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { runInJobContext } from "./jobContext"; +import { X_JOB_CAP, X_QUEUE_KEY, isXUrl, xJobCapSentence, xJobCapVerdict, xJobAsksX, xJobContextRefusal, xJobCounts, xQueueRefusal } from "./xJobRule"; + +const T0 = Date.parse("2026-11-18T12:00:00.000Z"); +const MIN = 60_000; + +test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { + assert.deepEqual({ ...X_JOB_CAP }, { perHour: 12, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); + assert.ok(Object.isFrozen(X_JOB_CAP)); + assert.equal(X_QUEUE_KEY, "platform:twitter"); + // Nothing in the rule's two modules reads a setting, an environment variable or an option. + for (const file of ["xJobRule.ts", "../jobs/xJobCap.ts"]) { + const code = readFileSync(path.join(import.meta.dirname, file), "utf8").replace(/^\s*\/\/.*$/gm, ""); + assert.doesNotMatch(code, /process\.env|getSettings|settings\b|\bforce\b/i, file); + } +}); + +test("the hour window: the 13th start in 60 minutes is refused, and says when the next may start", () => { + const starts = Array.from({ length: 12 }, (_, i) => T0 + i * 5 * MIN); // 12:00 … 12:55 + assert.deepEqual(xJobCapVerdict(starts.slice(0, 11), T0 + 56 * MIN), { ok: true, lastHour: 11, lastDay: 11 }); + const full = xJobCapVerdict(starts, T0 + 56 * MIN); + assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" }); + assert.equal( + xJobCapSentence(full, T0 + 56 * MIN), + "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " + + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it.", + ); + // Rolling: at 13:00 the 12:00 start has left the window (a start exactly 60 minutes old is out). + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN - 1).ok, false); + // X's own gap (5 minutes) makes exactly 12 an hour: the cap never bites a run at the default gap. + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 11); +}); + +test("the day window: the 151st start in 24 hours is refused until the oldest of the last 150 is a day old", () => { + const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 9 * MIN); // one every 9 minutes: 22.5 hours + const now = T0 + 150 * 9 * MIN; + const full = xJobCapVerdict(starts, now); + assert.equal(full.ok, false); + assert.equal(full.window, "day"); + assert.equal(full.lastDay, 150); + assert.equal(full.nextAt, T0 + 24 * 60 * MIN); + assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in 90 min\)/); + // The day is named when it is not today's. + assert.match(xJobCapSentence(xJobCapVerdict(starts, T0 + 151 * 9 * MIN - 23 * 60 * MIN), T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); + assert.equal(xJobCapVerdict(starts, T0 + 24 * 60 * MIN).ok, true); + assert.equal(xJobCapVerdict(starts.slice(1), now).ok, true); +}); + +test("a clock set back never frees a start early", () => { + const starts = Array.from({ length: 12 }, (_, i) => T0 + i * MIN); // 12:00 … 12:11 + // The clock now reads two hours EARLIER than the latest start: every start still counts. + const back = xJobCapVerdict(starts, T0 - 120 * MIN); + assert.equal(back.ok, false); + assert.equal(back.lastHour, 12); + assert.equal(back.nextAt, T0 + 60 * MIN); + // Only once the clock has passed them again by the window do they leave it. + assert.equal(xJobCapVerdict(starts, T0 + 59 * MIN).ok, false); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); +}); + +test("X jobs run on X's queue only: any other queue is refused, when queued and where the job runs", () => { + assert.equal(xQueueRefusal("fetch-posts for example-x", "platform:twitter"), null); + assert.equal( + xQueueRefusal("fetch-posts for example-x", "manual"), + 'fetch-posts for example-x asks X, and X jobs run on X\'s queue only (platform:twitter): the queue "manual" is refused. ' + + "On another queue it would run beside the job on X's, outside the gap between X jobs. Leave the queue at its default.", + ); + assert.match(xQueueRefusal("x", "platform:youtube") ?? "", /"platform:youtube" is refused/); + assert.match(xQueueRefusal("x", undefined) ?? "", /the queue it was given is refused/); + const ctx = (queueKey?: string) => ({ jobId: "j", kind: "fetch-posts", ...(queueKey ? { queueKey } : {}), onLog: () => {}, staleServices: new Set<string>() }); + // No job at all. + assert.match(xJobContextRefusal("example-x", "pnpm ops fetch-posts") ?? "", /^example-x asks X, and X is asked only by the editor's own jobs .* nothing was asked\. Queue it instead: pnpm ops fetch-posts$/); + // A job on another queue. + assert.match(runInJobContext(ctx("manual"), () => xJobContextRefusal("example-x", "d")) ?? "", /the queue "manual" is refused\..* Nothing was asked\.$/); + assert.match(runInJobContext(ctx(), () => xJobContextRefusal("example-x", "d")) ?? "", /the queue it was given is refused/); + // X's queue. + assert.equal(runInJobContext(ctx("platform:twitter"), () => xJobContextRefusal("example-x", "d")), null); +}); + +test("ruling R-a: what counts is decided from the job's own plan — only a library's media-only capture, with no way to the login, does not", () => { + // The watch's follow-up capture with shots off, as the editor queues it (xTrendingActions.ts afterXTrendingRead). + const mediaOnly = { queueKey: undefined, ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; + const library = { library: true }; + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: library }), false); + // Each way to a page or to the login makes it count. + for (const [what, params] of [ + ["shots on", { ...mediaOnly, shots: true }], + ["shots by default", { ...mediaOnly, shots: undefined }], + ["articles by default", { ...mediaOnly, articles: undefined }], + ["avatars by default", { ...mediaOnly, avatars: undefined }], + ["context by default", { ...mediaOnly, context: undefined }], + ["a thread shot", { ...mediaOnly, thread: true }], + ["avatars only", { ...mediaOnly, avatarsOnly: true }], + ["context only", { ...mediaOnly, contextOnly: true }], + ["the keep capture (login fallback)", { ...mediaOnly, keptMedia: true }], + ] as const) { + assert.equal(xJobCounts({ kind: "capture-posts", params, channel: library }), true, what); + } + // The channel's thread default counts when the plan does not say no. + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true, postCaptureThread: true } }), true); + assert.equal(xJobCounts({ kind: "capture-posts", params: { ...mediaOnly, thread: false }, channel: { library: true, postCaptureThread: true } }), false); + // Not a library: an X channel's media comes through gallery-dl with X's cookies. + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: false } }), true); + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly }), true); + // No plan to read: it counts. + assert.equal(xJobCounts({ kind: "capture-posts", channel: library }), true); + // Every other kind of X job counts, whatever its params say. + for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing"]) { + assert.equal(xJobCounts({ kind, params: mediaOnly, channel: library }), true, kind); + } +}); + +test("S5: which network jobs ask x.com — by X's queue, X's clip queue, an import's URL, or an X channel's job that is not local", () => { + const x = (kind: string, queueKey: string, params?: Record<string, unknown>) => xJobAsksX({ kind, queueKey, channelPlatform: "twitter", ...(params ? { params } : {}) }); + // X's queue, whatever the kind and channel. + assert.equal(xJobAsksX({ kind: "transcribe-one", queueKey: "platform:twitter" }), true); + assert.equal(xJobAsksX({ kind: "fetch-windows", queueKey: "clips:twitter" }), true, "X's clip windows, a batch with no channel"); + // An X channel's jobs that ask x.com, on any other queue: X's (and refused there). + for (const [kind, queueKey] of [ + ["fetch-posts", "manual"], + ["fetch-window", "clips:twitter"], + ["fetch-windows", "clips:twitter"], + ["record-live", "record-live:x-chan:1"], + ["check-kept-deleted", "channel:x-chan"], + ["redownload-incomplete-bucket", "transcription"], + ["import-media", "platform:youtube"], + ["sync", "platform:youtube"], + ] as const) { + assert.equal(x(kind, queueKey), true, `${kind} on ${queueKey}`); + } + // An X channel's jobs that ask x.com nothing: never X's. + assert.equal(x("transcribe-one", "transcribe-one:x-chan:1"), false, "the transcription worker: local"); + assert.equal(x("fetch-windows", "clips:saved-video"), false, "windows cut from the saved copy on disk"); + assert.equal(x("fetch-window", "clips:saved-video"), false); + assert.equal(x("import-media", "import-media:x-chan"), false, "a local file (a URL on X is queued on X's queue)"); + assert.equal(x("import-archive-org", "platform:archiveorg"), false, "archive.org"); + assert.equal(x("import-one", "platform:archiveorg", { url: "https://archive.org/details/example" }), false, "the URL's host"); + // An import asks its URL's host, whatever the channel and queue. + assert.equal(xJobAsksX({ kind: "import-one", queueKey: "platform:youtube", channelPlatform: "youtube", params: { url: "https://x.com/example/status/1" } }), true); + assert.equal(xJobAsksX({ kind: "import-one", queueKey: "platform:youtube", channelPlatform: "youtube", params: { url: "https://twitter.com/example/status/1" } }), true); + assert.equal(x("import-one", "platform:twitter", { url: "https://x.com/example/status/1" }), true); + // Not an X channel, not X's queue: not X's. + assert.equal(xJobAsksX({ kind: "fetch-posts", queueKey: "platform:bluesky", channelPlatform: "bluesky" }), false); + assert.equal(xJobAsksX({ kind: "fetch-window", queueKey: "clips:youtube", channelPlatform: "youtube" }), false); + // The transcription worker asks x.com nothing even on X's queue: it does not count. + assert.equal(xJobCounts({ kind: "transcribe-one" }), false); +}); + +// Review 3 M2, S5, S6: a window job is X's by the URL it will fetch, on ANY +// channel; an item with no URL is its channel's; t.co is X's. +test("review 3 M2: a window job is judged by its URLs — an x.com or twitter.com page on any channel is X's", () => { + const yt = (kind: string, queueKey: string, params: Record<string, unknown>, channelPlatform: string | null = "youtube") => + xJobAsksX({ kind, queueKey, channelPlatform, params }); + // The single window: its webpageUrl, on a channel that is not X's. + assert.equal(yt("fetch-window", "clips:youtube", { webpageUrl: "https://x.com/example/status/1" }), true); + assert.equal(yt("fetch-window", "clips:youtube", { webpageUrl: "https://mobile.twitter.com/example/status/1" }), true); + assert.equal(yt("fetch-window", "clips:youtube", { webpageUrl: "https://www.youtube.com/watch?v=abc" }), false); + // A batch: any item's URL that is X's makes the whole job X's. + const items = (...urls: Array<string | undefined>) => urls.map((u, i) => ({ slug: "c", id: `v${i}`, from: 1, to: 2, ...(u ? { webpageUrl: u } : {}) })); + assert.equal(yt("fetch-windows", "clips:youtube", { items: items("https://www.youtube.com/watch?v=a", "https://x.com/example/status/2") }), true); + assert.equal(yt("fetch-windows", "manual", { items: items("https://x.com/example/status/2") }, null), true, "a multi-channel batch under a queue override"); + assert.equal(yt("fetch-windows", "clips:youtube", { items: items("https://www.youtube.com/watch?v=a") }), false); + // X's own queue is X's whatever the URLs. + assert.equal(yt("fetch-windows", "platform:twitter", { items: items("https://www.youtube.com/watch?v=a") }), true); + // Windows cut from the saved copy: the controller never takes the network + // for an X source there (M1), so the queue passes whatever the URL. + assert.equal(yt("fetch-windows", "clips:saved-video", { items: items("https://x.com/example/status/2") }, "twitter"), false); +}); + +test("review 3 S5: an X channel's window of a copy or a mirror on another platform passes; an item with no URL is its channel's", () => { + const x = (kind: string, queueKey: string, params?: Record<string, unknown>, extra: Partial<Parameters<typeof xJobAsksX>[0]> = {}) => + xJobAsksX({ kind, queueKey, channelPlatform: "twitter", ...(params ? { params } : {}), ...extra }); + const item = (webpageUrl?: string, slug = "x-chan") => ({ slug, id: "1", from: 1, to: 2, ...(webpageUrl ? { webpageUrl } : {}) }); + // find-copy's windows of a copy, on archive.org's clip queue. + assert.equal(x("fetch-windows", "clips:archiveorg", { items: [item("https://web.archive.org/web/2026/https://example.org/v.mp4"), item("https://archive.org/details/example")] }), false); + // A mirror of the X video on another platform. + assert.equal(x("fetch-window", "clips:twitter-mirror", { webpageUrl: "https://rumble.com/v-example.html" }), false); + assert.equal(x("fetch-windows", "clips:rumble", { items: [item("https://rumble.com/v-example.html")] }), false); + // NO URL NEVER PASSES BY ITSELF: the item's channel decides. + assert.equal(x("fetch-window", "clips:youtube", {}), true, "a single window with no URL on an X channel"); + assert.equal(x("fetch-window", "clips:youtube"), true, "no plan at all on an X channel"); + assert.equal(x("fetch-windows", "clips:archiveorg", { items: [item("https://archive.org/details/example"), item(undefined)] }), true); + // A multi-channel batch: each URL-less item by its own channel's platform. + const multi = { items: [item("https://archive.org/details/example", "yt-chan"), item(undefined, "x-chan")] }; + assert.equal(xJobAsksX({ kind: "fetch-windows", queueKey: "manual", params: multi, itemChannelPlatforms: { "yt-chan": "youtube", "x-chan": "twitter" } }), true); + assert.equal(xJobAsksX({ kind: "fetch-windows", queueKey: "manual", params: multi, itemChannelPlatforms: { "yt-chan": "youtube", "x-chan": "youtube" } }), false); + // fetch-copies: archive.org's (its controller refuses an X address). + assert.equal(x("fetch-copies", "platform:archiveorg"), false); +}); + +test("review 3 S6: a t.co short link is X's", () => { + for (const url of ["https://t.co/AbCdEf123", "http://t.co/x", "https://www.t.co/x"]) { + assert.equal(isXUrl(url), true, url); + assert.equal(xJobAsksX({ kind: "import-one", queueKey: "platform:youtube", channelPlatform: "youtube", params: { url } }), true, url); + } + for (const url of ["https://not-t.co/x", "https://example.com/t.co", "https://nottwitter.com/x", "not a url", ""]) { + assert.equal(isXUrl(url), false, url); + } + assert.equal(isXUrl("https://x.com/a/status/1"), true); + assert.equal(isXUrl("https://twitter.com/a/status/1"), true); +}); + +test("review 4 C: X's addresses — a trailing dot, X's media hosts, a schemeless address; never a lookalike or a userinfo", () => { + for (const url of [ + "https://x.com./u/status/1", + "https://twitter.com./u/status/1", + "https://t.co./AbC", + "https://video.twimg.com/ext_tw_video/1/pu/vid/720x1280/a.mp4", + "https://pbs.twimg.com/media/abc.jpg", + "https://twimg.com/x", + "x.com/u/status/1", + "twitter.com/u/status/1", + "mobile.twitter.com/u/status/1", + "t.co/AbC", + "video.twimg.com/a.mp4", + "X.COM/u/status/1", + "//x.com/u/status/1", + " https://x.com/u/status/1 ", + "HTTPS://X.COM/u/status/1", + "https://mobile.TWITTER.com/u/status/1", + "https://evil.example@x.com/u/status/1", + "https://x.com:443/u/status/1", + "x.com:443/u/status/1", + ]) { + assert.equal(isXUrl(url), true, url); + } + for (const url of [ + "https://x.com@evil.example/u/status/1", + "https://x.com.evil.example/u/status/1", + "https://evilx.com/u", + "https://nottwitter.com/u", + "https://twitter.com.evil.example/u", + "https://nottwimg.com/a.mp4", + "https://twimg.com.evil.example/a.mp4", + "https://t.co.evil.example/a", + "evil.example/x.com/u/status/1", + "x.com.evil.example/u", + "nottwitter.com/u", + "mailto:someone@example.org", + "javascript:alert(1)", + "/u/status/1", + "x", + ]) { + assert.equal(isXUrl(url), false, url); + } +}); + +test("review 4 B: an import of a file by its page is X's by that page's address, on any channel", () => { + const im = (url: string | undefined, channelPlatform: string, queueKey = "import-media:c") => + xJobAsksX({ kind: "import-media", queueKey, channelPlatform, ...(url !== undefined ? { params: { url } } : {}) }); + for (const url of ["https://x.com/u/status/1", "https://t.co/AbC", "https://twitter.com/u/status/1"]) { + assert.equal(im(url, "youtube"), true, `${url} on a YouTube channel`); + assert.equal(im(url, "twitter"), true, `${url} on an X channel`); + } + assert.equal(im("https://www.youtube.com/watch?v=a", "twitter"), false, "another platform's page, on an X channel"); + assert.equal(im("https://rumble.com/v-a.html", "rumble"), false); + assert.equal(im(undefined, "twitter"), false, "a local file with no page"); + assert.equal(im("https://x.com/u/status/1", "youtube", "platform:twitter"), true, "on X's queue"); +}); + +test("review 3 S4: a start in the future counts in both windows, and never moves the windows off the real starts", () => { + const real = Array.from({ length: 11 }, (_, i) => T0 + i * MIN); + const future = T0 + 365 * 24 * 60 * MIN; + const v = xJobCapVerdict([...real, future], T0 + 11 * MIN); + assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 12, 12]); + // The next may start when the oldest of the newest twelve has left: the real 12:00 start, at 13:00. + assert.equal(v.nextAt, T0 + 60 * MIN); + // The future start alone keeps counting until the clock has passed it by the window. + assert.deepEqual([xJobCapVerdict([future], T0).lastHour, xJobCapVerdict([future], T0).lastDay], [1, 1]); + assert.equal(xJobCapVerdict([future], future + 60 * MIN).lastHour, 0); +}); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -0,0 +1,300 @@ +// THE TWO RULES EVERY X JOB MEETS, AND THEIR NUMBERS (lane x-followups, R2; +// the operator, 18 Nov 2026: "X should refuse and/or have an immutable global +// per-account cap"). ONE module: the constants are here and nowhere else. +// +// 1. X JOBS RUN ON X'S QUEUE ONLY (`platform:twitter`). A job that asks X +// as the connected account or with X's cookies — a posts fetch in any +// mode, a resumed backfill, a sync, a capture, a trending read, an +// import of an X post, an availability check, a channel's turn in an X +// run — is refused on any other queue: when it is queued +// (jobs/networkGuard.ts) and again where it runs (xJobContextRefusal, +// asked by the code that is about to ask X). On another queue it would +// run beside the job on X's and outside the gap between X jobs. +// +// 2. A CAP NOBODY CAN RAISE: at most X_JOB_CAP.perHour X jobs started in any +// rolling 60 minutes and X_JOB_CAP.perDay in any rolling 24 hours, ON +// THIS MACHINE, over every kind of X job together (review 2 M1: ONE +// bucket — never one per login source, cookie spec or channel, which a +// flipped source or a respelled spec would turn into a fresh count for +// the same X account). A job past it is refused before it starts, with +// the time the next may start; one that meets it AT its start ends +// deferred, not failed (jobs/networkGuard.ts). +// +// WHAT COUNTS (review 2, ruling R-a): a job that can ask x.com with the +// login or X's cookies — xJobCounts below, decided from the job's own plan +// (its kind and its spec), never from a flag a caller passes. +// +// THE CAP IS A CONSTANT OF THE CODE. It is not in settings.json, not in a +// channel's config, not an environment variable, not an option of any action +// or command, and no `force` passes it. Changing it is a code change, reviewed +// like one. Nothing in this module reads a setting. +// +// Pure but for xJobContextRefusal, which reads the running job's context +// (lib/jobContext.ts). The count's file is jobs/xJobCap.ts. + +import { currentJobContext } from "./jobContext"; + +export const X_QUEUE_KEY = "platform:twitter"; + +export const X_JOB_CAP = Object.freeze({ + perHour: 12, + hourMs: 60 * 60_000, + perDay: 150, + dayMs: 24 * 60 * 60_000, +}); + +// ── 1. the queue ─────────────────────────────────────────────────────────── + +// Why a job that asks X may not be on `queueKey`, or null. `what` names the +// job ("fetch-posts for example-x"). +export function xQueueRefusal(what: string, queueKey: string | undefined): string | null { + if (queueKey === X_QUEUE_KEY) return null; + return ( + `${what} asks X, and X jobs run on X's queue only (${X_QUEUE_KEY}): the queue ` + + `${queueKey === undefined || queueKey === "" ? "it was given" : `"${queueKey}"`} is refused. ` + + "On another queue it would run beside the job on X's, outside the gap between X jobs. Leave the queue at its default." + ); +} + +// WHERE X IS ABOUT TO BE ASKED: only inside a job of the editor's, and only +// one on X's queue. Null when the caller stands there. `door` names the way +// in ("pnpm ops fetch-posts --json '{…}' --wait"). +export function xJobContextRefusal(what: string, door: string): string | null { + const job = currentJobContext(); + if (!job) { + return ( + `${what} asks X, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh ` + + `cookie jar, under X's job cap, stopped by the X alert and held after a rate limit): nothing was asked. ` + + `Queue it instead: ${door}` + ); + } + const queue = xQueueRefusal(what, job.queueKey); + return queue ? `${queue} Nothing was asked.` : null; +} + +// ── 2. the cap ───────────────────────────────────────────────────────────── + +export type XJobCapVerdict = { + ok: boolean; + // X jobs started in the last 60 minutes and the last 24 hours. + lastHour: number; + lastDay: number; + // When the next X job may start (ms since the epoch), when `ok` is false. + nextAt?: number; + window?: "hour" | "day"; +}; + +// THE CLOCK NEVER FREES A START EARLY, AND A START IN THE FUTURE NEVER HIDES +// THE REAL ONES (review 3 S4). A window is every start later than `now` minus +// its length — a start stamped after `now` included: a machine clock set back +// (by a person, by a time sync) leaves every recorded start inside its window +// until the clock has passed it again, and one stamped far ahead (a clock that +// jumped forward) counts in both windows without pushing the windows past the +// starts around it. +export function xJobCapVerdict(starts: ReadonlyArray<number>, now: number): XJobCapVerdict { + const recent = [...starts].filter((t) => Number.isFinite(t)).sort((a, b) => b - a); + const hour = recent.filter((t) => t > now - X_JOB_CAP.hourMs); + const day = recent.filter((t) => t > now - X_JOB_CAP.dayMs); + const out = { lastHour: hour.length, lastDay: day.length }; + // The next may start once the oldest of the newest <cap> starts has left its window. + const hourFree = hour.length >= X_JOB_CAP.perHour ? hour[X_JOB_CAP.perHour - 1] + X_JOB_CAP.hourMs : null; + const dayFree = day.length >= X_JOB_CAP.perDay ? day[X_JOB_CAP.perDay - 1] + X_JOB_CAP.dayMs : null; + if (hourFree === null && dayFree === null) return { ok: true, ...out }; + const window = dayFree !== null && (hourFree === null || dayFree >= hourFree) ? "day" : "hour"; + return { ok: false, ...out, nextAt: Math.max(hourFree ?? 0, dayFree ?? 0), window }; +} + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); +const day = (ms: number) => new Date(ms).toISOString().slice(0, 10); + +// The refusal: which cap, how full, and when the next X job may start. +export function xJobCapSentence(v: XJobCapVerdict, now: number): string { + if (v.ok || v.nextAt === undefined) return ""; + const full = + v.window === "day" + ? `${v.lastDay} X jobs started in the last 24 hours (the cap is ${X_JOB_CAP.perDay})` + : `${v.lastHour} X jobs started in the last 60 minutes (the cap is ${X_JOB_CAP.perHour})`; + const minutes = Math.max(1, Math.ceil((v.nextAt - now) / 60_000)); + const when = `${day(v.nextAt) === day(now) ? "" : `${day(v.nextAt)} `}${hhmm(v.nextAt)} UTC`; + const wait = minutes >= 120 ? `about ${Math.round(minutes / 60)} h` : `${minutes} min`; + return ( + `X's job cap is reached on this machine: ${full}. The next X job may start at ${when} (in ${wait}); ` + + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it." + ); +} + +// The sentence for a count that cannot be read: nothing starts on a guess. +export function xJobCapUnreadableSentence(file: string): string { + return ( + `X's job count cannot be read (${file}): no X job starts while it is unreadable, because the cap on X jobs ` + + "is counted there. Repair the file (it is JSON: {version: 2, starts: [times]}), then ask again." + ); +} + +// The sentence for a count that is not on disk and cannot be rebuilt from the +// job records (review 2, ruling R-c): `why` says what is missing; `until`, +// when known, is when no X job on record can still count. +export function xJobCapUnrebuildableSentence(file: string, why: string, until?: number): string { + return ( + `X's job count is not on disk (${file}) and cannot be rebuilt from the job records: ${why}. ` + + "No X job starts while the last day's X jobs cannot be counted" + + (until !== undefined ? ` — at the latest until ${day(until)} ${hhmm(until)} UTC, when none on record can still count` : "") + + ". Restore the job records (the corpus's .jobs directory) and ask again." + ); +} + +// ── 3. what counts ───────────────────────────────────────────────────────── + +// The job as it will run: its kind, its spec's params (jobs/jobSpec.ts — what +// the job's function runs with), and the channel it is for. +export type XJobPlan = { + kind: string; + params?: Readonly<Record<string, unknown>>; + channel?: { library?: boolean; postCaptureThread?: boolean }; +}; + +// DOES THIS X JOB COUNT AGAINST THE CAP? Every X job does — a read, a fetch in +// any mode, an X run's channel, an import, an availability check, a capture +// with its shots — EXCEPT the one job that cannot ask x.com: a trending +// library's capture of MEDIA ONLY, which takes files from X's two media CDN +// hosts by the addresses already in the saved captures, with no cookie, no +// page and no logged-in fallback. Every half that would open a page must be +// off BY NAME in the plan (shots, articles, avatars, context; no thread shot, +// by the plan or the channel's default; no avatars-only or context-only run), +// and it is not a keep capture (`keptMedia`: a post the CDN cannot serve whole +// is then downloaded the logged-in way). A capture that COULD fall back to +// the login counts. A plan that cannot be read counts. +// +// It still runs on X's queue, spaced from the others by X's gap, under X's +// cooldown and the watch's jar rule: only the count is not asked. +export function xJobCounts(plan: XJobPlan): boolean { + // The transcription worker reads a file on disk (review 2 S5). + if (plan.kind === "transcribe-one") return false; + if (plan.kind !== "capture-posts" || plan.channel?.library !== true) return true; + const p = plan.params; + if (!p || typeof p !== "object") return true; + const off = (k: string) => p[k] === false; + if (!(off("shots") && off("articles") && off("avatars") && off("context"))) return true; + if (p.thread === true || (p.thread !== false && plan.channel.postCaptureThread === true)) return true; + if (p.avatarsOnly === true || p.contextOnly === true) return true; + if (p.keptMedia === true) return true; + return p.media === false; +} + +// ── 4. which jobs ask x.com (review 2 S5, review 3 M2/S5/S6) ─────────────── + +// X's clip windows run on X's own queue (lib/queueKeys.ts clipWindowQueueKey); +// the clip queue X once had is X's all the same. +export const X_CLIPS_QUEUE_KEY = "clips:twitter"; + +// Windows cut from saved containers (lib/queueKeys.ts SAVED_VIDEO_CLIP_QUEUE). +const SAVED_VIDEO_CLIP_QUEUE = "clips:saved-video"; + +// IS THIS ADDRESS X'S? x.com and twitter.com and their subdomains, X's short +// links (t.co: X answers and redirects to the post — asking it is asking X; +// review 3 S6), and X's media hosts (twimg.com: video., pbs. and the rest; +// review 4 C). By the HOST alone, lowercased and without a trailing dot: a +// host that merely ends in "twitter.com" (nottwitter.com) or begins with an X +// host (x.com.example.org) is not X's, and neither is a userinfo that reads +// like one (https://x.com@example.org/). An address written without a scheme +// is X's when its first segment is an X host ("x.com/u/status/1"). +const X_HOSTS: ReadonlyArray<string> = ["x.com", "twitter.com", "t.co", "twimg.com"]; + +function hostOf(raw: string): string | null { + const s = raw.trim(); + // A scheme with an authority (https://…); a scheme-relative //host/…; a + // scheme with none (mailto:, javascript:), which names no host; else no + // scheme at all — the first segment is the host (a port after it allowed). + const href = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) + ? s + : s.startsWith("//") + ? `https:${s}` + : /^[a-z][a-z0-9+.-]*:(?!\d)/i.test(s) + ? s + : `https://${s}`; + try { + const host = new URL(href).hostname.toLowerCase().replace(/\.+$/, ""); + return host || null; + } catch { + return null; + } +} + +export function isXUrl(url: unknown): boolean { + if (typeof url !== "string" || !url.trim()) return false; + const host = hostOf(url); + return host !== null && X_HOSTS.some((h) => host === h || host.endsWith(`.${h}`)); +} + +// The network job as queued: its kind, its queue, its channel's platform and +// its spec's params. `itemChannelPlatforms`: for a batch of windows, the +// platform of each item's channel (by slug), read by the caller — an item +// that names no URL is fetched from its channel's page. +export type XAskPlan = { + kind: string; + queueKey: string; + channelPlatform?: string | null; + params?: Readonly<Record<string, unknown>>; + itemChannelPlatforms?: Readonly<Record<string, string | null | undefined>>; +}; + +const isWindowKind = (kind: string) => kind === "fetch-window" || kind === "fetch-windows"; + +// The windows a window job will fetch: each one's page URL (when it names one) +// and its channel. A single window's are its params'. +function windowAsks(plan: XAskPlan): Array<{ url?: string; slug?: string }> { + const p = plan.params; + if (plan.kind === "fetch-windows" && p && Array.isArray(p.items)) { + return (p.items as unknown[]).map((raw) => { + const it = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {}; + const url = typeof it.webpageUrl === "string" && it.webpageUrl.trim() ? it.webpageUrl.trim() : undefined; + const slug = typeof it.slug === "string" ? it.slug : undefined; + return { ...(url ? { url } : {}), ...(slug ? { slug } : {}) }; + }); + } + const url = typeof p?.webpageUrl === "string" && p.webpageUrl.trim() ? p.webpageUrl.trim() : undefined; + // No plan to read: one window of the job's channel. + return [url ? { url } : {}]; +} + +// DOES THIS NETWORK JOB ASK x.com? It does on X's queue (or X's old clip +// queue), whatever its kind. Then: +// import-one asks its URL's host (isXUrl: x.com, twitter.com, t.co, twimg.com); +// fetch-window(s) ask the URLs of their windows (review 3 M2), ON ANY +// CHANNEL: an x.com page is X's wherever it is filed. A +// window that names no URL is fetched from its +// channel's page, so its CHANNEL decides — "no URL" +// never passes by itself (S5). On `clips:saved-video` +// they ask nothing: windows cut from the saved copy on +// disk — and the controller never goes to the network +// for an X source from that queue (M1, +// controller/fetchWindows.ts); +// fetch-copies archive.org (its controller refuses an X address); +// transcribe-one the transcription worker, over a file on disk; +// import-media asks its page's address when it names one +// (`params.url`, isXUrl — review 4 B), on any channel +// and queue; with none, on its own queue +// (`import-media:<slug>`), a local file; +// import-archive-org archive.org. +// Everything else an X channel queues asks X, and is refused off X's queue. +export function xJobAsksX(plan: XAskPlan): boolean { + if (plan.queueKey === X_QUEUE_KEY || plan.queueKey === X_CLIPS_QUEUE_KEY) return true; + if (plan.kind === "import-one" && typeof plan.params?.url === "string") return isXUrl(plan.params.url); + if (plan.kind === "transcribe-one") return false; + if (plan.kind === "import-media" && typeof plan.params?.url === "string" && plan.params.url.trim()) return isXUrl(plan.params.url); + if (isWindowKind(plan.kind)) { + if (plan.queueKey === SAVED_VIDEO_CLIP_QUEUE) return false; + return windowAsks(plan).some((w) => { + if (w.url) return isXUrl(w.url); + const platform = w.slug !== undefined && plan.itemChannelPlatforms && Object.hasOwn(plan.itemChannelPlatforms, w.slug) + ? plan.itemChannelPlatforms[w.slug] + : plan.channelPlatform; + return platform === "twitter"; + }); + } + if (plan.channelPlatform !== "twitter") return false; + if (plan.kind === "fetch-copies") return false; + if (plan.kind === "import-media" && plan.queueKey.startsWith("import-media:")) return false; + if (plan.kind === "import-archive-org") return false; + return true; +} diff --git a/common/lib/xTrending/config.test.ts b/common/lib/xTrending/config.test.ts @@ -39,7 +39,7 @@ test("a trending page URL is its id; anything else is refused", () => { test("the marker is an object; its caps are kept only in range", () => { assert.deepEqual(coerceXTrendingConfig({}), {}); assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 4, maxPosts: 30, other: 1 }), { maxScrolls: 4, maxPosts: 30 }); - assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 21, maxPosts: 0 }), {}); + assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 41, maxPosts: 0 }), {}); assert.deepEqual(coerceXTrendingConfig({ maxScrolls: 2.5, maxPosts: "9" }), {}); for (const bad of [undefined, null, true, "yes", 1, []]) assert.equal(coerceXTrendingConfig(bad), undefined); }); @@ -65,17 +65,17 @@ test("a library is a channel carrying the marker — the marker alone — and it assert.equal(isXTrendingChannel(null), false); }); -test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; out of range is refused", () => { - assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 8, posts: 60 } }); - assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 60 } }); +test("a read's caps: the ask, else the channel's, else 20 scrolls and 200 posts; out of range is refused", () => { + assert.deepEqual(xTrendingLimits(undefined), { ok: true, limits: { scrolls: 20, posts: 200 } }); + assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }), { ok: true, limits: { scrolls: 3, posts: 200 } }); assert.deepEqual(xTrendingLimits({ maxScrolls: 3 }, { scrolls: 20, posts: 200 }), { ok: true, limits: { scrolls: 20, posts: 200 }, }); - assert.deepEqual(xTrendingLimits({}, { scrolls: 21 }), { ok: false, error: '"scrolls" is a whole number, 1–20' }); - assert.deepEqual(xTrendingLimits({}, { posts: 201 }), { ok: false, error: '"posts" is a whole number, 1–200' }); - assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–200' }); - assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–20' }); + assert.deepEqual(xTrendingLimits({}, { scrolls: 41 }), { ok: false, error: '"scrolls" is a whole number, 1–40' }); + assert.deepEqual(xTrendingLimits({}, { posts: 401 }), { ok: false, error: '"posts" is a whole number, 1–400' }); + assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–400' }); + assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–40' }); }); test("the per-file media cap: 100 MB unless the library says otherwise, kept only in range", () => { diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts @@ -55,10 +55,10 @@ export function xRateLimitHoldSentence(what: string, remainingMs: number, now: n ); } -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_SCROLLS = 20; +export const X_TRENDING_MAX_SCROLLS = 40; +export const X_TRENDING_DEFAULT_POSTS = 200; +export const X_TRENDING_MAX_POSTS = 400; 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 diff --git a/common/lib/xTrending/organise.ts b/common/lib/xTrending/organise.ts @@ -123,6 +123,9 @@ export async function renameXTrendingTopic( } topic.title = title; topic.organised = { what: "rename", by: ask.by, at }; + // Its own field: a merge into this topic overwrites `organised`, and a + // read must still know the name was set. + topic.titleFrom = "rename"; return { write: true, result: { ok: true, op: "rename", topic: topic.id, title, was, changed: true, sentence: `Topic "${was}" is now "${title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }, @@ -198,7 +201,7 @@ export async function moveXTrendingPosts( const base = topicIdFromTitle(title) || "topic"; let id = base; for (let k = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); k++) id = `${base}-${k}`; - target = { id, title, createdAt: at, sources: [] }; + target = { id, title, createdAt: at, sources: [], titleFrom: "ask" }; topics.push(target); created = true; // THE TOPIC FIRST, THEN THE POSTS (review 1 S6): cut between the two diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -513,3 +513,442 @@ test("a library in one line: its topics, its posts and how many are undecided", assert.deepEqual(await summarizeXTrending(await judgeLibrary("judge-summary")), { topics: 2, posts: 5, unjudged: 1 }); assert.deepEqual(await summarizeXTrending(root("judge-summary-empty")), { topics: 0, posts: 0, unjudged: 0 }); }); + +// ── lane x-followups: the page's own words, the topic's name, the tab ────── + +const PAGE = { + title: "Kettle festival opens", + summary: "The annual kettle festival opened this morning.", + lastUpdatedAt: "2026-11-16T11:30:00.000Z", + tabs: [ + { label: "Top", timelineId: "tl-top" }, + { label: "Latest", timelineId: "tl-latest" }, + ], +}; + +test("a topic nobody named is born with the page's title; the source keeps X's title, summary, last update and tabs; the listing says them", async () => { + const dir = root("page-born"); + const made = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); + // The id stays the page's: a name can change, an id cannot. + assert.deepEqual(made.topic, { id: `t-${REF.trendId}`, title: "Kettle festival opens", created: true }); + const [topic] = await readXTrendingTopics(dir); + assert.deepEqual(topic.sources, [ + { trendId: REF.trendId, url: REF.url, ...PAGE, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1, tab: "Top" }] }, + ]); + assert.deepEqual((await readXTrendingMembership(dir))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z", rank: 1, tab: "Top" }]); + const listing = await listXTrending(dir); + assert.deepEqual(listing.topics[0].sources, [ + { trendId: REF.trendId, url: REF.url, title: PAGE.title, summary: PAGE.summary, lastUpdatedAt: PAGE.lastUpdatedAt, tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + ]); + // No page in the capture: the fallback name, as before, and nothing invented on the source. + const bare = root("page-none"); + assert.equal((await recordXTrendingRead(bare, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 })).topic.title, `Trending ${REF.trendId}`); + assert.deepEqual((await readXTrendingTopics(bare))[0].sources[0], { trendId: REF.trendId, url: REF.url, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1 }] }); + // A title of several lines, or longer than a topic's name may be, is one line and cut; the source keeps X's whole title. + const long = root("page-long"); + const title = `Kettle\n festival ${"x".repeat(200)}`; + const cut = await recordXTrendingRead(long, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title } }); + assert.equal(cut.topic.title.length, 120); + assert.match(cut.topic.title, /^Kettle festival x+…$/); + assert.equal(topicTitleProblem(cut.topic.title), null); + assert.equal((await readXTrendingTopics(long))[0].sources[0].title, `Kettle festival ${"x".repeat(200)}`); +}); + +test("a topic still carrying the fallback name takes the page's title on a later pass; a topic somebody named never does", async () => { + const { renameXTrendingTopic } = await import("./organise"); + const IDLE = () => false; + const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; + const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE, tab: "Top" }; + const fallback = `Trending ${REF.trendId}`; + + // Made before titles were read: the next read names it — and the SAME read parsed again (a reparse) does too. + const dir = root("name-fallback"); + await recordXTrendingRead(dir, first); + const read = await recordXTrendingRead(dir, later); + assert.deepEqual(read.topic, { id: `t-${REF.trendId}`, title: PAGE.title, created: false, renamed: { was: fallback } }); + // Once named so, a later pass renames nothing (and says nothing). + assert.equal((await recordXTrendingRead(dir, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z", page: { ...PAGE, title: "Another headline" } })).topic.renamed, undefined); + assert.equal((await readXTrendingTopics(dir))[0].title, PAGE.title); + // …while the SOURCE follows X's words. + assert.equal((await readXTrendingTopics(dir))[0].sources[0].title, "Another headline"); + const reparsed = root("name-reparse"); + await recordXTrendingRead(reparsed, first); + const again = await recordXTrendingRead(reparsed, { ...first, added: 0, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); + assert.deepEqual(again.topic.renamed, { was: fallback }); + assert.equal((await readXTrendingTopics(reparsed))[0].sources[0].reads[0].tab, "Top"); + // The reparse fills the tab its sighting could not say before, and adds no second sighting. + assert.deepEqual((await readXTrendingMembership(reparsed))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: first.at, rank: 1, tab: "Top" }]); + + // A name asked for at the read stays. + const asked = root("name-asked"); + await recordXTrendingRead(asked, { ...first, topic: "Kettles" }); + assert.equal((await recordXTrendingRead(asked, later)).topic.title, "Kettles"); + + // Renamed by an agent or by the operator: never renamed by a read — even renamed back to the fallback's own words. + for (const by of ["agent", "operator"] as const) { + const named = root(`name-renamed-${by}`); + await recordXTrendingRead(named, first); + assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: "My kettles", by, readInFlight: IDLE })).ok, true); + assert.equal((await recordXTrendingRead(named, later)).topic.title, "My kettles"); + assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: fallback, by, readInFlight: IDLE })).ok, true); + const kept = await recordXTrendingRead(named, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(kept.topic.title, fallback); + assert.equal(kept.topic.renamed, undefined); + // X's title is on the source all the same. + assert.equal((await readXTrendingTopics(named))[0].sources[0].title, PAGE.title); + } + + // The fallback of ANOTHER page is somebody's choice of words here: a second page read into the topic does not rename it. + const other = root("name-other-page"); + await recordXTrendingRead(other, first); + assert.equal((await recordXTrendingRead(other, { ...later, ref: REF_2, topic: `t-${REF.trendId}` })).topic.title, fallback); + + // A title another topic already answers to is not taken: a topic's name is its own. + const taken = root("name-taken"); + await recordXTrendingRead(taken, { ...first, ref: REF_2, topic: "kettle FESTIVAL opens" }); + await recordXTrendingRead(taken, { ...first, readId: READ_B }); + const refused = await recordXTrendingRead(taken, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); + assert.equal(refused.topic.title, fallback); + assert.equal(refused.topic.renamed, undefined); + assert.equal((await readXTrendingTopics(taken)).find((t) => t.id === `t-${REF.trendId}`)?.sources[0].title, PAGE.title); + // …and a NEW topic is not born with a name another answers to either. + const born = root("name-born-taken"); + await recordXTrendingRead(born, { ...first, ref: REF_2, topic: PAGE.title }); + assert.equal((await recordXTrendingRead(born, { ...later })).topic.title, fallback); +}); + +test("an older read parsed again does not put its words over a newer read's", async () => { + const dir = root("page-order"); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 1, page: { title: "Morning headline", summary: "Morning." } }); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Noon headline", summary: "Noon." } }); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." }, tab: "Top" }); + const source = (await readXTrendingTopics(dir))[0].sources[0]; + assert.equal(source.title, "Noon headline"); + assert.equal(source.summary, "Noon."); + // The read's own tab is the read's, whenever it is learned. + assert.equal(source.reads[0].tab, "Top"); +}); + +test("gone from the page is said per tab: a post only the other tab showed is not missing from this one", async () => { + const dir = root("gone-tabs"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + // 701 and 702 on Top; 703 on Latest only; 704 by a read from before tabs were read. + await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["704"], added: 1 }); + await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", postIds: ["701", "702"], added: 2, tab: "Top" }); + await recordXTrendingRead(dir, { readId: READ_C, at: at(11), ref: REF, topic: "T", postIds: ["703"], added: 1, tab: "Latest" }); + // A complete read of Top that shows 701 only: 702 is gone (Top showed it), 704 too (untagged: the opening tab's), 703 is not. + const top = await recordXTrendingRead(dir, { readId: "tr-01JD0000000000000000000000", at: at(12), ref: REF, topic: "T", postIds: ["701"], added: 0, tab: "Top", complete: true }); + assert.deepEqual([...top.gone].sort(), ["702", "704"]); + const members = await readXTrendingMembership(dir); + assert.equal(members["703"].gone, undefined); + // The listing says which tab showed a post. + await writeXTrendingPosts(dir, ["701", "702", "703", "704"].map((id) => post(id, "a", `post ${id}`))); + const listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "703")?.reads, [{ read: READ_C, trendId: REF.trendId, at: at(11), tab: "Latest" }]); + assert.deepEqual(listing.posts.find((p) => p.id === "704")?.reads, [{ read: READ_A, trendId: REF.trendId, at: at(9) }]); + assert.equal(listing.topics[0].sources[0].lastReadTab, "Top"); + // A complete read that cannot say its tab judges only sightings that name none: 703, seen on Latest, is not its to judge. + const unknown = await recordXTrendingRead(dir, { readId: "tr-01JE0000000000000000000000", at: at(13), ref: REF, topic: "T", postIds: ["701"], added: 0, complete: true }); + assert.deepEqual(unknown.gone, []); + assert.equal((await readXTrendingMembership(dir))["703"].gone, undefined); +}); + +// ── review 1: S4 and the set-name field ──────────────────────────────────── + +test("S4: an older read parsed again never names a topic by a title older than the one its source holds", async () => { + const { renameXTrendingTopic } = await import("./organise"); + const dir = root("s4-age"); + const fallback = `Trending ${REF.trendId}`; + // Another topic answers to the noon title, so the page's topic keeps its fallback at the noon read… + await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T08:00:00.000Z", ref: REF_2, topic: "Noon headline", postIds: ["201"], added: 1 }); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }); + const noon = await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Noon headline" } }); + assert.equal(noon.topic.title, fallback); + // …then that other topic is renamed away, and the MORNING read is parsed again: its title is older than the source's. + assert.equal((await renameXTrendingTopic(dir, { topic: "noon-headline", title: "Something else", by: "operator", readInFlight: () => false })).ok, true); + const morning = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." } }); + assert.deepEqual(morning.topic.renamed, { was: fallback }); + assert.equal(morning.topic.title, "Noon headline"); + const topic = (await readXTrendingTopics(dir)).find((t) => t.id === `t-${REF.trendId}`)!; + assert.equal(topic.title, "Noon headline"); + assert.equal(topic.titleFrom, "page"); + assert.equal(topic.sources[0].title, "Noon headline"); + // What the source did not have yet is taken even from the older read: there is nothing newer to keep. + assert.equal(topic.sources[0].summary, "Morning."); +}); + +test("a name that was SET is recorded in a field no merge or move writes, and a read never changes it afterwards", async () => { + const { mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } = await import("./organise"); + const { xTrendingTitleFrom, xTrendingTopicNameIsSet } = await import("./store"); + const IDLE = () => false; + const fallback = `Trending ${REF.trendId}`; + const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; + const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE }; + const topicOf = async (dir: string, id = `t-${REF.trendId}`) => (await readXTrendingTopics(dir)).find((t) => t.id === id)!; + + // A name ASKED FOR that is literally the fallback's words is a set name. + const asked = root("set-asked-fallback"); + const made = await recordXTrendingRead(asked, { ...first, topic: fallback }); + assert.equal((await topicOf(asked, made.topic.id)).titleFrom, "ask"); + assert.equal((await recordXTrendingRead(asked, { ...later, topic: made.topic.id })).topic.title, fallback); + + // Renamed, then MERGED INTO (which overwrites `organised`): still a set name. + const merged = root("set-rename-then-merge"); + await recordXTrendingRead(merged, first); + await recordXTrendingRead(merged, { readId: READ_C, at: "2026-11-17T09:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["201"], added: 1 }); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback + " ", by: "agent", readInFlight: IDLE })).ok, true); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: "Kettles", by: "agent", readInFlight: IDLE })).ok, true); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback, by: "agent", readInFlight: IDLE })).ok, true); + const m = await mergeXTrendingTopics(merged, { into: `t-${REF.trendId}`, from: ["cups"], by: "operator", readInFlight: IDLE }); + assert.equal(m.ok, true, m.ok ? "" : m.error); + const after = await topicOf(merged); + assert.equal(after.organised?.what, "merge"); + assert.equal(after.titleFrom, "rename"); + assert.equal(xTrendingTopicNameIsSet(after), true); + assert.equal((await recordXTrendingRead(merged, later)).topic.title, fallback); + + // A topic made by a move, under the name given, is a set name too. + const moved = root("set-move"); + await recordXTrendingRead(moved, first); + const mv = await moveXTrendingPosts(moved, { ids: ["101"], to: "Picked", create: true, by: "agent" }); + assert.equal(mv.ok, true, mv.ok ? "" : mv.error); + assert.equal((await readXTrendingTopics(moved)).find((t) => t.title === "Picked")?.titleFrom, "ask"); + + // A topic that took its page's title says so, and is not "set". + const page = root("set-page"); + await recordXTrendingRead(page, { ...first, page: PAGE }); + assert.equal((await topicOf(page)).titleFrom, "page"); + assert.equal(xTrendingTopicNameIsSet(await topicOf(page)), false); + // Topics from before the field: a rename as the last organise step, a name that is no fallback (asked), a fallback. + const legacy = (title: string, organised?: { what: "rename" | "merge"; by: "agent"; at: string }) => ({ title, sources: [{ trendId: REF.trendId, url: REF.url, reads: [] }], ...(organised ? { organised } : {}) }); + assert.equal(xTrendingTitleFrom(legacy("Kettles")), "ask"); + assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "rename", by: "agent", at: "x" })), "rename"); + assert.equal(xTrendingTitleFrom(legacy(fallback)), undefined); + assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "merge", by: "agent", at: "x" })), undefined); +}); + +test("a listing gives at most 600 characters of X's summary, cut at a word; the source keeps all of it", async () => { + const { listedXTrendingSummary, X_TRENDING_SUMMARY_LIST_MAX } = await import("./store"); + assert.equal(X_TRENDING_SUMMARY_LIST_MAX, 600); + const dir = root("summary-cap"); + const summary = Array.from({ length: 150 }, (_, i) => `word${i}`).join(" "); + assert.ok(summary.length > 900); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title: "T", summary } }); + assert.equal((await readXTrendingTopics(dir))[0].sources[0].summary, summary); + const listed = (await listXTrending(dir)).topics[0].sources[0].summary!; + assert.ok(listed.length <= 600, String(listed.length)); + assert.match(listed, /^word0 word1 .* word\d+…$/); + assert.ok(summary.startsWith(listed.slice(0, -1))); + // A short one is given whole; one unbroken run is cut hard. + assert.equal(listedXTrendingSummary("Short."), "Short."); + assert.equal(listedXTrendingSummary("x".repeat(700)).length, 600); +}); + +// ── added scope R3: one read, two tabs ───────────────────────────────────── + +test("R3: a read of two tabs records each tab's sightings and ranks; gone is said tab by tab, and of the page once every tab that showed the post has stopped", async () => { + const dir = root("two-tabs"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + const id = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; + const read = (n: number, top: string[], latest: string[], complete: { top?: boolean; latest?: boolean } = { top: true, latest: true }, page = true) => + recordXTrendingRead(dir, { + readId: id(n), + at: at(8 + n), + ref: REF, + topic: "T", + postIds: [...new Set([...top, ...latest])], + added: 0, + ...(page ? { page: PAGE } : {}), + tabReads: [ + // Named by the capture's page answer, or only by the timeline id the requests carried. + { ...(page ? { tab: "Top" } : {}), timelineId: "tl-top", postIds: top, ...(complete.top ? { complete: true } : {}) }, + { ...(page ? { tab: "Latest" } : {}), timelineId: "tl-latest", postIds: latest, ...(complete.latest ? { complete: true } : {}) }, + ], + }); + await writeXTrendingPosts(dir, ["901", "902", "903", "904"].map((p) => post(p, "a", `post ${p}`))); + // Read 1: 901 and 902 on both tabs, 903 on Top only, 904 on Latest only. + const first = await read(1, ["901", "902", "903"], ["904", "902", "901"]); + assert.deepEqual(first.tabs, ["Top", "Latest"]); + assert.deepEqual([first.placed, first.kept, first.gone], [4, 0, []]); + let members = await readXTrendingMembership(dir); + assert.deepEqual(members["902"].seen, [ + { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Top" }, + { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Latest" }, + ]); + assert.deepEqual(members["904"].seen.map((s) => [s.tab, s.rank]), [["Latest", 1]]); + assert.deepEqual((await readXTrendingTopics(dir))[0].sources[0].reads[0].tabs, ["Top", "Latest"]); + assert.deepEqual((await listXTrending(dir)).topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); + + // Read 2: Latest no longer shows 902 (Top still does) nor 904 (which only Latest showed). + const second = await read(2, ["901", "902", "903"], ["901"]); + assert.deepEqual(second.gone, ["904"]); + assert.deepEqual(second.goneFromTab, [{ id: "902", tab: "Latest" }]); + members = await readXTrendingMembership(dir); + assert.equal(members["902"].gone, undefined); + assert.deepEqual(Object.keys(members["902"].goneTabs ?? {}), ["Latest"]); + assert.deepEqual(members["904"].gone, { at: at(10), read: id(2), trendId: REF.trendId }); + let listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs, [{ tab: "Latest", at: at(10), read: id(2) }]); + assert.equal(listing.posts.find((p) => p.id === "902")?.gone, undefined); + // Gone from the page says it all: no per-tab line beside it. + assert.equal(listing.posts.find((p) => p.id === "904")?.goneTabs, undefined); + assert.ok(listing.posts.find((p) => p.id === "904")?.gone); + + // Read 3: Top was capped (not read to its end), Latest to its end again: nothing new is said of Top's posts. + const third = await read(3, ["901"], ["901"], { latest: true }); + assert.deepEqual([third.gone, third.goneFromTab], [[], undefined]); + // Read 4: Top to its end without 902: now gone from every tab that showed it — gone from the page. 903 too (Top only). + const fourth = await read(4, ["901"], ["901"]); + assert.deepEqual([...fourth.gone].sort(), ["902", "903"]); + // Read 5 names no tab in its capture (no page answer): the source's known tabs name them by timeline id. 902 is back on Latest. + const fifth = await read(5, ["901"], ["901", "902"], { top: true, latest: true }, false); + assert.deepEqual(fifth.tabs, ["Top", "Latest"]); + assert.deepEqual(fifth.back, ["902"]); + members = await readXTrendingMembership(dir); + assert.equal(members["902"].gone, undefined); + assert.deepEqual(members["902"].wasGone, [{ from: at(12), to: at(13) }]); + // Still gone from Top, shown again by Latest: said so. + listing = await listXTrending(dir); + assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs?.map((g) => g.tab), ["Top"]); + assert.equal(members["902"].seen.at(-1)?.tab, "Latest"); +}); + +// ── review 2 (lane x-followups): M2 and ruling R-d ───────────────────────── + +test("M2: a post seen only by reads from before tabs is not marked gone by a complete Latest read while Top stopped at its cap", async () => { + const dir = root("m2-untagged"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + await writeXTrendingPosts(dir, ["601", "602"].map((p) => post(p, "a", `post ${p}`))); + // A read from before tabs were read: its sightings name no tab (the page opened on Top). + await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["601", "602"], added: 2 }); + // A two-tab read: Top stopped at its post cap (it shows 602 only), Latest read to its end, and neither shows 601. + const twoTabs = (readId: string, h: number, topComplete: boolean) => + recordXTrendingRead(dir, { + readId, + at: at(h), + ref: REF, + topic: "T", + page: PAGE, + postIds: ["602"], + added: 0, + tabReads: [ + { tab: "Top", timelineId: "tl-top", postIds: ["602"], ...(topComplete ? { complete: true } : {}) }, + { tab: "Latest", timelineId: "tl-latest", postIds: [], complete: true }, + ], + }); + const capped = await twoTabs(READ_B, 10, false); + assert.deepEqual([capped.gone, capped.goneFromTab], [[], undefined]); + let members = await readXTrendingMembership(dir); + assert.equal(members["601"].gone, undefined); + assert.equal(members["601"].goneTabs, undefined, "Latest never showed it: it is not Latest's to judge"); + // Only a complete read of the tab the page opens on judges it: then it is gone from Top, which was the only tab that showed it. + const READ_D = "tr-01JD0000000000000000000000"; + const complete = await twoTabs(READ_D, 11, true); + assert.deepEqual(complete.gone, ["601"]); + members = await readXTrendingMembership(dir); + assert.deepEqual(Object.keys(members["601"].goneTabs ?? {}), ["Top"]); + assert.deepEqual(members["601"].gone, { at: at(11), read: READ_D, trendId: REF.trendId }); +}); + +test("M2: a read that cannot name its tab still judges sightings that name none; a named read of another tab never does", async () => { + const dir = root("m2-unnamed"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["611", "612"], added: 2 }); + // Latest, named, read to its end: not its to judge. + const latest = await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", postIds: ["612"], added: 0, tab: "Latest", complete: true }); + assert.deepEqual(latest.gone, []); + // An unnamed complete read: it is. + const unnamed = await recordXTrendingRead(dir, { readId: READ_C, at: at(11), ref: REF, topic: "T", postIds: ["612"], added: 0, complete: true }); + assert.deepEqual(unnamed.gone, ["611"]); +}); + +test("R-d: gone from the PAGE needs every tab that showed the post to drop it IN THE SAME READ; marks from different reads stay per tab", async () => { + const dir = root("rd-same-read"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + const id = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; + const read = (n: number, top: string[], latest: string[], complete: { top?: boolean; latest?: boolean }) => + recordXTrendingRead(dir, { + readId: id(n), + at: at(8 + n), + ref: REF, + topic: "T", + page: PAGE, + postIds: [...new Set([...top, ...latest])], + added: 0, + tabReads: [ + { tab: "Top", timelineId: "tl-top", postIds: top, ...(complete.top ? { complete: true } : {}) }, + { tab: "Latest", timelineId: "tl-latest", postIds: latest, ...(complete.latest ? { complete: true } : {}) }, + ], + }); + await writeXTrendingPosts(dir, ["621", "622"].map((p) => post(p, "a", `post ${p}`))); + // Read 1: both tabs show 621 and 622. + await read(1, ["621", "622"], ["621", "622"], { top: true, latest: true }); + // Read 2: Latest to its end without 621; Top capped (it showed 622 only). + const second = await read(2, ["622"], ["622"], { latest: true }); + assert.deepEqual([second.gone, second.goneFromTab], [[], [{ id: "621", tab: "Latest" }]]); + // Read 3: Top to its end without 621; Latest capped. Gone from Top now, and from Latest since read 2 — two reads: not gone from the page. + const third = await read(3, ["622"], ["622"], { top: true }); + assert.deepEqual([third.gone, third.goneFromTab], [[], [{ id: "621", tab: "Top" }]]); + let members = await readXTrendingMembership(dir); + assert.equal(members["621"].gone, undefined); + assert.deepEqual(Object.keys(members["621"].goneTabs ?? {}).sort(), ["Latest", "Top"]); + assert.deepEqual(members["621"].goneTabs?.Latest?.read, id(2)); + assert.deepEqual(members["621"].goneTabs?.Top?.read, id(3)); + // The listing says each tab, with its own time — never "gone from the page". + const listing = await listXTrending(dir); + assert.equal(listing.posts.find((p) => p.id === "621")?.gone, undefined); + assert.deepEqual(listing.posts.find((p) => p.id === "621")?.goneTabs?.map((g) => [g.tab, g.read]), [["Latest", id(2)], ["Top", id(3)]]); + // Read 4: both tabs to their end, neither shows 621: gone from the page, by this read. + const fourth = await read(4, ["622"], ["622"], { top: true, latest: true }); + assert.deepEqual(fourth.gone, ["621"]); + members = await readXTrendingMembership(dir); + assert.deepEqual(members["621"].gone, { at: at(12), read: id(4), trendId: REF.trendId }); + // A post one tab still shows in the same read is never gone from the page, whatever the other tab says. + const fifth = await read(5, ["622"], [], { top: true, latest: true }); + assert.deepEqual([fifth.gone, fifth.goneFromTab], [[], [{ id: "622", tab: "Latest" }]]); +}); + +test("review 3 S7: the opening tab is the one named Top, wherever the page's answer lists it; else the first", async () => { + const dir = root("s7-opening"); + const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; + await writeXTrendingPosts(dir, ["621", "622"].map((p) => post(p, "a", `post ${p}`))); + // A read from before tabs: its sightings name none (the page opened on Top). + await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["621", "622"], added: 2 }); + // The page's answer lists Latest FIRST. Top stopped at its cap; Latest read to its end; neither shows 621. + const latestFirst = { ...PAGE, tabs: [PAGE.tabs[1], PAGE.tabs[0]] }; + const r = await recordXTrendingRead(dir, { + readId: READ_B, + at: at(10), + ref: REF, + topic: "T", + page: latestFirst, + postIds: ["622"], + added: 0, + tabReads: [ + { tab: "Top", timelineId: "tl-top", postIds: ["622"] }, + { tab: "Latest", timelineId: "tl-latest", postIds: [], complete: true }, + ], + }); + assert.deepEqual(r.gone, [], "Latest is not the opening tab because it is listed first"); + const members = await readXTrendingMembership(dir); + assert.equal(members["621"].goneTabs, undefined); + // A page whose tabs name no Top: its first tab opens. + const dir2 = root("s7-first"); + await writeXTrendingPosts(dir2, ["631", "632"].map((p) => post(p, "a", `post ${p}`))); + await recordXTrendingRead(dir2, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["631", "632"], added: 2 }); + const other = { ...PAGE, tabs: [{ label: "For you", timelineId: "tl-a" }, { label: "Newest", timelineId: "tl-b" }] }; + const r2 = await recordXTrendingRead(dir2, { + readId: READ_B, + at: at(10), + ref: REF, + topic: "T", + page: other, + postIds: ["632"], + added: 0, + tabReads: [ + { tab: "For you", timelineId: "tl-a", postIds: ["632"], complete: true }, + { tab: "Newest", timelineId: "tl-b", postIds: [] }, + ], + }); + assert.deepEqual(r2.gone, ["631"]); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -57,6 +57,8 @@ export const TRENDING_DIRNAME = "trending"; export const TRENDING_READS_DIRNAME = "reads"; export const TRENDING_RESPONSES_FILENAME = "responses.jsonl"; export const TRENDING_PAGE_SHOT_FILENAME = "page.png"; +// The page after the read pressed its second tab (or tried to). +export const TRENDING_TAB_SHOT_FILENAME = "page-latest.png"; export const TRENDING_READ_FILENAME = "read.json"; export function trendingDir(channelRoot: string): string { @@ -312,18 +314,40 @@ export type XTrendingSourceRead = { at: string; posts: number; added: number; + // The tab of the page whose timeline the read saw (its label, as X shows + // it), when the capture says which. A read sees ONE tab: the one the page + // opens on. Absent for a read saved before tabs were read, until it is + // parsed again, and for a capture whose page answer or timeline id is missing. + tab?: string; + // A read that covered several tabs (Top, then Latest): their labels. + tabs?: string[]; }; +// One tab of a trending page: its label and the timeline it lists. +export type XTrendingTab = { label: string; timelineId: string }; + // One trending page read into a topic. `title` and `summary` are X's own -// words for the page, filled once the parser knows where the page keeps them. +// words for the page, `lastUpdatedAt` when X last rewrote them and `tabs` the +// page's tabs (lane x-followups): all as the LATEST read or reparse that +// carried the page's own answer found them, and kept when a later capture +// lacks it. export type XTrendingSource = { trendId: string; url: string; title?: string; summary?: string; + lastUpdatedAt?: string; + tabs?: XTrendingTab[]; reads: XTrendingSourceRead[]; }; +// THE NAME A TOPIC IS BORN WITH when nobody named it and its page gave no +// title: "Trending <the page's number>". A topic still carrying it takes the +// page's title at the next read or reparse that finds one (recordXTrendingRead). +export function xTrendingFallbackTitle(trendId: string): string { + return `Trending ${trendId}`; +} + // Who organised (renamed, merged, moved) and when: the caller's word, as a // judgement's `by` is (lib/xTrending/organise.ts). export type XTrendingOrganiseBy = "agent" | "operator"; @@ -341,9 +365,36 @@ export type XTrendingTopic = { aliases?: string[]; // Its last rename or merge. organised?: XTrendingOrganised; + // WHERE ITS NAME CAME FROM, in a field of its own that no merge or move + // writes (review 1): "ask" — a read was asked to make it under that name; + // "rename" — somebody renamed it; "page" — nobody named it and it took its + // trending page's title. Absent: the fallback name, or a topic from before + // this field (xTrendingTitleFrom reads those). A name that was SET ("ask", + // "rename") is never changed by a read. + titleFrom?: XTrendingTitleFrom; }; -export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number }; +export type XTrendingTitleFrom = "page" | "ask" | "rename"; + +// Whether somebody set the topic's name. A topic from before `titleFrom`: a +// rename is its last organise step, or its name is not a fallback name (it was +// asked for: no read gave a topic a page's title then). +export function xTrendingTopicNameIsSet(t: Pick<XTrendingTopic, "title" | "titleFrom" | "organised" | "sources">): boolean { + const from = xTrendingTitleFrom(t); + return from === "ask" || from === "rename"; +} + +// Where a topic's name came from; undefined for the fallback name. +export function xTrendingTitleFrom(t: Pick<XTrendingTopic, "title" | "titleFrom" | "organised" | "sources">): XTrendingTitleFrom | undefined { + if (t.titleFrom) return t.titleFrom; + if (t.organised?.what === "rename") return "rename"; + if (/^Trending \d+$/.test(t.title) && (t.sources.length === 0 || t.sources.some((s) => t.title === xTrendingFallbackTitle(s.trendId)))) return undefined; + return "ask"; +} + +// One sighting: the read, the page, when, its rank on the page, and the tab +// of the page that showed it (as XTrendingSourceRead.tab). +export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number; tab?: string }; // 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 @@ -359,6 +410,13 @@ export type XTrendingMember = { seen: XTrendingSeen[]; media?: XTrendingMedia; gone?: XTrendingGone; + // GONE FROM ONE TAB (lane x-followups): per tab label ("" for a read that + // could not say its tab), the read of that tab that reached its end and did + // not show the post. `gone` above is set only when ONE read dropped the + // post from every tab that showed it (review 2, ruling R-d); marks here from + // different reads never add up to it. A mark alone means "gone from that + // tab at <time>". + goneTabs?: Record<string, XTrendingGone>; // Earlier absences that ended: gone from `from`, shown again at `to`. wasGone?: Array<{ from: string; to: string }>; // Its last move between topics (lib/xTrending/organise.ts): the topic it @@ -383,13 +441,20 @@ function parseTopics(raw: unknown): XTrendingTopic[] { const reads: XTrendingSourceRead[] = []; for (const r of Array.isArray(s.reads) ? s.reads : []) { if (!r || typeof r !== "object" || !isXTrendingReadId(r.id) || !str(r.at)) continue; - reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0 }); + const readTabs = (Array.isArray(r.tabs) ? r.tabs : []).filter((x: unknown): x is string => str(x)); + reads.push({ id: r.id, at: r.at, posts: Number(r.posts) || 0, added: Number(r.added) || 0, ...(str(r.tab) ? { tab: r.tab } : {}), ...(readTabs.length > 1 ? { tabs: readTabs } : {}) }); + } + const tabs: XTrendingTab[] = []; + for (const tab of Array.isArray(s.tabs) ? s.tabs : []) { + if (tab && typeof tab === "object" && str(tab.label) && str(tab.timelineId)) tabs.push({ label: tab.label, timelineId: tab.timelineId }); } sources.push({ trendId: s.trendId, url: s.url, ...(str(s.title) ? { title: s.title } : {}), ...(str(s.summary) ? { summary: s.summary } : {}), + ...(str(s.lastUpdatedAt) ? { lastUpdatedAt: s.lastUpdatedAt } : {}), + ...(tabs.length ? { tabs } : {}), reads, }); } @@ -406,6 +471,7 @@ function parseTopics(raw: unknown): XTrendingTopic[] { sources, ...(aliases.length ? { aliases: [...new Set<string>(aliases)] } : {}), ...(organised ? { organised } : {}), + ...(t.titleFrom === "page" || t.titleFrom === "ask" || t.titleFrom === "rename" ? { titleFrom: t.titleFrom } : {}), }); } return out; @@ -422,7 +488,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { const seen: XTrendingSeen[] = []; for (const s of Array.isArray(m.seen) ? m.seen : []) { if (!s || typeof s !== "object" || !isXTrendingReadId(s.read) || !str(s.trendId) || !str(s.at)) continue; - seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0 }); + seen.push({ read: s.read, trendId: s.trendId, at: s.at, rank: Number(s.rank) || 0, ...(str(s.tab) ? { tab: s.tab } : {}) }); } const media = m.media && typeof m.media === "object" && Number(m.media.count) > 0 @@ -435,6 +501,14 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { : undefined; 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 goneTabs: Record<string, XTrendingGone> = {}; + if (m.goneTabs && typeof m.goneTabs === "object" && !Array.isArray(m.goneTabs)) { + for (const [tab, mark] of Object.entries(m.goneTabs as Record<string, Partial<XTrendingGone> | null>)) { + if (mark && typeof mark === "object" && str(mark.at) && isXTrendingReadId(mark.read) && str(mark.trendId)) { + goneTabs[tab] = { at: mark.at, read: mark.read, trendId: mark.trendId }; + } + } + } 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), ); @@ -449,6 +523,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { seen, ...(media ? { media } : {}), ...(gone ? { gone } : {}), + ...(Object.keys(goneTabs).length ? { goneTabs } : {}), ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}), ...(moved ? { moved } : {}), }; @@ -557,10 +632,26 @@ export type RecordReadInput = { // 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; + // What the page said of itself in this capture (xTrendingParse.ts + // trendPageOf): written onto the topic's source, and the name of a topic + // nobody named. + page?: { title?: string; summary?: string; lastUpdatedAt?: string; tabs?: ReadonlyArray<XTrendingTab> }; + // The tab whose timeline this read saw (its label), when the capture shows + // ONE; and, per post, the tab that showed it. + tab?: string; + tabs?: Readonly<Record<string, string>>; + // A READ OF SEVERAL TABS (lane x-followups): per timeline the capture lists, + // the posts it listed in its own order, its tab's label when the capture + // names it (else `timelineId`, which the source's known tabs may name), and + // whether that tab was read to its end. Given, it replaces `tab` and + // `complete`; `postIds` stays every post of the read, each once. + tabReads?: ReadonlyArray<{ tab?: string; timelineId?: string; postIds: ReadonlyArray<string>; complete?: boolean }>; }; export type RecordReadResult = { - topic: { id: string; title: string; created: boolean }; + // `renamed`: the topic carried the name it was born with ("Trending + // <number>") and took the page's title in this pass; `was` is that name. + topic: { id: string; title: string; created: boolean; renamed?: { was: string } }; // Posts this read placed in the topic (new to the library's membership). placed: number; // Posts the library already had, left in the topic they were in. @@ -569,11 +660,35 @@ export type RecordReadResult = { // only), and posts that were gone and are shown again. gone: string[]; back: string[]; + // Posts a tab read to its end no longer shows while another tab still does. + goneFromTab?: Array<{ id: string; tab: string }>; + // The tabs this read listed, by label (as the source names them), and the + // label of each timeline id the read named. + tabs?: string[]; + tabLabels?: Record<string, string>; }; +// A page's title as a topic's name: one line, cut to a topic name's length. +function pageTitleAsName(title: string | undefined): string | undefined { + const text = title?.replace(/\s+/g, " ").trim(); + if (!text) return undefined; + return text.length > X_TRENDING_TOPIC_TITLE_MAX ? text.slice(0, X_TRENDING_TOPIC_TITLE_MAX - 1).trimEnd() + "…" : text; +} + // One read, recorded: its topic found or made, the page added to the topic's // sources, the read appended, and every post it showed given a place (a post // already placed keeps its topic and gains the read). +// +// THE TOPIC'S NAME (lane x-followups). A topic made by a read that named none +// is called by the page's title when the capture carries one, else "Trending +// <number>". A topic STILL CARRYING THAT FALLBACK for this page takes the +// page's title in any later pass that finds one — a read or a reparse. A +// topic somebody named is never renamed by a read: one made with a name +// asked for, and one renamed since (`titleFrom`, a field no merge or move +// writes; by the operator or an agent — even back to the fallback's words, and +// even when the name asked for IS the fallback's words). A title another +// topic already answers to is not taken (a topic's name is its own): the +// fallback stays, and the source carries X's title all the same. export async function recordXTrendingRead(channelRoot: string, input: RecordReadInput): Promise<RecordReadResult> { if (!isXTrendingReadId(input.readId)) throw new Error(`"${input.readId}" is not a trending read id`); const topic = await withJsonFileLock(topicsPath(channelRoot), async () => { @@ -586,13 +701,15 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId)); } let created = false; + let renamed: { was: string } | undefined; + const fallback = xTrendingFallbackTitle(input.ref.trendId); if (!found) { - const title = asked || `Trending ${input.ref.trendId}`; const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`; let id = base; // Never the id of a topic merged away: that id means the topic it went into. for (let n = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); n++) id = `${base}-${n}`; - found = { id, title, createdAt: input.at, sources: [] }; + // A name asked for is a SET name, whatever its words ("Trending <number>" included). + found = { id, title: asked || fallback, createdAt: input.at, sources: [], ...(asked ? { titleFrom: "ask" as const } : {}) }; topics.push(found); created = true; } @@ -601,62 +718,170 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] }; found.sources.push(source); } + // X's own words for the page and its tabs, as THIS capture has them — only + // from a pass no older than the source's latest read (a reparse of an old + // read does not put old words over newer ones), or where the source has + // none yet (there is nothing newer to keep). + const newest = source.reads.reduce((a, r) => (r.at > a ? r.at : a), ""); + if (input.page) { + const current = input.at >= newest; + const title = input.page.title?.replace(/\s+/g, " ").trim(); + const summary = input.page.summary?.replace(/\s+/g, " ").trim(); + if (title && (current || !source.title)) source.title = title; + if (summary && (current || !source.summary)) source.summary = summary; + if (input.page.lastUpdatedAt && (current || !source.lastUpdatedAt)) source.lastUpdatedAt = input.page.lastUpdatedAt; + if (input.page.tabs?.length && (current || !source.tabs?.length)) { + source.tabs = input.page.tabs.map((t) => ({ label: t.label, timelineId: t.timelineId })); + } + } + // THE NAME, from what the SOURCE now holds (review 1 S4): the same age + // guard as the words above, so an older read parsed again never names a + // topic by a title older than the one the source already has. + if (!xTrendingTopicNameIsSet(found) && found.title === fallback) { + const name = pageTitleAsName(source.title); + // Unless another topic answers to it: a topic's name is its own. + if (name && name !== found.title && !resolveXTrendingTopic(topics.filter((t) => t !== found), name)) { + if (!created) renamed = { was: found.title }; + found.title = name; + found.titleFrom = "page"; + } + } + // THE TABS THIS READ LISTED, each named: by the capture's own page answer, + // else by the tabs the source already knows for that timeline id (a + // capture with no page answer still says which tab it was). + const tabLabels: Record<string, string> = {}; + const tabReads = (input.tabReads ?? [{ postIds: [...input.postIds], ...(input.tab ? { tab: input.tab } : {}), ...(input.complete ? { complete: true } : {}) }]).map((t) => { + const tab = t.tab ?? (t.timelineId ? source!.tabs?.find((known) => known.timelineId === t.timelineId)?.label : undefined); + if (tab && t.timelineId) tabLabels[t.timelineId] = tab; + return { postIds: [...t.postIds], ...(tab ? { tab } : {}), ...(t.complete ? { complete: true } : {}) }; + }); + const tabsSeen = [...new Set(tabReads.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; const read = source.reads.find((r) => r.id === input.readId); + const tabFields = { ...(tabsSeen.length === 1 ? { tab: tabsSeen[0] } : {}), ...(tabsSeen.length > 1 ? { tabs: tabsSeen } : {}) }; if (!read) { - source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added }); + source.reads.push({ id: input.readId, at: input.at, posts: input.postIds.length, added: input.added, ...tabFields }); } else { // The same read recorded again (a reparse): what the capture is now // read to hold, and whatever this pass added on top of the last. read.posts = input.postIds.length; read.added += input.added; + if (tabsSeen.length) { + delete read.tab; + delete read.tabs; + Object.assign(read, tabFields); + } } await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); - return { id: found.id, title: found.title, created }; + // THE TAB THE PAGE OPENS ON (the reader reads it first, as "Top"): the + // source's tab NAMED Top, wherever the page's answer lists it (review 3 + // S7), else its first known tab, else a tab of that name in this read. A + // sighting that names no tab was this tab's (review 2 M2). + const isTop = (label: string | undefined) => label?.trim().toLowerCase() === "top"; + const openingTab = + source.tabs?.find((t) => isTop(t.label))?.label ?? source.tabs?.[0]?.label ?? tabReads.find((t) => isTop(t.tab))?.tab; + return { id: found.id, title: found.title, created, ...(renamed ? { renamed } : {}), tabReads, tabLabels, openingTab }; }); const counts = await withJsonFileLock(membershipPath(channelRoot), async () => { const posts = await readXTrendingMembership(channelRoot); let placed = 0; let kept = 0; const gone: string[] = []; + const goneFromTab: Array<{ id: string; tab: 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]; - if (have) { - kept++; - if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen); - if (!have.media && input.media?.[id]) have.media = input.media[id]; - 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); + const counted = new Set<string>(); + for (const tabRead of topic.tabReads) { + tabRead.postIds.forEach((id, i) => { + const tab = input.tabs?.[id] ?? tabRead.tab; + const seen: XTrendingSeen = { read: input.readId, trendId: input.ref.trendId, at: input.at, rank: i + 1, ...(tab ? { tab } : {}) }; + const have = posts[id]; + if (have) { + if (!counted.has(id)) kept++; + // One sighting per read AND tab. The same read again (a reparse) + // gives the sighting the tab it could not say before. + const same = have.seen.find((s) => s.read === input.readId && s.tab === tab); + const untagged = same ? undefined : have.seen.find((s) => s.read === input.readId && s.tab === undefined); + if (!same && untagged && tab) untagged.tab = tab; + else if (!same && !untagged) 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 on this tab, by a read later than the one that missed it. + const key = tab ?? ""; + const tabMark = have.goneTabs?.[key]; + if (tabMark && input.at > tabMark.at) { + delete have.goneTabs![key]; + if (Object.keys(have.goneTabs!).length === 0) delete have.goneTabs; + } + if (have.gone && input.at > have.gone.at) { + (have.wasGone ??= []).push({ from: have.gone.at, to: input.at }); + delete have.gone; + if (!back.includes(id)) back.push(id); + } + } else { + placed++; + posts[id] = { + topic: topic.id, + ...(input.threads?.[id] ? { thread: input.threads[id] } : {}), + seen: [seen], + ...(input.media?.[id] ? { media: input.media[id] } : {}), + }; } - } else { - placed++; - 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); + counted.add(id); + }); + } + // GONE, TAB BY TAB. A tab read to its end marks the posts THAT TAB showed + // before and does not show now (`goneTabs[<tab>]`): "gone from <tab> at + // <time>". A mark stays per tab and per read. + // + // GONE FROM THE PAGE (`gone`; review 2, ruling R-d) only when EVERY tab + // that showed the post dropped it IN THIS READ: each of its earlier + // sightings is judged by a tab this read read to its end without it, and + // no tab of this read shows it. Marks from different reads ("gone from + // Latest" at one read, "from Top" at a later one) never combine into it. + // + // WHICH SIGHTINGS A TAB'S READ JUDGES (review 2 M2): its own tab's. A + // sighting that names no tab (a read from before tabs were read) was the + // OPENING tab's: only a complete read of that tab judges it — or a read + // that cannot name its own tab. A read that cannot say its tab judges + // only sightings that name none. + const judges = (s: XTrendingSeen, tabRead: { tab?: string }) => + s.tab !== undefined + ? tabRead.tab !== undefined && s.tab === tabRead.tab + : tabRead.tab === undefined || (topic.openingTab !== undefined && tabRead.tab === topic.openingTab); + const shownNow = new Set(topic.tabReads.flatMap((t) => t.postIds)); + const completeReads = topic.tabReads.filter((t) => t.complete); + if (completeReads.length) { 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); + if (m.gone) continue; + const earlier = m.seen.filter((s) => s.trendId === input.ref.trendId && s.read !== input.readId && s.at < input.at); + if (earlier.length === 0) continue; + const droppedBy = completeReads.filter((t) => !t.postIds.includes(id) && earlier.some((s) => judges(s, t))); + if (droppedBy.length === 0) continue; + const mark: XTrendingGone = { at: input.at, read: input.readId, trendId: input.ref.trendId }; + const marked: string[] = []; + for (const t of droppedBy) { + const key = t.tab ?? ""; + if (m.goneTabs?.[key]) continue; + (m.goneTabs ??= {})[key] = mark; + if (t.tab) marked.push(t.tab); + } + if (!shownNow.has(id) && earlier.every((s) => droppedBy.some((t) => judges(s, t)))) { + m.gone = mark; + gone.push(id); + } else { + for (const tab of marked) goneFromTab.push({ id, tab }); + } } } await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true }); - return { placed, kept, gone, back }; + return { placed, kept, gone, back, ...(goneFromTab.length ? { goneFromTab } : {}) }; }); - return { topic, ...counts }; + const tabs = [...new Set(topic.tabReads.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; + return { + topic: { id: topic.id, title: topic.title, created: topic.created, ...(topic.renamed ? { renamed: topic.renamed } : {}) }, + ...(tabs.length ? { tabs } : {}), + ...(Object.keys(topic.tabLabels).length ? { tabLabels: topic.tabLabels } : {}), + ...counts, + }; } // ── one read's record ────────────────────────────────────────────────────── @@ -687,6 +912,16 @@ export type XTrendingReadOutcome = | "gone" | "error"; +export type XTrendingReadTab = { + tab?: string; + asked?: "top" | "latest"; + posts: number; + scrolls?: number; + stop?: string; + pageEnd?: boolean; + why?: string; +}; + export type XTrendingReadRecord = { version: 1; id: string; @@ -714,6 +949,18 @@ export type XTrendingReadRecord = { // Posts the parser finds in the capture, and how many the library lacked. posts: { onPage: number; added: number }; topic?: { id: string; title: string }; + // WHICH TAB'S TIMELINE THE READ SAW (lane x-followups): per timeline the + // capture lists, the page's label for it (absent when the page names no + // such tab, or the capture has no page answer) and the posts it showed + // first. Labels and counts only. A read sees one: the tab the page opens on. + // + // TAB BY TAB (R3): a read covers "Top" and then "Latest". Per tab: what was + // asked (`asked`), how many scrolls it took, why its scrolling stopped + // (`stop`: a TrendingReadStop, "not-read" with `why` when the tab could not + // be opened, "not-asked" for the opening tab of a read asked for the other + // only) and whether the capture shows that tab's end (`pageEnd`). An entry + // with no `tab` is posts listed by a request that named no timeline. + tabs?: XTrendingReadTab[]; shot: boolean; sentence: string; // When the capture was last parsed again (`reparse`). @@ -811,6 +1058,13 @@ export type XTrendingTopicRow = { url: string; title?: string; summary?: string; + // When X last rewrote its title and summary, the page's tabs by label, + // and the tab the LAST read saw (the only one a read sees). + lastUpdatedAt?: string; + tabs?: string[]; + lastReadTab?: string; + // …or the tabs, when the last read covered several. + lastReadTabs?: string[]; reads: number; lastReadAt: string | null; }>; @@ -829,7 +1083,10 @@ export type XTrendingPostRow = { text: string; media: XTrendingMedia & { thumbnail?: string }; topic: string; - reads: Array<{ read: string; trendId: string; at: string }>; + reads: Array<{ read: string; trendId: string; at: string; tab?: string }>; + // Gone from these tabs while another tab of the page still shows it (a + // tab's read reached its end without it). Absent once `gone` is set. + goneTabs?: Array<{ tab: string; at: string; read: string }>; // 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; @@ -930,6 +1187,35 @@ export async function listXTrendingReadIds(channelRoot: string): Promise<string[ } } +// X'S SUMMARY, AS A LISTING GIVES IT (review 1): the whole text is kept on the +// source (topics.json); a listing — the channel page, `get trending`, the MCP, +// umtool — gives at most this much, cut at a word with an ellipsis. X writes +// these, and they are other people's words inside a list of topics. +export const X_TRENDING_SUMMARY_LIST_MAX = 600; +export function listedXTrendingSummary(summary: string, max: number = X_TRENDING_SUMMARY_LIST_MAX): string { + if (summary.length <= max) return summary; + const cut = summary.slice(0, max - 1); + const word = cut.lastIndexOf(" "); + return `${(word > max * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; +} + +// The tabs the source's latest read saw, when that read says. +function lastReadTabsOf(s: XTrendingSource): string[] { + const last = s.reads.reduce<XTrendingSourceRead | undefined>((a, r) => (a === undefined || r.at > a.at ? r : a), undefined); + return last?.tabs?.length ? last.tabs : last?.tab ? [last.tab] : []; +} + +// The tabs a post is gone from WHILE THE PAGE STILL SHOWS IT on another: +// nothing once it is gone from the page (`gone` says that), and never the +// mark of a read that could not say its tab. +function goneFromTabsOf(m: XTrendingMember): Array<{ tab: string; at: string; read: string }> { + if (m.gone || !m.goneTabs) return []; + return Object.entries(m.goneTabs) + .filter(([tab]) => tab !== "") + .map(([tab, mark]) => ({ tab, at: mark.at, read: mark.read })) + .sort((a, b) => a.tab.localeCompare(b.tab)); +} + const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.at : a), ""); // The library's topics and posts. `topic` narrows the posts to one topic (its @@ -1011,8 +1297,9 @@ export async function listXTrending( text: post.text, media, topic: m.topic, - reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })), + reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at, ...(s.tab ? { tab: s.tab } : {}) })), ...(m.gone ? { gone: m.gone } : {}), + ...(goneFromTabsOf(m).length ? { goneTabs: goneFromTabsOf(m) } : {}), thread, ...(effective ? { judgement: effective } : {}), ...(opts.detail @@ -1061,7 +1348,11 @@ export async function listXTrending( trendId: s.trendId, url: s.url, ...(s.title ? { title: s.title } : {}), - ...(s.summary ? { summary: s.summary } : {}), + ...(s.summary ? { summary: listedXTrendingSummary(s.summary) } : {}), + ...(s.lastUpdatedAt ? { lastUpdatedAt: s.lastUpdatedAt } : {}), + ...(s.tabs?.length ? { tabs: s.tabs.map((t) => t.label) } : {}), + ...(lastReadTabsOf(s).length === 1 ? { lastReadTab: lastReadTabsOf(s)[0] } : {}), + ...(lastReadTabsOf(s).length > 1 ? { lastReadTabs: lastReadTabsOf(s) } : {}), reads: s.reads.length, lastReadAt: s.reads.reduce<string | null>((a, r) => (a === null || r.at > a ? r.at : a), null), })), diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts @@ -41,6 +41,15 @@ export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[ // the watch pauses ("failing") until a person switches it on again. export const X_TRENDING_WATCH_MAX_FAILURES = 3; +// A watch's tabs when it does NOT read both (both is the default and is not +// written): ["top"] or ["latest"]. Anything else reads both. +export function watchTabsOf(v: unknown): Array<"top" | "latest"> | undefined { + if (!Array.isArray(v)) return undefined; + const asked = new Set(v.filter((t): t is string => typeof t === "string").map((t) => t.toLowerCase())); + const tabs = (["top", "latest"] as const).filter((t) => asked.has(t)); + return tabs.length === 1 ? [...tabs] : undefined; +} + export type XTrendingWatch = { on: boolean; intervalMinutes: number; @@ -48,6 +57,8 @@ export type XTrendingWatch = { startedAt: string; until: string; shots: boolean; + // The ONE tab each tick reads, when not both (R3): ["top"] or ["latest"]. + tabs?: Array<"top" | "latest">; by: "agent" | "operator"; // The last tick the scan enqueued: when, its job, and when the next is due. lastTickAt?: string; @@ -87,6 +98,7 @@ function parseWatch(raw: unknown): XTrendingWatch | null { startedAt: r.startedAt, until: r.until, shots: r.shots === true, + ...(watchTabsOf(r.tabs) ? { tabs: watchTabsOf(r.tabs) } : {}), by: r.by === "operator" ? "operator" : "agent", ...(iso(r.lastTickAt) ? { lastTickAt: r.lastTickAt } : {}), ...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}), @@ -142,6 +154,9 @@ export type SetWatchAsk = { intervalMinutes: number; hours: number; shots?: boolean; + // The page's tabs each tick reads: ["top"], ["latest"] or both. Absent: + // what the watch had, else both. + tabs?: ReadonlyArray<"top" | "latest">; by: "agent" | "operator"; maxTopics: number; now: number; @@ -211,6 +226,7 @@ export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): startedAt: live?.startedAt ?? at, until, shots: ask.shots ?? live?.shots ?? false, + ...(watchTabsOf(ask.tabs ?? live?.tabs) ? { tabs: watchTabsOf(ask.tabs ?? live?.tabs) } : {}), by: ask.by, ...(live?.lastTickAt ? { lastTickAt: live.lastTickAt } : {}), ...(live?.lastJobId ? { lastJobId: live.lastJobId } : {}), @@ -232,7 +248,9 @@ export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): 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" : ""}`; + const every = + `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}` + + (w.tabs ? `, reading the "${w.tabs[0] === "latest" ? "Latest" : "Top"}" tab only` : ""); if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until the operator 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; diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -3,13 +3,44 @@ // made up; the SHAPES are X's public GraphQL tweet-result shapes as this repo // already reads them (xPlaywrightFetcher.ts): `{__typename: "Tweet", rest_id, // core.user_results.result, legacy}`, a TweetWithVisibilityResults wrapper, a -// quoted result, a promoted entry. The operation names are invented too — the -// real ones are learned from the first real read (the probe). +// quoted result, a promoted entry. The operation names are invented too. The +// page's own answer (title, summary, tabs) and the timeline id its requests +// name are in the shape the first real read showed (lane x-followups); the +// whole real shape, instruction by instruction, is xTrendingRealShape.ts. export const FIXTURE_TREND_ID = "1900000000000000001"; export const FIXTURE_TREND_URL = `https://x.com/i/trending/${FIXTURE_TREND_ID}`; export const FIXTURE_TREND_OP = "ExampleTrendPage"; export const FIXTURE_TIMELINE_OP = "ExampleTrendTimeline"; +// X's own words for the page (invented), and the page's two tabs: the +// timeline the fixture's requests name is the first. +export const FIXTURE_TITLE = "Kettle festival opens"; +export const FIXTURE_SUMMARY = "The annual kettle festival opened this morning to a long queue."; +export const FIXTURE_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); +export const FIXTURE_TOP_TIMELINE = "fixture-timeline-top"; +export const FIXTURE_LATEST_TIMELINE = "fixture-timeline-latest"; + +// The page's own answer, as the real page shapes it. +export function fixtureTrendPageBody(): Record<string, unknown> { + return { + data: { + ai_trend_by_rest_id: { + rest_id: FIXTURE_TREND_ID, + result: { + page: { + article: { article_text: { entities: [], text: FIXTURE_SUMMARY }, title: FIXTURE_TITLE }, + last_updated_at_ms: FIXTURE_LAST_UPDATED_MS, + post_timelines: [ + { label: "Top", post_timeline: { id: FIXTURE_TOP_TIMELINE } }, + { label: "Latest", post_timeline: { id: FIXTURE_LATEST_TIMELINE } }, + ], + }, + rest_id: FIXTURE_TREND_ID, + }, + }, + }, + }; +} export type FixtureTweet = { id: string; @@ -90,12 +121,12 @@ function entry(t: FixtureTweet): Record<string, unknown> { } // One timeline answer holding these posts. -export function fixtureTimelineBody(tweets: FixtureTweet[]): Record<string, unknown> { +export function fixtureTimelineBody(tweets: FixtureTweet[], bottom: string = FIXTURE_BOTTOM_CURSOR): Record<string, unknown> { return { data: { timeline: { instructions: [ - { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: FIXTURE_BOTTOM_CURSOR } }] }, + { type: "TimelineAddEntries", entries: [...tweets.map(entry), { entryId: "cursor-bottom-1", content: { entryType: "TimelineTimelineCursor", cursorType: "Bottom", value: bottom } }] }, ], }, }, @@ -124,11 +155,68 @@ export const FIXTURE_SECOND_PAGE: FixtureTweet[] = [ // page's next request for that timeline carries. export const FIXTURE_BOTTOM_CURSOR = "fixture-cursor"; -const graphqlUrl = (op: string, n: number, cursor?: string) => +const graphqlUrl = (op: string, n: number, cursor?: string, timelineId: string = FIXTURE_TOP_TIMELINE) => `https://x.com/i/api/graphql/fixtureQueryId${n}/${op}?variables=${encodeURIComponent( - JSON.stringify({ rest_id: FIXTURE_TREND_ID, ...(cursor ? { cursor } : {}) }), + JSON.stringify({ + rest_id: FIXTURE_TREND_ID, + ...(op === FIXTURE_TIMELINE_OP ? { timelineId } : {}), + ...(cursor ? { cursor } : {}), + }), )}`; +// The address of a request for the page's timeline (the tab the page opens +// on): its `variables` name the timeline, and the cursor it continues from +// when it is not the first. +export function fixtureTimelineUrl(n = 2, cursor?: string, timelineId: string = FIXTURE_TOP_TIMELINE): string { + return graphqlUrl(FIXTURE_TIMELINE_OP, n, cursor, timelineId); +} + +// THE PAGE'S OTHER TAB, "Latest" (lane x-followups): its own timeline and its +// own cursor. `fixtureLatestFirst` is what pressing the tab brings; +// `fixtureLatestContinuation` what a scroll then brings (no post: the tab's end). +export const FIXTURE_LATEST_CURSOR = "fixture-latest-cursor"; +export function fixtureLatestFirst(tweets: FixtureTweet[], n = 20): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, undefined, FIXTURE_LATEST_TIMELINE), status: 200, body: fixtureTimelineBody(tweets, FIXTURE_LATEST_CURSOR) }; +} +export function fixtureLatestContinuation(tweets: FixtureTweet[] = [], n = 21): FixtureResponse { + return { url: graphqlUrl(FIXTURE_TIMELINE_OP, n, FIXTURE_LATEST_CURSOR, FIXTURE_LATEST_TIMELINE), status: 200, body: fixtureTimelineBody(tweets, FIXTURE_LATEST_CURSOR) }; +} +// What "Latest" lists: a post only it shows, and two that "Top" shows too. +export const FIXTURE_LATEST_PAGE: FixtureTweet[] = [ + { id: "1900000000000001009", handle: "lid_watch", text: "Just now: the doors are open." }, + { id: "1900000000000001001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo", "photo"] }, + { id: "1900000000000001005", handle: "lid_watch", text: "A reply about the queue.", replyTo: { id: "1900000000000001001", handle: "teapot_news" }, media: ["animated_gif"] }, +]; +// The page with both tabs: "Top" as fixtureTrendingResponses plays it (read +// to its end by a continuation that brings nothing), and a "Latest" tab that +// can be pressed and is read to its end too. +export function fixtureTwoTabResponses(latest: FixtureTweet[] = FIXTURE_LATEST_PAGE): { + load: FixtureResponse[]; + scrolls: FixtureResponse[][]; + tabs: Record< + string, + { + load?: FixtureResponse[]; + scrolls?: FixtureResponse[][]; + hidden?: boolean; + // The fake page's other ways a "Latest" may be (social/fakeXProfileBrowser.ts FakeTrendingTab). + role?: "tab" | "link" | "button"; + outsideTablist?: boolean; + clickError?: string; + countHangs?: boolean; + navigatesTo?: string; + scrollHangs?: boolean; + } + >; +} { + const top = fixtureTrendingResponses(); + return { + load: top.load, + scrolls: [top.scrolls[0], [fixtureContinuation([], 5)], []], + tabs: { Latest: { load: [fixtureLatestFirst(latest)], scrolls: [[fixtureLatestContinuation([])], []] } }, + }; +} + // 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 { @@ -141,7 +229,7 @@ export type FixtureResponse = { url: string; status: number; body?: unknown; tex export function fixtureTrendingResponses(): { load: FixtureResponse[]; scrolls: FixtureResponse[][] } { return { load: [ - { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: { data: { example_trend: { rest_id: FIXTURE_TREND_ID } } } }, + { url: graphqlUrl(FIXTURE_TREND_OP, 1), status: 200, body: fixtureTrendPageBody() }, { url: graphqlUrl(FIXTURE_TIMELINE_OP, 2), status: 200, body: fixtureTimelineBody(FIXTURE_FIRST_PAGE) }, // Not GraphQL: never saved. { url: "https://x.com/i/api/1.1/example.json", status: 200, body: { ok: true } }, diff --git a/common/social/__fixtures__/xTrendingRealShape.ts b/common/social/__fixtures__/xTrendingRealShape.ts @@ -0,0 +1,278 @@ +// A TRENDING PAGE'S ANSWERS IN THE SHAPE THE REAL PAGE GIVES THEM (lane +// x-followups), with INVENTED data: every id, handle, name, word, cursor and +// timeline id here is made up. The shapes are what the first real read of a +// trending page saved (18 Nov 2026), reduced to the keys the parser reads and +// the ones that could mislead it: +// +// AiTrendByRestId the page itself: data.ai_trend_by_rest_id.result +// .page — article {title, article_text.text}, +// last_updated_at_ms, disclaimer, post_timelines +// [{label, post_timeline.id}] (two tabs) — and +// result.contexts.topics. +// GenericTimelineById a tab's posts. Its request's `variables` name the +// timeline (`timelineId`), `count`, and from the +// second request on the `cursor` it continues from. +// FIRST answer: TimelineClearCache, TimelineTerminate +// Timeline (direction Top), TimelineAddEntries with +// tweet entries, one MODULE of accounts, a cursor-top +// and a cursor-bottom entry. LATER answers: +// TimelineAddEntries with tweet entries and NO cursor +// entry, then two TimelineReplaceEntry instructions +// carrying the new top and bottom cursors. +// TrendRelevantUsers accounts, under the page's own `data` key, in a +// timeline with instructions and no post. +// useStoryTopicQuery other trends of the same story (names, counts). +// small ones DataSaverMode, ViewerBadgeCounts: no post. +// +// THE END OF A TIMELINE IS NOT HERE. The read these shapes come from stopped +// at its post cap after three scrolls; no saved capture shows what the page +// fetches when a tab has no more posts. Its shape is NOT guessed: there is no +// builder for it, and `realContinuation` with no post (or only posts already +// shown) is the parser's own rule for an end acted out in the LATER-answer +// shape, not something X was seen to send. Until a read reaches a real end +// and saves it, `pageEnd` is true only for a capture that looks like that. + +import { fixtureTweetResult, type FixtureResponse, type FixtureTweet } from "./xTrendingCapture"; + +export const INVENTED_TREND_ID = "1900000000000000002"; +export const INVENTED_TREND_URL = `https://x.com/i/trending/${INVENTED_TREND_ID}`; +// The two operation names are X's own (they are in every such page's +// requests); everything named INVENTED_ below is made up. +export const REAL_PAGE_OP = "AiTrendByRestId"; +export const REAL_TIMELINE_OP = "GenericTimelineById"; +export const INVENTED_TITLE = "Kettle festival opens with a record queue"; +export const INVENTED_SUMMARY = + "The annual kettle festival opened this morning. Visitors queued from dawn, and the organisers added a second hall for the afternoon demonstrations."; +export const INVENTED_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); +export const INVENTED_TOP_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS10b3A="; +export const INVENTED_LATEST_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS1sYXRlc3Q="; + +const url = (op: string, variables: Record<string, unknown>) => + `https://x.com/i/api/graphql/fixtureQueryId/${op}?variables=${encodeURIComponent(JSON.stringify(variables))}&features=${encodeURIComponent("{}")}`; + +export type RealPage = { + trendId?: string; + title?: string; + summary?: string; + lastUpdatedAtMs?: number; + tabs?: Array<{ label: string; timelineId: string }>; +}; + +// The page's own answer. +export function realPageBody(o: RealPage = {}): Record<string, unknown> { + const trendId = o.trendId ?? INVENTED_TREND_ID; + const tabs = o.tabs ?? [ + { label: "Top", timelineId: INVENTED_TOP_TIMELINE }, + { label: "Latest", timelineId: INVENTED_LATEST_TIMELINE }, + ]; + return { + data: { + ai_trend_by_rest_id: { + rest_id: trendId, + result: { + contexts: { topics: ["Food and drink"] }, + page: { + article: { + article_text: { entities: [], text: o.summary ?? INVENTED_SUMMARY }, + title: o.title ?? INVENTED_TITLE, + }, + available_actions: [], + disclaimer: "This story is a summary of posts and may evolve over time.", + last_updated_at_ms: o.lastUpdatedAtMs ?? INVENTED_LAST_UPDATED_MS, + post_timelines: tabs.map((t) => ({ label: t.label, post_timeline: { id: t.timelineId } })), + }, + rest_id: trendId, + }, + }, + }, + }; +} + +export function realPageAnswer(o: RealPage = {}): FixtureResponse { + return { + url: url(REAL_PAGE_OP, { trendId: o.trendId ?? INVENTED_TREND_ID, includePromotedContent: false, withBirdwatchNotes: true, withVoice: true, withCommunity: true }), + status: 200, + body: realPageBody(o), + }; +} + +function tweetEntry(t: FixtureTweet, sort: number): Record<string, unknown> { + return { + content: { + __typename: "TimelineTimelineItem", + clientEventInfo: { component: "trends_tweets", element: "tweet" }, + entryType: "TimelineTimelineItem", + itemContent: { + __typename: "TimelineTweet", + itemType: "TimelineTweet", + tweetDisplayType: "Tweet", + tweet_results: { result: fixtureTweetResult(t) }, + }, + }, + entryId: `tweet-${t.id}`, + sortIndex: String(sort), + }; +} + +function cursorEntry(kind: "Top" | "Bottom", value: string, n: number): Record<string, unknown> { + return { + content: { __typename: "TimelineTimelineCursor", cursorType: kind, entryType: "TimelineTimelineCursor", value }, + entryId: `cursor-${kind.toLowerCase()}-${n}`, + sortIndex: String(n), + }; +} + +// The accounts module the first answer carries among its entries: users, no post. +function accountsModule(): Record<string, unknown> { + const user = (handle: string, i: number) => ({ + entryId: `trends-accounts-7-user-${i}`, + item: { + clientEventInfo: { component: "trends_accounts", element: "user" }, + itemContent: { + __typename: "TimelineUser", + itemType: "TimelineUser", + userDisplayType: "User", + user_results: { result: { __typename: "User", rest_id: `80000${i}`, core: { screen_name: handle, name: handle }, legacy: { description: "An invented account." } } }, + }, + }, + }); + return { + content: { + __typename: "TimelineTimelineModule", + clientEventInfo: { component: "trends_accounts" }, + displayType: "Vertical", + entryType: "TimelineTimelineModule", + header: { displayType: "Classic", sticky: false, text: "Relevant people" }, + items: [user("kettle_org", 1), user("teapot_news", 2), user("spout_clips", 3)], + }, + entryId: "trends-accounts-7", + sortIndex: "7", + }; +} + +const timelineBody = (instructions: unknown[]) => ({ + data: { timeline: { timeline: { instructions, metadata: { scribeConfig: { page: "trends" } } } } }, +}); + +export const realBottomCursor = (n: number) => `fixture-bottom-cursor-${n}`; +export const realTopCursor = (n: number) => `fixture-top-cursor-${n}`; + +// A tab's FIRST answer: no cursor in the request; the cursors are entries. +export function realFirstPage(tweets: FixtureTweet[], o: { timelineId?: string; bottom?: string } = {}): FixtureResponse { + return { + url: url(REAL_TIMELINE_OP, { timelineId: o.timelineId ?? INVENTED_TOP_TIMELINE, count: 20, withQuickPromoteEligibilityTweetFields: true }), + status: 200, + body: timelineBody([ + { type: "TimelineClearCache" }, + { direction: "Top", type: "TimelineTerminateTimeline" }, + { + type: "TimelineAddEntries", + entries: [ + ...tweets.slice(0, 2).map((t, i) => tweetEntry(t, 100 - i)), + accountsModule(), + ...tweets.slice(2).map((t, i) => tweetEntry(t, 90 - i)), + cursorEntry("Top", realTopCursor(1), 999), + cursorEntry("Bottom", o.bottom ?? realBottomCursor(1), 1), + ], + }, + ]), + }; +} + +// A LATER answer of a tab: the request carries the cursor it continues from; +// the answer lists no cursor entry and REPLACES the two it had. +export function realContinuation( + tweets: FixtureTweet[], + o: { timelineId?: string; asked?: string; bottom?: string; n?: number } = {}, +): FixtureResponse { + const n = o.n ?? 2; + return { + url: url(REAL_TIMELINE_OP, { + timelineId: o.timelineId ?? INVENTED_TOP_TIMELINE, + count: 20, + cursor: o.asked ?? realBottomCursor(n - 1), + withQuickPromoteEligibilityTweetFields: true, + }), + status: 200, + body: timelineBody([ + { type: "TimelineAddEntries", entries: tweets.map((t, i) => tweetEntry(t, 80 - i)) }, + { entry: cursorEntry("Top", realTopCursor(n), 999), entry_id_to_replace: "cursor-top-999", type: "TimelineReplaceEntry" }, + { entry: cursorEntry("Bottom", o.bottom ?? realBottomCursor(n), 1), entry_id_to_replace: "cursor-bottom-1", type: "TimelineReplaceEntry" }, + ]), + }; +} + +// The accounts the page names, under the page's own `data` key: a timeline +// with instructions and no post. +export function realRelevantUsers(trendId: string = INVENTED_TREND_ID): FixtureResponse { + return { + url: url("TrendRelevantUsers", { trendId }), + status: 200, + body: { + data: { + ai_trend_by_rest_id: { + rest_id: trendId, + result: { trend_relevant_users: { timeline: { instructions: [{ type: "TimelineAddEntries", entries: [accountsModule()] }] } } }, + }, + }, + }, + }; +} + +// Other trends of the same story. +export function realStoryTopics(): FixtureResponse { + const trend = (id: string, name: string) => ({ + trend_results: { + id: `trend-${id}`, + result: { + __typename: "Trend", + core: { category: "Food and drink", created_at_ms: INVENTED_LAST_UPDATED_MS, hook: "An invented hook.", name }, + id: `trend-${id}`, + post_count: "1.2K", + rest_id: id, + social_proof: [], + }, + }, + }); + return { + url: url("useStoryTopicQuery", { rest_id: "story-fixture", limit: 3 }), + status: 200, + body: { data: { story_topic: { id: "story-fixture", stories: { items: [trend("1900000000000000003", "Teapot prices"), trend("1900000000000000004", "Saucer shortage")] } } } }, + }; +} + +const small = (op: string, body: unknown): FixtureResponse => ({ url: url(op, {}), status: 200, body }); + +export const INVENTED_FIRST: FixtureTweet[] = [ + { id: "1900000000000003001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo"] }, + { + id: "1900000000000003002", + handle: "saucer_fan", + text: "Quoting the festival post.", + quoted: { id: "1900000000000002900", handle: "kettle_org", text: "Festival programme attached.", media: ["photo"] }, + }, + { id: "1900000000000003003", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true }, +]; +export const INVENTED_SECOND: FixtureTweet[] = [ + { id: "1900000000000003004", handle: "lid_watch", text: "The queue at noon.", media: ["animated_gif"] }, + { id: "1900000000000003005", handle: "kettle_org", text: "A second hall is open." }, +]; +export const INVENTED_THIRD: FixtureTweet[] = [ + { id: "1900000000000003006", handle: "teapot_news", name: "Teapot News", text: "Afternoon demonstrations begin." }, +]; + +// What the page fetched, in the order the real read saved it: small answers, +// the page, its accounts, its story, the first page of the default tab, then +// one continuation per scroll (`later`: the posts each brought). +export function realCaptureResponses(o: { page?: RealPage; first?: FixtureTweet[]; later?: FixtureTweet[][] } = {}): FixtureResponse[] { + const later = o.later ?? [INVENTED_SECOND, INVENTED_THIRD]; + return [ + small("DataSaverMode", { data: { viewer: { data_saver_mode: false } } }), + realPageAnswer(o.page), + realRelevantUsers(o.page?.trendId), + realStoryTopics(), + realFirstPage(o.first ?? INVENTED_FIRST), + small("ViewerBadgeCounts", { data: { viewer_v2: { badge_counts: { ntab_unread_count: 0 } } } }), + ...later.map((tweets, i) => realContinuation(tweets, { n: i + 2 })), + ]; +} diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -17,7 +17,8 @@ // exists (a spec writes it). The file holds SYNTHETIC cookies only: // { "delayMs"?: number, "closeAfterMs"?: number, "fail"?: string, // "cookies": [{ name, value, domain, path?, expires? }], -// "trending"?: { href?, load: [{url, status, body?, text?}], scrolls: [[…], …] } } +// "trending"?: { href?, load: [{url, status, body?, text?}], scrolls: [[…], …], +// tabs?: { "<label>": { load?, scrolls?, hidden? } } } } // // A TRENDING PAGE (lane x-trending): with `trending` in the file, the fake's // page answers a read of x.com/i/trending/<id> (xTrendingRead.ts) from it — @@ -40,6 +41,29 @@ export type FakeTrendingPage = { gotoError?: string; load: FakeTrendingResponse[]; scrolls?: FakeTrendingResponse[][]; + // THE PAGE'S OTHER TABS (lane x-followups), by the label the page shows: + // pressing one (getByRole("tablist").getByRole("tab", {name})) plays its + // `load` back and makes its `scrolls` the ones the next scrolls bring. A tab + // with `hidden` is not on the page at all; one with no `load` is pressed and + // brings nothing (a tab that never loads). Review 2: `role` makes it a link + // or a button of that name instead (never pressed); `outsideTablist` puts + // it outside the tab list; `clickError` makes its click throw; `countHangs` + // makes its look-up never answer; `navigatesTo` is where the page is after + // it is pressed (another page). + tabs?: Record<string, FakeTrendingTab>; +}; + +export type FakeTrendingTab = { + load?: FakeTrendingResponse[]; + scrolls?: FakeTrendingResponse[][]; + hidden?: boolean; + role?: "tab" | "link" | "button"; + outsideTablist?: boolean; + clickError?: string; + countHangs?: boolean; + navigatesTo?: string; + // Its scrolls never answer (a page that stops answering inside the tab). + scrollHangs?: boolean; }; type FixtureFile = { @@ -68,6 +92,10 @@ export function fakeTrendingPage( const handlers: Array<(res: unknown) => void> = []; let asked = ""; let scrolled = 0; + // The tab pressed last ("" = the tab the page opened on). + let active = ""; + // Where a press took the page (FakeTrendingTab.navigatesTo). + let movedTo: string | undefined; const emit = (responses: FakeTrendingResponse[] | undefined) => { for (const r of responses ?? []) { const res = { @@ -84,6 +112,8 @@ export function fakeTrendingPage( if (f.delayMs && f.delayMs > 0) await wait(Math.min(f.delayMs, 30_000)); asked = url; scrolled = 0; + active = ""; + movedTo = undefined; if (f.trending?.gotoError) throw new Error(f.trending.gotoError); emit(f.trending?.load); return null; @@ -93,10 +123,38 @@ export function fakeTrendingPage( evaluate: async (fn: string) => { const t = source().trending; if (!t) return null; - if (fn === "location.href") return t.href ?? asked; - if (fn.includes("scrollTo")) emit(t.scrolls?.[scrolled++]); + if (fn === "location.href") return movedTo ?? t.href ?? asked; + if (fn.includes("scrollTo") && active && t.tabs?.[active]?.scrollHangs) return new Promise(() => {}); + if (fn.includes("scrollTo")) emit((active ? t.tabs?.[active]?.scrolls : t.scrolls)?.[scrolled++]); return null; }, + // The page's controls by role and name, as Playwright finds them: a tab + // list (holding the tabs that are in it), and tabs, links and buttons. + getByRole: (role: string, opts?: { name?: string | RegExp }) => { + const tabs = () => Object.entries(source().trending?.tabs ?? {}).filter(([, t]) => !t.hidden); + const control = (inList: boolean) => (r: string, o?: { name?: string | RegExp }) => { + const name = typeof o?.name === "string" ? o.name : ""; + const tab = tabs().find(([label, t]) => label === name && (t.role ?? "tab") === r && (inList ? !t.outsideTablist : true))?.[1]; + return { + count: () => (tab?.countHangs ? new Promise<number>(() => {}) : Promise.resolve(tab ? 1 : 0)), + first: () => ({ + click: async () => { + if (!tab) throw new Error(`no ${r} named ${name}`); + if (tab.clickError) throw new Error(tab.clickError); + active = name; + scrolled = 0; + if (tab.navigatesTo) movedTo = tab.navigatesTo; + emit(tab.load); + }, + }), + }; + }; + if (role === "tablist") { + const any = tabs().some(([, t]) => (t.role ?? "tab") === "tab" && !t.outsideTablist) || tabs().some(([, t]) => t.countHangs); + return { count: async () => (any ? 1 : 0), first: () => ({ click: async () => {} }), getByRole: control(true) }; + } + return control(false)(role, opts); + }, on: (event: string, cb: (arg: never) => void) => { if (event === "response") handlers.push(cb as (res: unknown) => void); }, diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -71,6 +71,11 @@ export type PostFetchInput = { // --full repair, which re-walks everything on purpose. Undefined: the // fetcher's own default. stopAtKnown?: boolean; + // The run RESUMES THE FULL-HISTORY WALK from `cursor` (lib/timelineWalk.ts + // "backfill"): no watermark, and posts already archived are not its end. A + // fetcher that can tell a resume point was not honoured says so instead of + // walking the timeline again from the top. + resumedBackfill?: boolean; // Save progress during a long run: called with posts not yet handed back and // the resume point they are safe under. Posts passed here are NOT returned // again in the result. A fetcher that pages in one shot never calls it. @@ -98,6 +103,10 @@ export type PostFetchResult = { // Maps onto the existing "needs cookies" snapshot bucket rather than // inventing a new failure surface. needsCookies?: boolean; + // `complete` because the walk met a run of posts already archived (a + // sync's "caught up"), not because the source had no more. Never the end of + // a history walk: the controller keeps a backfill's resume point on it. + caughtUp?: boolean; // The run failed part-way. `posts` and `cursor` still hold what it got, so // the controller saves them before reporting the failure. error?: string; diff --git a/common/social/importPost.test.ts b/common/social/importPost.test.ts @@ -45,7 +45,10 @@ channel("synth-kitchen", { name: "Synth Kitchen", handling: "youtube", url: "htt const { getPaths } = await import("../lib/paths"); const { readAllPosts } = await import("../lib/posts-server"); const { parsePostUrl } = await import("./fetchers"); -const { importPost, planImportPost, NOT_A_POST_URL } = await import("./importPost"); +// X is asked only inside a job of the editor's, on X's queue (lib/xJobRule.ts): these calls stand where one does. +const { importPost: importPostDirect, planImportPost, NOT_A_POST_URL } = await import("./importPost"); +const { insideEditorJob } = await import("../testing/jobs/asEditorJob"); +const importPost = insideEditorJob(importPostDirect); const { xGalleryDlFetcher } = await import("./xGalleryDlFetcher"); const { readFileSync } = await import("node:fs"); type Fetcher = import("./fetchers").SocialFetcher; @@ -181,3 +184,20 @@ test("X through gallery-dl: the status URL is what it reads, and the one post it const archived = await readAllPosts(path.join(ROOT, "channels", "synth-gdl")); assert.deepEqual(archived.map((p) => p.id), ["1700000000000000077"], "the quoted post is not written"); }); + +// Added scope R2 (lane x-followups): where X is about to be asked, only a job on X's queue stands. +test("R2a: importing an X post outside the editor's job, or in a job on another queue, asks the fetcher nothing; a Bluesky post is not X's", async () => { + const { asEditorJob } = await import("../testing/jobs/asEditorJob"); + const { f, asked } = fakeFetcher("twitter", (id) => post(id, "synthbaker")); + const ask = { paths, slug: "synth-social", url: "https://x.com/synthbaker/status/1700000000000000555", settings: {}, fetcherFor: () => f }; + const outside = await importPostDirect(ask); + assert.equal(outside.ok, false); + assert.match(outside.error ?? "", /^Importing https:\/\/x\.com\/synthbaker\/status\/1700000000000000555 asks X, and X is asked only by the editor's own jobs .*Queue it instead: pnpm ops import-post/); + const elsewhere = await asEditorJob(() => importPostDirect(ask), { queueKey: "platform:youtube" }); + assert.match(elsewhere.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "platform:youtube" is refused/); + assert.deepEqual(asked, []); + // Bluesky has no such rule: read with no job at all. + const sky = fakeFetcher("bluesky", () => null); + const r = await importPostDirect({ paths, slug: "synth-sky", url: "https://bsky.app/profile/synthbaker.bsky.social/post/3kother", settings: {}, fetcherFor: () => sky.f }); + assert.doesNotMatch(r.error ?? "", /asks X/); +}); diff --git a/common/social/importPost.ts b/common/social/importPost.ts @@ -17,6 +17,7 @@ // platform's queue, so it never runs beside a fetch of the same source. // A post already archived is not read again. +import { xJobContextRefusal } from "../lib/xJobRule"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import path from "node:path"; import type { Paths } from "../lib/paths"; @@ -144,6 +145,11 @@ export async function importPost(opts: { log(`Post ${ref.id} is already in ${opts.slug}'s archive; nothing to read.`); return { ...base, ok: true, already: true }; } + // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts). + if (fetcher.platform === "twitter") { + const refusal = xJobContextRefusal(`Importing ${ref.url}`, `pnpm ops import-post --json '{"slug":"${opts.slug}","url":"…"}' --wait`); + if (refusal) return { ...base, ok: false, error: refusal }; + } const policy = resolveCookiePolicy(opts.settings, config); const xLogin = fetcher.platform === "twitter" ? await resolveXCookieSourceFor(opts.paths, opts.settings, policy.cookies) : undefined; diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts @@ -43,12 +43,25 @@ export type BrowserLike = { close: () => Promise<void>; }; +// What a role look-up finds (Playwright's Locator, the part used): how many, +// the first pressed, and a look-up INSIDE it (a tab within a tab list). +export type LocatorLike = { + count: () => Promise<number>; + first: () => { click: (opts?: { timeout?: number }) => Promise<void> }; + getByRole?: (role: string, opts?: { name?: string | RegExp; exact?: boolean }) => LocatorLike; +}; + export type PageLike = { goto: (url: string, opts?: unknown) => Promise<unknown>; waitForSelector: (sel: string, opts?: unknown) => Promise<unknown>; waitForTimeout: (ms: number) => Promise<void>; evaluate: (fn: string) => Promise<unknown>; on: (event: string, cb: (arg: never) => void) => void; + // Something the page shows, found as a person finds it — by its role and + // its name (Playwright's getByRole) — and pressed. A trending read presses + // the page's own tab with it (xTrendingRead.ts); nothing else does. + // Optional: a page without it has nothing to press. + getByRole?: (role: string, opts?: { name?: string | RegExp; exact?: boolean }) => LocatorLike; // The post capture's shot (xPostCapture.ts): a PNG of the page, clipped to // the post. `clip` is in document coordinates when `fullPage` is set, in // the window's otherwise. diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -514,3 +514,106 @@ test("normalizeXTweets (the Playwright fallback's batch) links quotes the same w assert.equal(posts.find((p) => p.id === T3)?.quoted?.id, T5); assert.ok(!posts.some((p) => p.id === Q1 || p.id === Q2)); }); + +// --------------------------------------------------------------------------- +// The history walk's search phase, and a resumed backfill (lane x-followups) +// --------------------------------------------------------------------------- + +test("stream: the search phase's page marker is a resume point, in the extractor's own cursor form", async () => { + const { searchPhaseCursor, X_SEARCH_PHASE_STATE } = await import("./xGalleryDlFetcher"); + assert.equal(searchPhaseCursor("1899000000000000041"), "3_1899000000000000041/"); + // State 3 is the unfiltered search: the one a text-tweets run goes to (it skips state 2, the media search). + assert.equal(X_SEARCH_PHASE_STATE, 3); + assert.ok(buildGalleryDlArgs({ accountUrl: ACCOUNT, stream: true }).includes("extractor.twitter.text-tweets=true")); + + const s = newStream({ searchPhaseCursors: true }); + s.pushStdout(jsonl(1)); + assert.equal(s.pushStderr("[twitter][debug] Cursor: 1/LAST-TIMELINE-PAGE"), "cursor"); + // The timeline API has ended: gallery-dl goes on by search, which logs no "Cursor:" line. + s.pushStdout(jsonl(2)); + assert.equal(s.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000041"), "cursor"); + assert.equal(s.cursor, "3_1899000000000000041/"); + // A checkpoint is one page back, as with cursors. + assert.equal(s.takeCheckpoint()?.cursor, "1/LAST-TIMELINE-PAGE"); + s.pushStdout(jsonl(3)); + assert.equal(s.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000030"), "cursor"); + assert.deepEqual(s.takeCheckpoint()?.cursor, "3_1899000000000000041/"); + assert.equal(s.cursor, "3_1899000000000000030/"); + // A search that falls back to cursor paging logs its own cursor: taken as it is. + s.pushStderr("[twitter][debug] Cursor: 3_1899000000000000030/API-CURSOR"); + assert.equal(s.cursor, "3_1899000000000000030/API-CURSOR"); + // Its other debug lines are noise, and no boundary. + assert.equal(s.pushStderr("[twitter][debug] Repeated 'max_id' value (1899000000000000030)"), undefined); + assert.equal(s.cursor, "3_1899000000000000030/API-CURSOR"); + // The search WALK (older posts, an X search channel) keeps its own resume point: the marker is not read. + const search = newStream(); + search.pushStdout(jsonl(1)); + assert.equal(search.pushStderr("[twitter][debug] Next 'max_id': 1899000000000000041"), undefined); + assert.equal(search.cursor, undefined); +}); + +test("stream: a walk that does not stop at known posts says once that it is skipping them", () => { + const archived = newStream(); + for (let n = 0; n <= STOP_AFTER_KNOWN + 5; n++) archived.pushStdout(jsonl(n)); + const seen = new Set(archived.finish().map((p) => p.id)); + const s = newStream({ seenIds: seen, stopAtKnown: false }); + for (let n = 0; n < STOP_AFTER_KNOWN - 1; n++) s.pushStdout(jsonl(n)); + assert.equal(s.skippingKnown, false); + s.pushStdout(jsonl(STOP_AFTER_KNOWN)); + assert.equal(s.skippingKnown, true); + assert.equal(s.stopReached, false); + // A new post after them is read as any other. + s.pushStdout(jsonl(9000)); + assert.equal(s.finish().length, 1); +}); + +test("stream: a resumed backfill whose first posts are the timeline's newest restarted from the top", async () => { + const { newestPostId, TOP_RESTART_WINDOW } = await import("./xGalleryDlFetcher"); + const id = (n: number) => String(1899000000000000000n + BigInt(n)); + // Archived: 100..500 (500 is the newest). + const seen = new Set(Array.from({ length: 401 }, (_, i) => id(100 + i))); + assert.equal(newestPostId(seen), 1899000000000000500n); + assert.equal(newestPostId(["not-a-number"]), null); + assert.equal(newestPostId([]), null); + const resumed = (ns: number[]) => { + const s = newStream({ seenIds: seen, stopAtKnown: false, topRestartAt: newestPostId(seen)! }); + for (const n of ns) s.pushStdout(jsonl(n)); + return s.restartedFromTop; + }; + // At its place: posts below everything archived, and the page it re-reads. + assert.equal(resumed([101, 100, 99, 98]), false); + // The newest archived post itself, or anything newer: the top. + assert.equal(resumed([500, 499]), true); + assert.equal(resumed([501, 500]), true); + // An old pinned post first, then the top: still the top. + assert.equal(resumed([3, 501]), true); + // Only the first page is judged. + assert.equal(resumed([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 99 - i), 500]), false); + // A walk that is no resumed backfill is not judged at all. + const sync = newStream({ seenIds: seen }); + sync.pushStdout(jsonl(501)); + assert.equal(sync.restartedFromTop, false); +}); + +// Review 1 S1: the newest archived id is over the whole corpus (a deleted newest post, or a newer +// post imported from elsewhere, hides a restart). A search-phase place says exactly what may follow it. +test("stream: after a search-phase place `3_<N>/`, a first-page post above N means the place was not honoured", async () => { + const { resumePointCeiling, TOP_RESTART_WINDOW } = await import("./xGalleryDlFetcher"); + assert.equal(resumePointCeiling("3_1899000000000000300/"), 1899000000000000300n); + assert.equal(resumePointCeiling("3_1899000000000000300/API-CURSOR"), 1899000000000000300n); + assert.equal(resumePointCeiling("2_1899000000000000300/"), 1899000000000000300n); + // The timeline phase's places say nothing of ids. + assert.equal(resumePointCeiling("1/API-CURSOR"), null); + assert.equal(resumePointCeiling("1/"), null); + assert.equal(resumePointCeiling(undefined), null); + const after = (ns: number[]) => { + const s = newStream({ stopAtKnown: false, resumeCeiling: 1899000000000000300n }); + for (const n of ns) s.pushStdout(jsonl(n)); + return s.resumeNotHonoured; + }; + assert.equal(after([300, 299, 298]), false); + assert.equal(after([301]), true); + // Far below the archive's newest, and still above the place: caught, where the top check is blind. + assert.equal(after([299, 350]), true); + assert.equal(after([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 300 - i), 301]), false); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -65,6 +65,7 @@ import { type PostMediaDownloadArgs, type PostFetchInput, type PostFetchResult, + handleFromAccountUrl, type SocialFetcher, type SocialFetcherProbe, type SearchPostFetchInput, @@ -569,13 +570,104 @@ function pause(ms: number, signal: AbortSignal): Promise<void> { // posts it did get and the archive. export const RESTART_FROM_TOP_CURSOR = "1/"; -// A watermarked or resumed run stops once this many posts IN A ROW are already -// archived (or older than the watermark). Consecutive, so a pinned old post at -// the top of the timeline does not end the run; well above one page (~20 -// tweets, plus their quotes), so re-reading the page a resumed cursor points at -// does not end it either. +// A SYNC stops once this many posts IN A ROW are already archived (or older +// than the watermark). Consecutive, so a pinned old post at the top of the +// timeline does not end the run; well above one page (~20 tweets, plus their +// quotes), so re-reading the page a resumed cursor points at does not end it +// either. +// +// NOT A HISTORY WALK'S RULE (lane x-followups). A resumed backfill has no +// watermark, and known posts are not its end: it skips them and reads on, to +// the timeline's real end, its budget or a cap (the controller passes +// `stopAtKnown: false` for it, and never clears a backfill's resume point on +// a stop at known posts — lib/timelineWalk.ts settleTimelineRun). export const STOP_AFTER_KNOWN = 100; +// THE TIMELINE WALK HAS TWO PHASES, AND THE SECOND LOGS NO CURSOR (lane +// x-followups; read from gallery-dl 1.32.9's twitter extractor, and what a +// long walk showed). gallery-dl's timeline extractor reads the +// account's timeline API first (state 1: its "Cursor: 1/<API cursor>" after +// every page) and, where that ends — a few thousand posts down — goes on by +// SEARCH (`from:<handle> max_id:<id>`, state 3 with text-tweets on, which this +// fetcher always passes; state 2 is the media search it skips). The search +// pages by max_id: after each page it rewrites the query's `max_id:` and logs +// [twitter][debug] Next 'max_id': <N> +// and never a "Cursor:" line. Reading only "Cursor:", this side kept the LAST +// TIMELINE-PHASE cursor as the resume point for the whole search phase: a +// long walk that stopped at its budget saved a point thousands of posts above +// where it stood. Its resume re-read the search phase from the top — all +// archived — and ended "caught up" after 100 known posts. +// +// The search phase's resume point is the extractor's own cursor form with no +// API cursor: `3_<N>/` makes it ask `from:<handle> max_id:<N>` afresh, which +// is exactly the request it would have made next. +const MAX_ID_LINE = /\]\[debug\]\s+Next 'max_id':\s+(\d+)\s*$/; +export const X_SEARCH_PHASE_STATE = 3; +export function searchPhaseCursor(maxId: string): string { + return `${X_SEARCH_PHASE_STATE}_${maxId}/`; +} + +// A RESUMED BACKFILL THAT STARTED AGAIN FROM THE TOP. A resume point is +// gallery-dl's and X's to honour. When the first posts a resumed backfill +// reads are at or above the NEWEST archived post, the walk is at the top of +// the timeline, not at its saved place: it stops with this sentence and keeps +// the resume point, rather than walk the whole timeline again in silence. Only +// the first page is judged (a walk that began at its place cannot reach the +// top later). +export const TOP_RESTART_WINDOW = 20; +export const X_BACKFILL_RESTARTED_FROM_TOP = + "The resumed backfill did not continue from its saved resume point: the first posts gallery-dl read are the newest " + + "of the timeline, so the walk began again from the top. Stopped at once; the resume point is kept and nothing was " + + 'walked again. Run Resume backfill again; if it says this twice, fetch-posts {"older": true} walks down from the ' + + "oldest archived post instead."; + +// A SEARCH-PHASE PLACE SAYS WHAT MAY FOLLOW IT (review 1 S1). `3_<N>/` asks +// `max_id:<N>`: every post the walk then reads is at or below N. The check +// above compares with the newest id the ARCHIVE holds, which a deleted newest +// post or a newer post imported from elsewhere moves; this one is exact. A +// first-page post above N means the place was not honoured, wherever the walk +// went instead. The timeline phase's places (`1/<API cursor>`) name no id. +export function resumePointCeiling(cursor: string | undefined): bigint | null { + const m = /^[23]_(\d+)\//.exec(cursor ?? ""); + return m ? BigInt(m[1]) : null; +} +export const X_RESUME_POINT_NOT_HONOURED = + "The walk did not continue from its saved resume point: gallery-dl read a post newer than the place it was given " + + "(a search-phase place lists only posts at or below it). Stopped at once; the resume point is kept and nothing was " + + 'walked again. Run it again; if it says this twice, fetch-posts {"older": true} walks down from the oldest ' + + "archived post instead."; + +// A TIMELINE-PHASE PLACE MAY BE AN OLD BUILD'S (review 1 S2). Before the +// search phase's marker was read, a walk that had gone on into its search +// phase saved the timeline phase's LAST cursor. Resumed, gallery-dl re-enters +// there and reads the search phase from its top: posts already archived, +// skipped one page of about twenty per request, before any new one. The place +// is not rewritten to one below the archive's oldest post: nothing in +// gallery-dl's source proves the archive is unbroken between the timeline +// phase's last post and its oldest (an older-posts walk or an imported post +// can have put the oldest there), and a rewrite would then skip what lies +// between. So the run says what it is about to do. +export const X_TIMELINE_PHASE_PLACE_NOTE = + "The saved place is in the timeline phase. If an earlier build saved it while the walk was already below what X's " + + "timeline pages back, this run first passes through posts already archived (skipped, about twenty per request) " + + "before it reaches new ones, and may spend its whole budget there; its place then moves down and the next run " + + 'continues. fetch-posts {"older": true} starts below the oldest archived post instead.'; +export function isTimelinePhasePlace(cursor: string | undefined): boolean { + return /^1\/.+/.test(cursor ?? ""); +} + +// The newest of a set of post ids, as a number (X ids grow with time); null +// when none is numeric. +export function newestPostId(ids: Iterable<string>): bigint | null { + let max: bigint | null = null; + for (const id of ids) { + if (!/^\d+$/.test(id)) continue; + const n = BigInt(id); + if (max === null || n > max) max = n; + } + return max; +} + // How long one run may take. gallery-dl waits out X's rate limit in-process // ("Waiting for 14 minutes … (rate limit)"), so a backfill spends most of its // time asleep; with progress saved as it goes, a run that hits its budget @@ -622,6 +714,12 @@ export class GalleryDlStream { // The first challenge or login-wall line on stderr (xBlockLine), if any. challengeLine?: string; stopReached = false; + // A resumed backfill whose first posts are the timeline's newest (opts.topRestartAt). + restartedFromTop = false; + // A first-page post above the search-phase place the walk was given (opts.resumeCeiling). + resumeNotHonoured = false; + // STOP_AFTER_KNOWN known posts in a row were met by a walk that does not stop at them. + skippingKnown = false; cursor?: string; // The oldest post id read this run (any post, archived or not) — a search // walk's resume point. @@ -647,6 +745,17 @@ export class GalleryDlStream { seenIds: ReadonlySet<string>; since?: string; stopAtKnown: boolean; + // The timeline walk: read the search phase's page marker ("Next + // 'max_id': N") as a resume point (searchPhaseCursor). Off for a search + // walk, whose resume point is its own (oldestId). + searchPhaseCursors?: boolean; + // A resumed backfill: the newest archived post's id. One of the first + // TOP_RESTART_WINDOW posts at or above it means the walk restarted from + // the top (X_BACKFILL_RESTARTED_FROM_TOP). + topRestartAt?: bigint; + // A walk resumed from a search-phase place: the id nothing it reads may + // exceed (resumePointCeiling). Judged on the first page, as above. + resumeCeiling?: bigint; // The account's handle, to recognise its `user` record. accountHandle?: string; onLog?: (line: string) => void; @@ -674,6 +783,13 @@ export class GalleryDlStream { this.cursor = cursor[1]; return "cursor"; } + // The search phase's page boundary: a resume point, as a cursor is. + const maxId = this.opts.searchPhaseCursors ? MAX_ID_LINE.exec(line) : null; + if (maxId) { + this.previousCursor = this.cursor; + this.cursor = searchPhaseCursor(maxId[1]); + return "cursor"; + } if (DEBUG_LINE.test(line) || !line.trim()) return undefined; const waiting = RATE_LIMIT_LINE.test(line); if (waiting) this.rateLimited = true; @@ -772,6 +888,22 @@ export class GalleryDlStream { this.accountCreatedAt = xCreatedAt({ date: user.date }); } } + if ( + this.opts.topRestartAt !== undefined && + this.distinct <= TOP_RESTART_WINDOW && + /^\d+$/.test(post.id) && + BigInt(post.id) >= this.opts.topRestartAt + ) { + this.restartedFromTop = true; + } + if ( + this.opts.resumeCeiling !== undefined && + this.distinct <= TOP_RESTART_WINDOW && + /^\d+$/.test(post.id) && + BigInt(post.id) > this.opts.resumeCeiling + ) { + this.resumeNotHonoured = true; + } const isKnown = this.opts.seenIds.has(post.id); const isOlder = !isKnown && Boolean(this.opts.since && post.createdAt <= this.opts.since); @@ -779,8 +911,9 @@ export class GalleryDlStream { if (isKnown) this.known++; else this.older++; this.knownRun++; - if (this.opts.stopAtKnown && this.knownRun >= STOP_AFTER_KNOWN) { - this.stopReached = true; + if (this.knownRun >= STOP_AFTER_KNOWN) { + if (this.opts.stopAtKnown) this.stopReached = true; + else this.skippingKnown = true; } return; } @@ -1253,6 +1386,13 @@ async function walkSearchWindows( } } +// The account an X address names (x.com/<handle>[/…]), or null: X's handle +// alphabet only, and none of the paths that are not accounts. +export function xAccountHandleOf(url: string): string | null { + const handle = handleFromAccountUrl(url); + return handle && /^[A-Za-z0-9_]{1,50}$/.test(handle) ? handle : null; +} + export const xGalleryDlFetcher: SocialFetcher = { id: "x-gallery-dl", label: "X / Twitter (gallery-dl)", @@ -1273,50 +1413,18 @@ export const xGalleryDlFetcher: SocialFetcher = { } }, - // A cheap liveness probe: read a single item. There is no free unauthenticated - // X metadata endpoint, so unlike Bluesky this genuinely spawns the binary. + // NO REQUEST (review 1 of lane x-followups, M1). The Add-channel form's + // "Fetch details" calls this from a server action, outside any job: it used + // to start gallery-dl against X for one item, as a guest, with no queue, no + // gap, no alert and no cooldown. X is asked only by the editor's jobs + // (controller/fetchPosts.ts X_ONLY_AS_A_JOB), so the handle and the + // canonical address are read off the URL — what the Playwright fallback's + // and Nitter's probes, and the form's X-search branch, already do. Whether + // the account exists is learned by the channel's first fetch, which is a job. async probe(url: string): Promise<SocialFetcherProbe> { - const bin = getPaths().galleryDlBin; - try { - const res = await execa( - bin, - buildGalleryDlArgs({ accountUrl: url, limit: 1 }), - { reject: false, timeout: 60_000 }, - ); - if (res.exitCode !== 0) { - const err = `${res.stderr ?? ""}`.trim().split("\n").slice(-3).join(" "); - return { - ok: false, - error: looksLikeAuthFailure(err) - ? `gallery-dl needs X credentials (configure cookies-from-browser): ${err}` - : err || `gallery-dl exited ${res.exitCode}`, - }; - } - const records = parseGalleryDlOutput(res.stdout ?? ""); - const first = records[0]; - const author = - first && typeof first === "object" - ? ((first.author as Record<string, unknown> | undefined) ?? undefined) - : undefined; - const handle = - (typeof author?.name === "string" ? author.name : undefined) ?? - (typeof first?.screen_name === "string" ? first.screen_name : undefined); - const nick = typeof author?.nick === "string" ? author.nick : undefined; - return { - ok: true, - name: nick ?? handle, - handle, - url: handle ? `https://x.com/${handle}` : url, - }; - } catch (err) { - const message = (err as Error).message; - return { - ok: false, - error: /ENOENT/.test(message) - ? `gallery-dl not found (looked for "${bin}"; set GALLERY_DL_BIN)` - : message, - }; - } + const handle = xAccountHandleOf(url); + if (!handle) return { ok: false, error: "Could not read an X handle from that URL" }; + return { ok: true, name: handle, handle, url: `https://x.com/${handle}` }; }, async fetch(input: PostFetchInput): Promise<PostFetchResult> { @@ -1341,12 +1449,22 @@ export const xGalleryDlFetcher: SocialFetcher = { ` (up to ${Math.round(budgetMs / 60_000)} min this run; progress is saved as it goes)`, ); + // A resumed backfill given a real resume point ("1/" asks for the top). + const resumedBackfill = input.resumedBackfill === true && Boolean(input.cursor) && input.cursor !== RESTART_FROM_TOP_CURSOR; + const newestKnown = resumedBackfill ? newestPostId(seenIds) : null; + // Any walk resumed from a search-phase place, a sync's included. + const ceiling = resumePointCeiling(input.cursor); + if (resumedBackfill && isTimelinePhasePlace(input.cursor)) onLog?.(X_TIMELINE_PHASE_PLACE_NOTE); const stream = new GalleryDlStream({ channelSlug, seenIds, since, - // A --full repair re-walks everything on purpose. + // A --full repair re-walks everything on purpose; a resumed backfill + // skips what is archived and reads on (STOP_AFTER_KNOWN). stopAtKnown: input.stopAtKnown ?? Boolean(since), + searchPhaseCursors: true, + ...(resumedBackfill && newestKnown !== null ? { topRestartAt: newestKnown } : {}), + ...(ceiling !== null ? { resumeCeiling: ceiling } : {}), onLog, }); @@ -1401,10 +1519,12 @@ export const xGalleryDlFetcher: SocialFetcher = { // if gallery-dl has not exited a few seconds later; the resume point is // the latest cursor, safe once both pipes have drained. let stoppedAtKnown = false; + let stoppedAtTop = false; + let saidSkipping = false; let drained = false; let betweenPages = false; const stopForDrain = () => { - if (drained || stoppedAtKnown) return; + if (drained || stoppedAtKnown || stoppedAtTop) return; drained = true; onLog?.("Drain requested: stopping gallery-dl at this page boundary."); subprocess.kill("SIGTERM"); @@ -1415,9 +1535,29 @@ export const xGalleryDlFetcher: SocialFetcher = { input.drain?.addEventListener("abort", onDrain, { once: true }); const stdoutDone = readLines(subprocess.stdout, (line) => { + // Once the walk is known not to be at its place, what gallery-dl still + // prints before it dies is not read: how much that is depends on the + // machine, and none of it is wanted. + if (stoppedAtTop) return; if (line.trim()) betweenPages = false; stream.pushStdout(line); - if (stream.stopReached && !stoppedAtKnown) { + if ((stream.restartedFromTop || stream.resumeNotHonoured) && !stoppedAtTop && !stoppedAtKnown) { + stoppedAtTop = true; + onLog?.( + stream.resumeNotHonoured + ? "A post newer than the saved place was read: the resume point was not honoured; stopping gallery-dl." + : "The first posts read are the timeline's newest: the resume point was not honoured; stopping gallery-dl.", + ); + subprocess.kill(); + } + if (stream.skippingKnown && !saidSkipping) { + saidSkipping = true; + onLog?.( + `${STOP_AFTER_KNOWN} already-archived posts in a row: this walk has no watermark, so it skips them and reads on ` + + "(it ends at the timeline's end, its budget or a cap).", + ); + } + if (stream.stopReached && !stoppedAtKnown && !stoppedAtTop) { stoppedAtKnown = true; onLog?.( `Reached ${STOP_AFTER_KNOWN} already-archived posts in a row — caught up; stopping gallery-dl.`, @@ -1483,7 +1623,22 @@ export const xGalleryDlFetcher: SocialFetcher = { }; } - if (stoppedAtKnown) return { posts, complete: true }; + // The walk began again from the top: its saved place is kept, and what it + // read of the top (new posts, if any) is written like any other. + if (stoppedAtTop) { + // From the top, what was read is the timeline's newest: new posts among + // them are kept. Above a search-phase place the walk is somewhere it was + // not sent: nothing of it is written (a post from there would sit apart + // from the rest of the archive, below its oldest). + return { + posts: stream.resumeNotHonoured ? [] : posts, + complete: false, + cursor: input.cursor, + error: stream.resumeNotHonoured ? X_RESUME_POINT_NOT_HONOURED : X_BACKFILL_RESTARTED_FROM_TOP, + }; + } + + if (stoppedAtKnown) return { posts, complete: true, caughtUp: true }; if (res.isCanceled || signal.aborted || res.timedOut) { onLog?.( diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -10,6 +10,7 @@ import { import { FIXTURE_FIRST_PAGE, FIXTURE_TIMELINE_OP, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_OP, fixtureTimelineBody, fixtureTrendingResponses, @@ -217,3 +218,174 @@ test("S2/N4: a capture shows the page's end only when the bottom-cursor continua // No post at all: no page to have an end. assert.equal(end([line("ExampleTrendPage", 200, { data: {} })]), false); }); + +// ── the real page's shape (lane x-followups) ─────────────────────────────── + +test("the real shape: the page's title, summary, last update and tabs are read from the page's own answer", async () => { + const { trendPageOf } = await import("./xTrendingParse"); + const real = await import("./__fixtures__/xTrendingRealShape"); + assert.deepEqual(trendPageOf(real.realPageBody()), { + title: real.INVENTED_TITLE, + summary: real.INVENTED_SUMMARY, + lastUpdatedAt: new Date(real.INVENTED_LAST_UPDATED_MS).toISOString(), + tabs: [ + { label: "Top", timelineId: real.INVENTED_TOP_TIMELINE }, + { label: "Latest", timelineId: real.INVENTED_LATEST_TIMELINE }, + ], + }); + // The accounts answer shares the page's `data` key and carries no page. + assert.equal(trendPageOf(real.realRelevantUsers().body), undefined); + assert.equal(trendPageOf(real.realStoryTopics().body), undefined); + assert.equal(trendPageOf(real.realFirstPage(real.INVENTED_FIRST).body), undefined); + assert.equal(trendPageOf({ data: null }), undefined); + assert.equal(trendPageOf("no"), undefined); + // Words are one line; a title that is not text, a tab with no id and a date that is no number are left out. + assert.deepEqual( + trendPageOf({ data: { any_key: { result: { page: { article: { title: " Two\n lines ", article_text: { text: 7 } }, last_updated_at_ms: "soon", post_timelines: [{ label: "Top" }, { label: "Latest", post_timeline: { id: "t2" } }, { label: "Again", post_timeline: { id: "t2" } }] } } } } }), + { title: "Two lines", tabs: [{ label: "Latest", timelineId: "t2" }] }, + ); +}); + +test("the real shape: a capture parses to the page's posts once each, the page, and which tab showed them", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const parsed = parseTrendingCapture(linesOf(real.realCaptureResponses()), "lib"); + // Six posts: the quoted post rides on the post quoting it, the accounts of the module are no posts. + assert.deepEqual(parsed.posts.map((p) => p.id), ["1900000000000003001", "1900000000000003002", "1900000000000003003", "1900000000000003004", "1900000000000003005", "1900000000000003006"]); + assert.equal(parsed.posts[1].quoted?.id, "1900000000000002900"); + assert.equal(parsed.page?.title, real.INVENTED_TITLE); + assert.equal(parsed.page?.summary, real.INVENTED_SUMMARY); + assert.deepEqual(parsed.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 6, postIds: parsed.posts.map((p) => p.id), pageEnd: false }]); + assert.deepEqual(new Set(Object.values(parsed.tabs)), new Set(["Top"])); + assert.equal(Object.keys(parsed.tabs).length, 6); + assert.deepEqual( + parsed.operations.map((o) => [o.op, o.responses, o.tweets]), + [["AiTrendByRestId", 1, 0], ["DataSaverMode", 1, 0], ["GenericTimelineById", 3, 6], ["TrendRelevantUsers", 1, 0], ["useStoryTopicQuery", 1, 0], ["ViewerBadgeCounts", 1, 0]], + ); + assert.deepEqual(parsed.media, { + "1900000000000003001": { count: 1, kinds: ["image"] }, + "1900000000000003003": { count: 1, kinds: ["video"] }, + "1900000000000003004": { count: 1, kinds: ["gif"] }, + }); + // A capture with no page answer: posts all the same, no page, a timeline that is no known tab. + const bare = parseTrendingCapture(linesOf([real.realFirstPage(real.INVENTED_FIRST)]), "lib"); + assert.equal(bare.page, undefined); + assert.deepEqual(bare.timelines.map((t) => [t.timelineId, t.tab, t.posts, t.pageEnd]), [[real.INVENTED_TOP_TIMELINE, undefined, 3, false]]); + assert.deepEqual(bare.tabs, {}); + // The old fixture names no timeline: one untagged timeline. + assert.deepEqual(parseTrendingCapture(linesOf(fixtureTrendingResponses().load), "lib").timelines.map((t) => t.timelineId), [FIXTURE_TOP_TIMELINE]); +}); + +test("the real shape: the bottom cursor is read from a cursor entry AND from TimelineReplaceEntry", async () => { + const { timelineShapeOf, requestVariablesOf } = await import("./xTrendingParse"); + const real = await import("./__fixtures__/xTrendingRealShape"); + // The first answer: a cursor entry (the top cursor beside it is not the bottom's). + assert.deepEqual(timelineShapeOf(real.realFirstPage(real.INVENTED_FIRST).body), { instructions: true, bottom: real.realBottomCursor(1) }); + // A later answer: no cursor entry, two replacements. + const later = real.realContinuation(real.INVENTED_SECOND, { n: 2 }); + assert.deepEqual(timelineShapeOf(later.body), { instructions: true, bottom: real.realBottomCursor(2) }); + assert.deepEqual(requestVariablesOf(later.url), { cursor: real.realBottomCursor(1), timelineId: real.INVENTED_TOP_TIMELINE }); + assert.deepEqual(requestVariablesOf(real.realFirstPage([]).url), { timelineId: real.INVENTED_TOP_TIMELINE }); + // A replacement named only by the entry it replaces (no cursorType on the new entry) is still the bottom's. + assert.deepEqual( + timelineShapeOf({ instructions: [{ type: "TimelineReplaceEntry", entry_id_to_replace: "cursor-bottom-1", entry: { entryId: "x", content: { value: "next" } } }] }), + { instructions: true, bottom: "next" }, + ); + // A replacement of the TOP cursor alone names no bottom. + assert.deepEqual( + timelineShapeOf({ instructions: [{ type: "TimelineReplaceEntry", entry_id_to_replace: "cursor-top-9", entry: { entryId: "cursor-top-9", content: { cursorType: "Top", value: "up" } } }] }), + { instructions: true }, + ); + // The accounts answer has instructions and no cursor. + assert.deepEqual(timelineShapeOf(real.realRelevantUsers().body), { instructions: true }); +}); + +test("the real shape: a capped read asserts nothing; the bottom continuation that brings nothing new is the end; a failed last answer asserts nothing", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const end = (responses: Array<{ url: string; status: number; body?: unknown }>) => parseTrendingCapture(linesOf(responses), "lib").pageEnd; + // A CAPPED READ (what the first real read was: it stopped at its post cap): every continuation brought new posts. + assert.equal(end(real.realCaptureResponses()), false); + assert.equal(end(real.realCaptureResponses({ later: [] })), false); + // The continuation from the last bottom cursor (carried by a TimelineReplaceEntry) brings no post… + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4 })]), true); + // …or only posts already shown. + assert.equal(end([...real.realCaptureResponses(), real.realContinuation(real.INVENTED_THIRD, { n: 4 })]), true); + // It must continue from the bottom cursor of the answer BEFORE it: the first answer's (an entry) is stale by then. + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realBottomCursor(1) })]), false); + assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realTopCursor(3) })]), false); + // A FAILED LAST ANSWER: a 429, a body not kept, GraphQL errors, no instructions. + const last = real.realContinuation([], { n: 4 }); + assert.equal(end([...real.realCaptureResponses(), { ...last, status: 429 }]), false); + assert.equal(end([...real.realCaptureResponses(), { url: last.url, status: 200 }]), false); + assert.equal(end([...real.realCaptureResponses(), { ...last, body: { ...(last.body as object), errors: [{ message: "Timeout" }] } }]), false); + assert.equal(end([...real.realCaptureResponses(), { ...last, body: { data: { timeline: {} } } }]), false); + // A failed answer BEFORE the end, then a clean end: the capture still cannot tell. + assert.equal(end([...real.realCaptureResponses(), { ...last, status: 500 }, last]), false); + // One of the page's small answers failing is the page's failure too. + assert.equal(end([...real.realCaptureResponses(), last, { url: real.realStoryTopics().url, status: 500 }]), false); +}); + +test("the real shape: two tabs in one capture show no end, and each post is the tab's that showed it first", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const latest = { timelineId: real.INVENTED_LATEST_TIMELINE }; + const responses = [ + ...real.realCaptureResponses({ later: [] }), + real.realContinuation([], { n: 2 }), + // The other tab: a post of its own and one the first tab showed. + real.realFirstPage([real.INVENTED_SECOND[0], real.INVENTED_FIRST[0]], { ...latest, bottom: "latest-1" }), + real.realContinuation([], { ...latest, asked: "latest-1", bottom: "latest-2" }), + ]; + const parsed = parseTrendingCapture(linesOf(responses), "lib"); + assert.equal(parsed.pageEnd, false); + // PER TIMELINE: each tab's own posts in its own order (a post both show is in both), and each tab's own end. + assert.deepEqual(parsed.timelines, [ + { timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 3, postIds: ["1900000000000003001", "1900000000000003002", "1900000000000003003"], pageEnd: true }, + { timelineId: real.INVENTED_LATEST_TIMELINE, tab: "Latest", posts: 1, postIds: ["1900000000000003004", "1900000000000003001"], pageEnd: true }, + ]); + // One tab at its end and the other capped: said of each by itself. + const capped = parseTrendingCapture(linesOf(responses.slice(0, -1)), "lib"); + assert.deepEqual(capped.timelines.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + // A continuation that brings only posts the OTHER tab showed is not this tab's end: they are new to it. + const borrowed = [...responses.slice(0, -1), real.realContinuation([real.INVENTED_FIRST[1]], { ...latest, asked: "latest-1", bottom: "latest-2" })]; + assert.deepEqual(parseTrendingCapture(linesOf(borrowed), "lib").timelines.map((t) => [t.tab, t.pageEnd]), [["Top", true], ["Latest", false]]); + // A failed answer anywhere: neither tab shows an end. + const failed = [...responses, { url: real.realStoryTopics().url, status: 500 }]; + assert.deepEqual(parseTrendingCapture(linesOf(failed), "lib").timelines.map((t) => t.pageEnd), [false, false]); + assert.equal(parsed.tabs["1900000000000003001"], "Top"); + assert.equal(parsed.tabs["1900000000000003004"], "Latest"); + // Each tab alone, read to its end, shows it: the continuation is its own timeline's. + assert.equal(parseTrendingCapture(linesOf(responses.slice(0, -2)), "lib").pageEnd, true); + // A continuation carrying ANOTHER timeline's bottom cursor is not this one's. + const crossed = [real.realFirstPage(real.INVENTED_FIRST), real.realContinuation([], { ...latest, asked: real.realBottomCursor(1) })]; + assert.equal(parseTrendingCapture(linesOf(crossed), "lib").pageEnd, false); +}); + +// Review 3 S8: THE PARSER'S OP FILTER. Every answer of an operation not in +// X_TRENDING_IGNORED_OPS that lists posts is the page's — so after a press +// took the page elsewhere, another page's timeline would be read as this +// topic's. `pageTabsOnly` (the controller sets it when a tab was abandoned, +// "the page changed") ingests only the timelines the trend answer names as +// its own tabs; the other answers stay counted in the capture, unread. +test("review 3 S8: after the page changed, only the trend answer's own timelines are ingested; the others stay in the capture", async () => { + const real = await import("./__fixtures__/xTrendingRealShape"); + const stray: typeof real.INVENTED_SECOND = [{ id: "1900000000000003901", handle: "elsewhere", text: "A post of another page." }]; + const responses = [ + real.realPageAnswer(), + real.realFirstPage(real.INVENTED_FIRST), + // Another trend's timeline, and a home-like answer naming no timeline. + real.realFirstPage(stray, { timelineId: "VGltZWxpbmU6Zml4dHVyZS1lbHNld2hlcmU=" }), + { ...real.realFirstPage([{ id: "1900000000000003902", handle: "home", text: "A home post." }]), url: "https://x.com/i/api/graphql/abc/HomeLatestTimeline?variables=%7B%22count%22%3A20%7D" }, + ]; + const all = parseTrendingCapture(linesOf(responses), "lib"); + assert.ok(all.posts.some((p) => p.id === "1900000000000003901"), "without the option every listing answer is read (the filter is by operation only)"); + const own = parseTrendingCapture(linesOf(responses), "lib", { pageTabsOnly: true }); + const ids = own.posts.map((p) => p.id); + assert.ok(!ids.includes("1900000000000003901") && !ids.includes("1900000000000003902"), ids.join(",")); + assert.ok(ids.includes(real.INVENTED_FIRST[0].id)); + assert.deepEqual(own.timelines.map((t) => t.timelineId), [real.INVENTED_TOP_TIMELINE]); + // The capture still says what it holds: every answer counted. + assert.equal(own.responses, all.responses); + assert.deepEqual(own.operations.map((o) => [o.op, o.responses]), all.operations.map((o) => [o.op, o.responses])); + // With no trend answer to name the tabs, nothing is the page's own: nothing is ingested. + const none = parseTrendingCapture(linesOf(responses.slice(1)), "lib", { pageTabsOnly: true }); + assert.equal(none.posts.length, 0); +}); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -15,6 +15,17 @@ // context, not another post of the page; and it skips promoted entries. A few // operations known to belong to other surfaces of the app are ignored by name. // +// WHAT THE FIRST REAL READ SHOWED (lane x-followups; the shapes are in +// __fixtures__/xTrendingRealShape.ts, with invented data): one answer carries +// the page itself — X's title and summary for the trend, when X last updated +// them, and the page's TABS, each a label and the id of the timeline it +// lists (trendPageOf) — and the posts come from a timeline operation whose +// request names that timeline id and, after the first, the cursor it +// continues from. The first timeline answer ends with cursor ENTRIES; every +// later one carries its new cursors in TimelineReplaceEntry instructions +// (timelineShapeOf reads both). The page is found by its SHAPE, the timeline +// by the posts it lists: no operation is matched by name here either. +// // Pure but for readCaptureLines (node:fs). import { readFile } from "node:fs/promises"; @@ -238,24 +249,100 @@ export function mediaSourcesInCapture(lines: ReadonlyArray<TrendingCaptureLine>) 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 { +// What a request asked for: the `variables` of the GraphQL URL. `cursor` is the +// cursor it continues from, `timelineId` the timeline it lists (a trending +// page's tab). Empty when the URL has none or cannot be read. +export function requestVariablesOf(url: string): { cursor?: string; timelineId?: string } { 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; + const v = raw ? (JSON.parse(raw) as { cursor?: unknown; timelineId?: unknown } | null) : null; + const text = (x: unknown) => (typeof x === "string" && x ? x : undefined); + const cursor = text(v?.cursor); + const timelineId = text(v?.timelineId); + return { ...(cursor ? { cursor } : {}), ...(timelineId ? { timelineId } : {}) }; } catch { - return undefined; + return {}; + } +} + +// The cursor a request carried. Undefined when the URL has none or cannot be read. +export function requestCursorOf(url: string): string | undefined { + return requestVariablesOf(url).cursor; +} + +// ONE TAB OF A TRENDING PAGE: its label as X shows it and the timeline it lists. +export type TrendingPageTab = { label: string; timelineId: string }; + +// WHAT THE PAGE SAYS OF ITSELF: X's title and summary for the trend (X's own +// words, written by X), when X last updated them, and the page's tabs. +export type TrendingPageInfo = { + title?: string; + summary?: string; + lastUpdatedAt?: string; + tabs: TrendingPageTab[]; +}; + +const oneLine = (v: unknown): string | undefined => { + if (typeof v !== "string") return undefined; + const text = v.replace(/\s+/g, " ").trim(); + return text || undefined; +}; + +// The page, from one answer's body: `data.<any>.result.page` holding an +// `article` (title, article_text.text) and/or `post_timelines` (label, +// post_timeline.id). Undefined for an answer that is not the page — the +// answers that share its `data` key but carry no `page` included. +export function trendPageOf(body: unknown): TrendingPageInfo | undefined { + const data = obj(obj(body)?.data); + if (!data) return undefined; + for (const value of Object.values(data)) { + const page = obj(obj(obj(value)?.result)?.page); + if (!page) continue; + const article = obj(page.article); + const title = oneLine(article?.title); + const summary = oneLine(obj(article?.article_text)?.text); + const tabs: TrendingPageTab[] = []; + for (const item of Array.isArray(page.post_timelines) ? page.post_timelines : []) { + const label = oneLine(obj(item)?.label); + const timelineId = obj(obj(item)?.post_timeline)?.id; + if (!label || typeof timelineId !== "string" || !timelineId) continue; + if (!tabs.some((t) => t.timelineId === timelineId)) tabs.push({ label, timelineId }); + } + if (!title && !summary && tabs.length === 0) continue; + const ms = page.last_updated_at_ms; + const at = typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? new Date(ms) : undefined; + return { + ...(title ? { title } : {}), + ...(summary ? { summary } : {}), + ...(at && !Number.isNaN(at.getTime()) ? { lastUpdatedAt: at.toISOString() } : {}), + tabs, + }; } + 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). +// +// A cursor is read wherever the answer keeps one, in the two places the real +// page uses and any other: +// - a cursor ENTRY among a TimelineAddEntries' entries (the first answer of +// a timeline): `{entryId: "cursor-bottom-…", content: {cursorType: +// "Bottom", value}}`; +// - a TimelineReplaceEntry instruction (every later answer, which lists no +// cursor entry): `{type: "TimelineReplaceEntry", entry_id_to_replace: +// "cursor-bottom-…", entry: {entryId, content: {cursorType: "Bottom", +// value}}}` — beside one for the top cursor, which is not the bottom's. +// A cursor of a MODULE inside the timeline (a "show more" of a carousel) is +// not the timeline's: only `cursorType: "Bottom"`, or a `cursor-bottom` id, is. export function timelineShapeOf(payload: unknown): { instructions: boolean; bottom?: string } { let instructions = false; let bottom: string | undefined; const seen = new Set<unknown>(); + const cursorOf = (content: Record<string, unknown> | undefined): string | undefined => { + const v = content?.value ?? obj(content?.itemContent)?.value; + return typeof v === "string" && v ? v : undefined; + }; const visit = (node: unknown): void => { if (!node || typeof node !== "object" || seen.has(node)) return; seen.add(node); @@ -268,9 +355,13 @@ export function timelineShapeOf(payload: unknown): { instructions: boolean; bott 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; + const v = cursorOf(obj(rec.content)); + if (v) bottom = v; + } + // The replacement of the bottom cursor's entry, named by the entry it replaces. + if (rec.type === "TimelineReplaceEntry" && typeof rec.entry_id_to_replace === "string" && rec.entry_id_to_replace.startsWith("cursor-bottom")) { + const v = cursorOf(obj(obj(rec.entry)?.content)); + if (v) bottom = v; } for (const child of Object.values(rec)) visit(child); }; @@ -301,22 +392,67 @@ export type ParsedTrendingCapture = { // 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". + // + // PER TIMELINE (lane x-followups): a trending page has tabs, each its own + // timeline, and one read may list two of them (Top, then Latest). The rule + // above is asked of EACH timeline by itself (`timelines[].pageEnd`): its own + // last answer, continuing from its own previous bottom cursor, bringing no + // post that timeline had not shown. What one tab no longer shows says + // nothing of the other. `pageEnd` here is the one timeline's when the + // capture lists exactly one, and false for a capture that lists two. pageEnd: boolean; + // What the page says of itself (trendPageOf), when an answer carried it. + page?: TrendingPageInfo; + // The timelines whose posts the capture lists, first listed first: the + // timeline id its requests named (absent when they named none), the tab of + // the page it is (when the page names that id), and how many of the page's + // posts it showed first. + // `postIds`: every post that timeline listed, in its own order (a post two + // tabs show is in both); `pageEnd`: the capture shows that timeline's end. + timelines: Array<{ timelineId?: string; tab?: string; posts: number; postIds: string[]; pageEnd: boolean }>; + // Post id → the label of the tab that showed it first, for the posts whose + // timeline is one of the page's tabs. + tabs: Record<string, string>; }; // The capture, parsed. `channelSlug` is the library's (a Post names its channel). +// +// WHICH ANSWERS ARE THE PAGE'S: every answer of an operation that is not in +// X_TRENDING_IGNORED_OPS and lists posts. `pageTabsOnly` (review 3 S8; the +// controller sets it when a tab of the read was abandoned because the page +// changed) narrows that to the timelines the trend answer names as its own +// tabs: an answer for any other timeline, or naming none, came from wherever +// the page went, and is counted in the capture (operations, responses, +// bytes) but not read. With no trend answer in the capture, no timeline is +// the page's own and nothing is read. export function parseTrendingCapture( lines: ReadonlyArray<TrendingCaptureLine>, channelSlug: string, + opts: { pageTabsOnly?: boolean } = {}, ): ParsedTrendingCapture { + const own = opts.pageTabsOnly + ? new Set( + (lines + .filter((l) => !X_TRENDING_IGNORED_OPS.includes(l.op) && l.body !== undefined && l.status >= 200 && l.status < 300) + .map((l) => trendPageOf(l.body)) + .find((pg) => pg !== undefined)?.tabs ?? [] + ).map((t) => t.timelineId), + ) + : null; const raws: XTweetRaw[] = []; 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 }> = []; + // Per answer of the page's own operations, in order: its operation, the + // timeline it asked for, and how many posts it brought that no earlier + // answer had. + const answers: Array<{ op: string; timelineId?: string; fresh: number; freshOfTimeline: number; asked?: string; bottom?: string; instructions: boolean }> = []; + // Timeline id ("" when a request named none) → the posts it listed, in order. + const listedBy = new Map<string, string[]>(); const seenIds = new Set<string>(); + // Post id → the timeline id of the answer that showed it first. + const firstTimeline = new Map<string, string>(); + let page: TrendingPageInfo | undefined; let failed = false; for (const line of lines) { const op = ops.get(line.op) ?? { op: line.op, responses: 0, bytes: 0, statuses: [], tweets: 0 }; @@ -333,38 +469,87 @@ export function parseTrendingCapture( // 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; + // The page itself: the first answer that carries it. + page ??= trendPageOf(line.body); + const asked = requestVariablesOf(line.url); + // Not one of the page's own timelines, after the page changed: kept, unread. + if (own && !(asked.timelineId !== undefined && own.has(asked.timelineId))) continue; const found = collectTimelineTweets(line.body); op.tweets += found.length; let fresh = 0; + let freshOfTimeline = 0; + const key = asked.timelineId ?? ""; for (const raw of found) { raws.push(raw); const id = xIdOf(raw); + if (id) { + const listed = listedBy.get(key) ?? []; + listedBy.set(key, listed); + if (!listed.includes(id)) { + listed.push(id); + freshOfTimeline++; + } + } if (id && !seenIds.has(id)) { seenIds.add(id); fresh++; + if (asked.timelineId) firstTimeline.set(id, asked.timelineId); } 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 } : {}) }); + answers.push({ + op: line.op, + fresh, + freshOfTimeline, + instructions: shape.instructions, + ...(asked.timelineId ? { timelineId: asked.timelineId } : {}), + ...(asked.cursor ? { asked: asked.cursor } : {}), + ...(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 timelineIds = [...new Set(listing.map((a) => a.timelineId).filter((id): id is string => id !== undefined))]; + // One timeline's end: its own last answer continues from its own previous + // bottom cursor (the same operation) and brought nothing that timeline had + // not shown. + const endOf = (key: string): boolean => { + const own = listing.filter((a) => (a.timelineId ?? "") === key); + const last = own.at(-1); + const before = last ? own.slice(0, -1).filter((a) => a.op === last.op).at(-1) : undefined; + return !failed && last !== undefined && before?.bottom !== undefined && last.asked === before.bottom && last.freshOfTimeline === 0; + }; + const keys = [...new Set(listing.map((a) => a.timelineId ?? ""))]; + const pageEnd = keys.length === 1 && endOf(keys[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]; + // Which tab showed what: the page's tabs by the timeline id they list. + const labelOf = new Map((page?.tabs ?? []).map((t) => [t.timelineId, t.label])); + const tabs: Record<string, string> = {}; + const shownFirst = new Map<string, number>(); + for (const p of posts) { + const timelineId = firstTimeline.get(p.id); + const label = timelineId ? labelOf.get(timelineId) : undefined; + if (label) tabs[p.id] = label; + if (timelineId) shownFirst.set(timelineId, (shownFirst.get(timelineId) ?? 0) + 1); + } + const untagged = posts.length - [...shownFirst.values()].reduce((a, n) => a + n, 0); + const isPost = new Set(posts.map((p) => p.id)); + const listedOf = (key: string) => (listedBy.get(key) ?? []).filter((id) => isPost.has(id)); + const timelines: ParsedTrendingCapture["timelines"] = timelineIds.map((timelineId) => ({ + timelineId, + ...(labelOf.get(timelineId) ? { tab: labelOf.get(timelineId)! } : {}), + posts: shownFirst.get(timelineId) ?? 0, + postIds: listedOf(timelineId), + pageEnd: endOf(timelineId), + })); + if (untagged > 0 || (timelines.length === 0 && listing.length > 0)) { + timelines.push({ posts: untagged, postIds: listedOf(""), pageEnd: keys.includes("") && endOf("") }); + } return { posts, media: kept, @@ -372,6 +557,9 @@ export function parseTrendingCapture( responses: lines.length, bytes, pageEnd, + ...(page ? { page } : {}), + timelines, + tabs, }; } diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts @@ -12,8 +12,13 @@ import { fakeTrendingPage, type FakeTrendingPage } from "./fakeXProfileBrowser"; import { bounded, isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead"; import { readCaptureLines } from "./xTrendingParse"; import { + FIXTURE_LATEST_PAGE, + FIXTURE_LATEST_TIMELINE, FIXTURE_TIMELINE_OP, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, + fixtureLatestFirst, + fixtureTwoTabResponses, fixtureTimelineBody, fixtureTrendingResponses, } from "./__fixtures__/xTrendingCapture"; @@ -26,7 +31,16 @@ after(() => rmSync(TMP, { recursive: true, force: true })); let dirs = 0; async function read( trending: FakeTrendingPage, - over: { scrolls?: number; posts?: number; signal?: AbortSignal } = {}, + // One tab unless a test asks for both: the page's other tab is R3's tests' (below). + over: { + scrolls?: number; + posts?: number; + signal?: AbortSignal; + tabs?: Array<"top" | "latest">; + pause?: (ms: number) => Promise<void>; + now?: () => number; + timeouts?: { call?: number; read?: number }; + } = {}, ): Promise<{ result: TrendingPageRead; dir: string; closed: number; pauses: number[]; log: string[] }> { const dir = path.join(TMP, `read-${++dirs}`); const pauses: number[] = []; @@ -38,11 +52,16 @@ async function read( dir, openPage: async () => ({ page, close: async () => void closed++ }), limits: { scrolls: over.scrolls ?? 8, posts: over.posts ?? 60 }, + tabs: over.tabs ?? ["top"], pauseMs: () => 7_000, - pause: async (ms) => void pauses.push(ms), + pause: async (ms) => { + pauses.push(ms); + if (over.pause) await over.pause(ms); + }, signal: over.signal ?? new AbortController().signal, onLog: (l) => log.push(l), - now: () => Date.parse("2026-11-17T10:00:00.000Z"), + now: over.now ?? (() => Date.parse("2026-11-17T10:00:00.000Z")), + ...(over.timeouts ? { timeouts: over.timeouts } : {}), }); return { result, dir, closed, pauses, log }; } @@ -61,6 +80,7 @@ test("a read keeps every GraphQL answer raw and a screenshot, and stops after tw statuses: { "200": 4 }, tweets: 4, shot: true, + tabs: [{ asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }], }); assert.ok(result.bytes > 0); assert.equal(closed, 1); @@ -547,3 +567,184 @@ test("kill ends the browser's own process when its pid checks out; else it says await mac.kill!(); assert.ok(log3.some((l) => /not killed \(finding the browser's process is Linux-only\); closing it again instead/.test(l))); }); + +// ── added scope R3: both tabs in one read ────────────────────────────────── + +const BOTH: Array<"top" | "latest"> = ["top", "latest"]; + +test("R3: the deadline covers what the read may do: 6 min for one tab at 20 scrolls, 10 for both, 18 at the maximum", async () => { + const { readDeadlineMs, READ_DEADLINE_MS, TAB_WAIT_MS } = await import("./xTrendingRead"); + assert.equal(readDeadlineMs({ scrolls: 20 }, 1), 6 * 60_000); + assert.equal(READ_DEADLINE_MS, 6 * 60_000); + assert.equal(readDeadlineMs({ scrolls: 20 }, 2), 10 * 60_000); + assert.equal(readDeadlineMs({ scrolls: 40 }, 2), 18 * 60_000); + assert.equal(TAB_WAIT_MS, 20_000); +}); + +test("R3: after Top is read to its stop the page's Latest tab is pressed and read under the same caps, into the one capture", async () => { + const { result, dir, pauses, log } = await read(fixtureTwoTabResponses(), { tabs: BOTH }); + assert.equal(result.stop, "idle"); + assert.deepEqual(result.tabs, [ + { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }, + { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 2, posts: 3, stop: "idle" }, + ]); + assert.equal(result.scrolls, 5); + // Five distinct posts: two of Latest's three are Top's too. + assert.equal(result.tweets, 5); + assert.ok(log.includes('Pressed the page\'s "Latest" tab.')); + // One capture: Top's answers, then Latest's, each request naming its own timeline. + const lines = await readCaptureLines(path.join(dir, "responses.jsonl")); + const timelines = lines.filter((l) => l.op === FIXTURE_TIMELINE_OP).map((l) => JSON.parse(new URL(l.url).searchParams.get("variables")!).timelineId); + assert.deepEqual(timelines, [FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_TOP_TIMELINE, FIXTURE_LATEST_TIMELINE, FIXTURE_LATEST_TIMELINE]); + assert.equal(readFileSync(path.join(dir, "page-latest.png")).subarray(1, 4).toString(), "PNG"); + assert.equal(result.tabShot, true); + // Never two contacts in a row: a wait after the load, after every scroll, and after the press. + assert.ok(pauses.filter((ms) => ms === 7_000).length >= 1 + 5 + 1); +}); + +test("R3: a Latest tab the page does not show, or one whose press brings nothing, is \"not read\" with its reason — Top's read stands", async () => { + const hidden = fixtureTwoTabResponses(); + hidden.tabs.Latest.hidden = true; + const a = await read(hidden, { tabs: BOTH }); + assert.equal(a.result.stop, "idle"); + assert.deepEqual(a.result.tabs[1], { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 0, posts: 0, stop: "not-read", why: 'the page shows no tab named "Latest" in its tab list' }); + assert.deepEqual(a.result.tabs[0], { asked: "top", tab: "Top", timelineId: FIXTURE_TOP_TIMELINE, scrolls: 3, posts: 4, stop: "idle" }); + // Pressed, and the page asks nothing for it. + const silent = fixtureTwoTabResponses(); + silent.tabs.Latest = {}; + const b = await read(silent, { tabs: BOTH }); + assert.equal(b.result.stop, "idle"); + assert.equal(b.result.tabs[1].stop, "not-read"); + assert.equal(b.result.tabs[1].why, 'pressing "Latest" brought no answer for its timeline within 20 s'); + assert.equal(b.result.scrolls, 3, "no scroll followed a press that brought nothing"); + // The page's own answer names no tabs at all (it was not fetched). + const noPage = fixtureTwoTabResponses(); + noPage.load = noPage.load.slice(1); + const c = await read(noPage, { tabs: BOTH }); + assert.equal(c.result.tabs[1].stop, "not-read"); + assert.match(c.result.tabs[1].why ?? "", /page's own answer, which names its tabs and their timelines, was not among what it fetched/); + assert.equal(c.result.tabs[0].tab, undefined); + assert.equal(c.result.tabs[0].posts, 4); +}); + +test("R3: a 429 on Latest stops the whole read; a 429 on Top means Latest is never pressed", async () => { + const limited = fixtureTwoTabResponses(); + limited.tabs.Latest.scrolls = [[{ url: fixtureLatestFirst([]).url, status: 429, text: "" }]]; + const a = await read(limited, { tabs: BOTH }); + assert.equal(a.result.stop, "rate-limit"); + assert.equal(a.result.tabs[1].stop, "rate-limit"); + assert.equal(a.result.tabs[1].scrolls, 1); + assert.equal(a.result.tabs[0].stop, "idle"); + const onTop = fixtureTwoTabResponses(); + onTop.scrolls = [[{ url: fixtureTwoTabResponses().load[1].url, status: 429, text: "" }]]; + const b = await read(onTop, { tabs: BOTH }); + assert.equal(b.result.stop, "rate-limit"); + assert.equal(b.result.tabs.length, 1); + assert.ok(!b.log.some((l) => /Pressed/.test(l))); + assert.equal(existsSync(path.join(b.dir, "page-latest.png")), false); +}); + +test("R3: each tab has the full caps; asked for Latest alone, Top is not scrolled", async () => { + const many = fixtureTwoTabResponses(FIXTURE_LATEST_PAGE); + // Top stops at a post cap of 4 after its first scroll; Latest then has its own count of 3 and reads on. + const capped = await read(many, { tabs: BOTH, posts: 4 }); + assert.deepEqual(capped.result.tabs.map((t) => [t.asked, t.stop, t.posts]), [["top", "post-cap", 4], ["latest", "idle", 3]]); + const only = await read(fixtureTwoTabResponses(), { tabs: ["latest"] }); + assert.deepEqual(only.result.tabs.map((t) => [t.asked, t.stop, t.scrolls]), [["top", "not-asked", 0], ["latest", "idle", 2]]); + // What the page loaded of Top by itself is in the capture all the same. + assert.equal(only.result.tabs[0].posts, 3); +}); + +// ── review 2 (lane x-followups): S1, S2, S3 ─────────────────────────────── + +test("S1: Latest is pressed only as a TAB inside the page's tab list, by its exact name — never a link or a button named like it", async () => { + // A link named exactly "Latest", and no tab: nothing is pressed. + const linkOnly = fixtureTwoTabResponses(); + linkOnly.tabs.Latest.role = "link"; + const a = await read(linkOnly, { tabs: BOTH }); + assert.equal(a.result.stop, "idle"); + assert.deepEqual(a.result.tabs[1], { asked: "latest", tab: "Latest", timelineId: FIXTURE_LATEST_TIMELINE, scrolls: 0, posts: 0, stop: "not-read", why: 'the page shows no tab named "Latest" in its tab list' }); + assert.ok(!a.log.some((l) => /Pressed/.test(l))); + assert.equal(a.result.scrolls, 3, "nothing of Latest was scrolled"); + // A button: the same. + const button = fixtureTwoTabResponses(); + button.tabs.Latest.role = "button"; + assert.equal((await read(button, { tabs: BOTH })).result.tabs[1].stop, "not-read"); + // A tab, but outside the page's tab list: the same. + const loose = fixtureTwoTabResponses(); + loose.tabs.Latest.outsideTablist = true; + assert.equal((await read(loose, { tabs: BOTH })).result.tabs[1].why, 'the page shows no tab named "Latest" in its tab list'); +}); + +test("S1: a press that leaves the trending page stops the read at once and closes the browser: Top read, Latest not read, the page changed", async () => { + const away = fixtureTwoTabResponses(); + away.tabs.Latest.navigatesTo = "https://x.com/search?q=example&f=live"; + const r = await read(away, { tabs: BOTH }); + assert.equal(r.result.stop, "idle", "Top's read stands"); + assert.equal(r.result.tabs[0].stop, "idle"); + assert.deepEqual([r.result.tabs[1].stop, r.result.tabs[1].why, r.result.tabs[1].scrolls], ["not-read", "the page changed", 0]); + assert.equal(r.result.scrolls, 3, "no scroll after the page changed"); + assert.equal(r.result.tabShot, undefined, "nothing more is done with the page"); + assert.equal(r.closed, 1); +}); + +test("S2: a press that fails — the click throws, or the page does not answer the look-up — is \"not read\" with why; Top stands", async () => { + const throws = fixtureTwoTabResponses(); + throws.tabs.Latest.clickError = "Element is not visible"; + const a = await read(throws, { tabs: BOTH }); + assert.equal(a.result.stop, "idle"); + assert.equal(a.result.tabs[1].stop, "not-read"); + assert.match(a.result.tabs[1].why ?? "", /^pressing "Latest" failed: Element is not visible/); + assert.equal(a.result.error, undefined); + // The look-up never answers: the page call's deadline, caught. + const hangs = fixtureTwoTabResponses(); + hangs.tabs.Latest.countHangs = true; + const b = await read(hangs, { tabs: BOTH, timeouts: { call: 50 } }); + assert.equal(b.result.stop, "idle"); + assert.equal(b.result.tabs[1].stop, "not-read"); + assert.match(b.result.tabs[1].why ?? "", /^pressing "Latest" failed: the page did not answer within 0 s \(looking for the "Latest" tab\)/); + assert.equal(b.closed, 1); +}); + +test("S2: the read's deadline during Latest keeps Top's result: Latest stopped at the deadline, with what it had", async () => { + // Latest scrolls without end; the read's deadline falls in the middle of it. + const endless = fixtureTwoTabResponses(); + endless.tabs.Latest.scrolls = Array.from({ length: 50 }, (_, i) => [fixtureLatestFirst([{ id: `19000000000000031${String(i).padStart(2, "0")}`, handle: `l_${i}`, text: `Latest ${i}.` }])]); + let clock = 0; + const r = await read(endless, { + tabs: BOTH, + scrolls: 40, + posts: 400, + // Each pause is a second of the read's clock; the deadline is 20 of them. + pause: async () => { + clock += 1; + await new Promise((res) => setTimeout(res, 5)); + }, + timeouts: { read: 120 }, + }); + assert.ok(clock > 0); + assert.equal(r.result.tabs[0].stop, "idle"); + assert.equal(r.result.tabs[1].stop, "deadline"); + assert.ok(r.result.tabs[1].posts > 0, "what Latest had is kept"); + assert.equal(r.result.stop, "idle", "the read is Top's, not a failure"); + assert.equal(r.result.error, undefined); +}); + +test("S3: the wait for Latest's answer is bounded by its own 20 s wall clock, each step's settle counted", async () => { + const silent = fixtureTwoTabResponses(); + silent.tabs.Latest = {}; + // Every pause takes 5 s of the clock: the wait ends after four steps, not forty. + let t = Date.parse("2026-11-17T10:00:00.000Z"); + let steps = 0; + const r = await read(silent, { + tabs: BOTH, + now: () => t, + pause: async (ms) => { + if (ms === 500) steps++; + t += 5_000; + }, + }); + assert.equal(r.result.tabs[1].stop, "not-read"); + assert.equal(r.result.tabs[1].why, 'pressing "Latest" brought no answer for its timeline within 20 s'); + assert.ok(steps <= 4, `waited ${steps} steps`); +}); diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts @@ -22,12 +22,24 @@ // NOTHING HERE WAITS FOREVER (review 1). Every call into the page is raced // against a deadline — the load 75 s, a scroll, a look at the address or a // screenshot 20 s each, closing the browser 10 s — and against the job's -// cancel; and the whole read against READ_DEADLINE_MS (6 minutes: twenty -// scrolls at the longest gap, twice over). A page that stops answering ends +// cancel; and the whole read against its deadline (readDeadlineMs: two +// minutes, and twelve seconds — the longest gap and a page call — for every +// scroll each tab may make). A page that stops answering ends // the read with a sentence, what was captured kept, and the browser is closed // (killed, when closing does not answer) so the profile is free again. Once // the read returns, nothing more is appended to responses.jsonl. // +// TWO TABS, ONE READ (lane x-followups, R3). A trending page has tabs — "Top", +// which it opens on, and "Latest" — each its own timeline. After the opening +// tab is read to its stop, the read PRESSES THE PAGE'S OWN TAB: the element +// with the tab's role and the label the page's own answer gave for it, found +// as a person finds it. It builds no request: it waits for the page's request +// for that tab's timeline (the timeline id the page's answer named) and then +// scrolls under the same caps. Each tab has the full scroll and post caps. +// A tab that is not found, or whose press brings no timeline answer within +// the wait, is "not read" with its reason: not a failure, and never retried. +// A 429, a 403, a 401 or a login page on either tab stops the whole read. +// // The caller (controller/readXTrending.ts) is one editor job on X's queue; // this module knows nothing of queues, alerts or the store. @@ -42,6 +54,7 @@ import { X_TRENDING_IDLE_SCROLLS, type XTrendingLimits } from "../lib/xTrending/ import { TRENDING_PAGE_SHOT_FILENAME, TRENDING_RESPONSES_FILENAME, + TRENDING_TAB_SHOT_FILENAME, } from "../lib/xTrending/store"; import { importPlaywright, type ChromiumLike, type PageLike } from "./playwrightRuntime"; import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; @@ -52,8 +65,11 @@ import { xIdOf } from "./xNormalize"; import { collectTimelineTweets, graphqlOpOf, + requestVariablesOf, + trendPageOf, X_TRENDING_IGNORED_OPS, type TrendingCaptureLine, + type TrendingPageInfo, } from "./xTrendingParse"; // One answer is kept up to this size, a read's answers up to this in all: @@ -66,7 +82,47 @@ export const TRENDING_READ_MAX_BYTES = 64 * 1024 * 1024; export const PAGE_LOAD_TIMEOUT_MS = 75_000; export const PAGE_CALL_TIMEOUT_MS = 20_000; export const PAGE_CLOSE_TIMEOUT_MS = 10_000; -export const READ_DEADLINE_MS = 6 * 60_000; +// How long the read waits, after pressing a tab, for the page's request for +// that tab's timeline. +export const TAB_WAIT_MS = 20_000; +// One whole read: two minutes for the load, the screenshots and the tab +// press, and twelve seconds (the longest gap, 10 s, and a page call) for +// every scroll each tab may make. One tab at 20 scrolls: 6 minutes (what a +// read always had). Both tabs at the default 20 scrolls: 10 minutes. Both at +// the maximum 40: 18 minutes. +export const READ_DEADLINE_BASE_MS = 2 * 60_000; +export const READ_DEADLINE_PER_SCROLL_MS = 12_000; +export function readDeadlineMs(limits: Pick<XTrendingLimits, "scrolls">, tabs: number): number { + return READ_DEADLINE_BASE_MS + Math.max(1, tabs) * limits.scrolls * READ_DEADLINE_PER_SCROLL_MS; +} +export const READ_DEADLINE_MS = readDeadlineMs({ scrolls: 20 }, 1); + +// The tabs a read may be asked for, and in the order it reads them: the tab +// the page opens on, then the other. +export type TrendingTabAsk = "top" | "latest"; +export const TRENDING_TAB_ASKS: readonly TrendingTabAsk[] = ["top", "latest"]; +// WHY A TAB WAS NOT READ when the press took the page off the trending page +// (review 2 S1). Said in read.json; the controller reads it to ingest only the +// page's own timelines from such a read (review 3 S8). +export const TRENDING_PAGE_CHANGED = "the page changed"; + +export const TRENDING_TAB_LABEL: Readonly<Record<TrendingTabAsk, string>> = { top: "Top", latest: "Latest" }; + +// One tab of a read: what was asked, the page's own label and timeline for it +// (when the page's answer named one), how it went. +// stop why its scrolling stopped (TrendingReadStop), or +// "not-read": the tab was asked for and could not be opened — +// `why` says so — or "not-asked": the page loaded it (the tab it +// opens on) and the read was asked for the other only. +export type TrendingTabRead = { + asked: TrendingTabAsk; + tab?: string; + timelineId?: string; + scrolls: number; + posts: number; + stop: TrendingReadStop | "not-read" | "not-asked"; + why?: string; +}; // Why a read stopped scrolling. // idle two scrolls in a row brought no new post: the page's end @@ -106,6 +162,13 @@ export type TrendingPageRead = { // The FIRST answer that stopped the read — a 429, a 403 or a 401 — by its // operation and status, so a read's record says which request it was. stoppedBy?: { op: string; status: number }; + // Tab by tab, in the order they were read. `stop` and `scrolls` above are + // the whole read's: the stop of the last tab that was scrolled (or the + // answer that stopped everything), and every scroll. + tabs: TrendingTabRead[]; + // page-latest.png was written (the page after the second tab was pressed, + // or after the press was tried). + tabShot?: boolean; }; // `kill` ends the browser when `close` does not answer: the process itself, @@ -178,12 +241,36 @@ export function abortablePause(ms: number, signal: AbortSignal): Promise<void> { const SCROLL_TO_BOTTOM = "window.scrollTo(0, document.documentElement.scrollHeight)"; +// Whether the page is still the trending page the read opened (review 2 S1): +// the same host and path. Its query may change (a tab may say itself there). +export function sameTrendingPage(href: unknown, opened: string): boolean { + if (typeof href !== "string") return false; + try { + const a = new URL(href); + const b = new URL(opened); + return a.hostname.replace(/^www\./, "") === b.hostname.replace(/^www\./, "") && a.pathname.replace(/\/+$/, "") === b.pathname.replace(/\/+$/, ""); + } catch { + return false; + } +} + +// A page's path, for a log line: never its query (it may carry a search). +function safePath(href: string): string { + try { + return new URL(href).pathname; + } catch { + return "an address that cannot be read"; + } +} + export async function readXTrendingPage(o: { url: string; // The read's directory (`trending/reads/<readId>`), made here. dir: string; openPage: () => Promise<TrendingPageSession>; limits: XTrendingLimits; + // The tabs to read (default: both), read in the page's order. + tabs?: ReadonlyArray<TrendingTabAsk>; pauseMs: () => number; pause?: (ms: number, signal: AbortSignal) => Promise<void>; signal: AbortSignal; @@ -192,7 +279,7 @@ export async function readXTrendingPage(o: { // The byte caps and the deadlines, for tests (defaults: the constants above). maxResponseBytes?: number; maxReadBytes?: number; - timeouts?: { load?: number; call?: number; close?: number; read?: number }; + timeouts?: { load?: number; call?: number; close?: number; read?: number; tab?: number }; }): Promise<TrendingPageRead> { const log = o.onLog ?? (() => {}); const pause = o.pause ?? abortablePause; @@ -203,8 +290,10 @@ export async function readXTrendingPage(o: { load: o.timeouts?.load ?? PAGE_LOAD_TIMEOUT_MS, call: o.timeouts?.call ?? PAGE_CALL_TIMEOUT_MS, close: o.timeouts?.close ?? PAGE_CLOSE_TIMEOUT_MS, - read: o.timeouts?.read ?? READ_DEADLINE_MS, + read: o.timeouts?.read ?? readDeadlineMs(o.limits, (o.tabs ?? TRENDING_TAB_ASKS).length), + tab: o.timeouts?.tab ?? TAB_WAIT_MS, }; + const wanted = TRENDING_TAB_ASKS.filter((t) => (o.tabs ?? TRENDING_TAB_ASKS).includes(t)); // The read's own clock: fired at its deadline, and by the job's cancel. const clock = new AbortController(); let pastDeadline = false; @@ -229,9 +318,21 @@ export async function readXTrendingPage(o: { statuses: {}, tweets: 0, shot: false, + tabs: [], }; const seen = new Set<string>(); + // Per timeline the page asked for ("" for a request that named none): the + // posts it listed, and how many answers it has had. + const seenBy = new Map<string, Set<string>>(); + const answersBy = new Map<string, number>(); + // What the page said of itself: its tabs' labels and timelines. + let pageInfo: TrendingPageInfo | undefined; + // The first timeline the page asked for: the tab it opens on, whether or + // not the page's own answer (which names the tabs) was among what it fetched. + let firstTimeline: string | undefined; let rateLimited = false; + // The read's deadline fell inside the second tab (review 2 S2). + let latestCut = false; let unauthorized = false; let forbidden = false; let n = 0; @@ -286,9 +387,18 @@ export async function readXTrendingPage(o: { out.saved++; keep({ ...base, bytes, body }); if (status >= 200 && status < 300 && !X_TRENDING_IGNORED_OPS.includes(op)) { - for (const raw of collectTimelineTweets(body)) { + pageInfo ??= trendPageOf(body); + const timeline = requestVariablesOf(url).timelineId ?? ""; + const found = collectTimelineTweets(body); + if (timeline || found.length) answersBy.set(timeline, (answersBy.get(timeline) ?? 0) + 1); + if (timeline && found.length) firstTimeline ??= timeline; + const own = seenBy.get(timeline) ?? new Set<string>(); + seenBy.set(timeline, own); + for (const raw of found) { const id = xIdOf(raw); - if (id) seen.add(id); + if (!id) continue; + seen.add(id); + own.add(id); } } })().catch(() => { @@ -339,28 +449,185 @@ export async function readXTrendingPage(o: { } log(`The page loaded: ${out.responses} answer(s), ${seen.size} post(s) so far.`); - let idle = 0; - let stop: TrendingReadStop | null = blocked(); - while (!stop) { - if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; - else if (seen.size >= o.limits.posts) stop = "post-cap"; - else if (out.scrolls >= o.limits.scrolls) stop = "scroll-cap"; - if (stop) break; - const before = seen.size; - await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); - out.scrolls++; - await pause(o.pauseMs(), signal); - await settle(); - stop = blocked(); - if (stop) break; - if (seen.size === before) { - if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle"; + // THE PAGE'S TABS, as its own answer named them. The tab it opens on is + // "Top"; with no such answer the opening tab is whatever the page lists. + const tabOf = (ask: TrendingTabAsk) => + pageInfo?.tabs.find((t) => t.label.trim().toLowerCase() === TRENDING_TAB_LABEL[ask].toLowerCase()); + // The posts one tab has listed so far: its own timeline's, else (a page + // that named no tabs) every post seen. + const countOf = (timelineId: string | undefined) => (timelineId ? (seenBy.get(timelineId)?.size ?? 0) : seen.size); + + // One tab scrolled to its stop, under the read's caps. + const scrollTab = async (timelineId: string | undefined): Promise<{ stop: TrendingReadStop; scrolls: number }> => { + let idle = 0; + let scrolls = 0; + let stop: TrendingReadStop | null = blocked(); + while (!stop) { + if (signal.aborted) stop = pastDeadline ? "deadline" : "cancelled"; + else if (countOf(timelineId) >= o.limits.posts) stop = "post-cap"; + else if (scrolls >= o.limits.scrolls) stop = "scroll-cap"; + if (stop) break; + const before = countOf(timelineId); + await bounded("scrolling", page.evaluate(SCROLL_TO_BOTTOM), t.call, signal); + scrolls++; + out.scrolls++; + await pause(o.pauseMs(), signal); + await settle(); + stop = blocked(); + if (stop) break; + if (countOf(timelineId) === before) { + if (++idle >= X_TRENDING_IDLE_SCROLLS) stop = "idle"; + } else { + idle = 0; + } + log(`Scroll ${out.scrolls}: ${countOf(timelineId)} post(s) on this tab, ${out.responses} answer(s).`); + } + return { stop: stop ?? "idle", scrolls }; + }; + // A stop that ends the whole read, not one tab's scrolling. + const ends = (stop: TrendingReadStop) => stop !== "idle" && stop !== "scroll-cap" && stop !== "post-cap"; + + // THE TAB THE PAGE OPENS ON. + const named = tabOf("top"); + const top = named ?? (firstTimeline ? { label: undefined, timelineId: firstTimeline } : undefined); + const openingTab: TrendingTabRead = { + asked: "top", + ...(top?.label ? { tab: top.label } : {}), + ...(top ? { timelineId: top.timelineId } : {}), + scrolls: 0, + posts: 0, + stop: "not-asked", + }; + out.tabs.push(openingTab); + let stop: TrendingReadStop = blocked() ?? "idle"; + if (wanted.includes("top") || blocked()) { + const r = await scrollTab(top?.timelineId); + openingTab.stop = r.stop; + openingTab.scrolls = r.scrolls; + stop = r.stop; + } + openingTab.posts = countOf(top?.timelineId); + + // THE OTHER TAB: pressed, never asked for. WHATEVER HAPPENS HERE, THE + // OPENING TAB'S READ STANDS (review 2 S2): a press that fails is "not + // read", and the read's deadline falling inside it stops this tab only. + // `abandoned`: the page left the trending page — nothing more is done + // with it (S1); `hung`: a page call did not answer (no screenshot). + let abandoned = false; + let hung = false; + if (wanted.includes("latest") && !ends(stop)) { + const latest = tabOf("latest"); + const second: TrendingTabRead = { + asked: "latest", + ...(latest ? { tab: latest.label, timelineId: latest.timelineId } : {}), + scrolls: 0, + posts: 0, + stop: "not-read", + }; + out.tabs.push(second); + const label = latest?.label ?? TRENDING_TAB_LABEL.latest; + // The read's own deadline (or a page that stopped answering) inside + // this tab: it stops here, with what it had; the read is the opening + // tab's. A cancel is the whole read's. + const cutHere = (err: unknown): boolean => { + if (err instanceof PageDeadlineError) hung = true; + if (o.signal.aborted) return false; + return pastDeadline || err instanceof PageDeadlineError; + }; + if (!latest) { + second.why = pageInfo + ? `the page's own answer names no "${label}" tab (it names: ${pageInfo.tabs.map((x) => `"${x.label}"`).join(", ") || "none"})` + : "the page's own answer, which names its tabs and their timelines, was not among what it fetched"; + } else if (!page.getByRole) { + second.why = "this page cannot be pressed"; } else { - idle = 0; + // THE PAGE'S OWN TAB (S1): a control of role "tab", INSIDE the page's + // tab list, with exactly the name the page's own answer gave. Never a + // link or a button of that name: those go elsewhere. + const had = answersBy.get(latest.timelineId) ?? 0; + let pressed = false; + try { + const list = page.getByRole("tablist"); + const found = list.getByRole?.("tab", { name: latest.label, exact: true }); + const count = found ? await bounded(`looking for the "${label}" tab`, found.count(), t.call, signal) : 0; + if (!found || !count) { + second.why = `the page shows no tab named "${label}" in its tab list`; + } else { + await bounded(`pressing the "${label}" tab`, found.first().click({ timeout: Math.min(t.call, 15_000) }), t.call, signal); + pressed = true; + log(`Pressed the page's "${label}" tab.`); + } + } catch (err) { + if (o.signal.aborted) throw err; + second.why = `pressing "${label}" failed: ${firstLine(err)}`; + if (err instanceof PageDeadlineError) hung = true; + } + // STILL THE SAME PAGE (S1): a press that took the page anywhere else + // stops the read at once — nothing more is read, pressed or shot. + if (pressed) { + const href = await bounded("reading its address", page.evaluate("location.href"), t.call, signal).catch(() => null); + if (!sameTrendingPage(href, o.url)) { + second.why = TRENDING_PAGE_CHANGED; + abandoned = true; + pressed = false; + log(`After pressing "${label}" the page is no longer the trending page${typeof href === "string" ? ` (${safePath(href)})` : ""}: the read stops here.`); + } + } + if (pressed) { + // The page's own request for that tab's timeline: waited for, in + // short steps, on ITS OWN 20 s WALL CLOCK (S3) — each step's settle + // counted, not only the steps. + const waitFrom = now(); + for (let waited = 0; waited < t.tab && now() - waitFrom < t.tab && (answersBy.get(latest.timelineId) ?? 0) <= had && !signal.aborted && !blocked(); waited += 500) { + await pause(500, signal); + await settle(); + } + if (blocked()) { + second.stop = blocked()!; + stop = second.stop; + } else if (signal.aborted) { + if (o.signal.aborted) { + second.stop = "cancelled"; + stop = "cancelled"; + } else { + second.stop = "deadline"; + } + } else if ((answersBy.get(latest.timelineId) ?? 0) <= had) { + second.why = `pressing "${label}" brought no answer for its timeline within ${Math.round(t.tab / 1000)} s`; + } else { + const scrollsBefore = out.scrolls; + try { + await pause(o.pauseMs(), signal); + await settle(); + const r = await scrollTab(latest.timelineId); + second.stop = r.stop; + // The deadline inside Latest is Latest's stop, not the read's. + if (r.stop !== "deadline") stop = r.stop; + } catch (err) { + if (!cutHere(err)) throw err; + second.stop = "deadline"; + } + second.scrolls = out.scrolls - scrollsBefore; + } + } + } + second.posts = countOf(latest?.timelineId); + if (second.stop === "deadline") log(`The "${label}" tab stopped at the read's deadline, with ${second.posts} post(s).`); + // The page as it stood after the press (or the try): beside page.png. + if (!abandoned && !hung && !signal.aborted) { + try { + const png = await bounded("the second screenshot", page.screenshot({ type: "png" }), t.call, signal); + await writeFile(path.join(o.dir, TRENDING_TAB_SHOT_FILENAME), png); + out.tabShot = true; + } catch { + /* the screenshot is a courtesy: its failure costs nothing */ + } } - log(`Scroll ${out.scrolls}: ${seen.size} post(s), ${out.responses} answer(s).`); + if (second.stop === "not-read") log(`The "${label}" tab was not read: ${second.why}.`); } - out.stop = stop ?? "idle"; + // The deadline fell inside the second tab: the read is the first's. + if (out.tabs[1]?.stop === "deadline") latestCut = true; + out.stop = stop; } catch (err) { const hung = err instanceof PageDeadlineError || pastDeadline; out.stop = blocked() ?? (hung ? "deadline" : o.signal.aborted ? "cancelled" : "error"); @@ -392,7 +659,7 @@ export async function readXTrendingPage(o: { }); } } - if (out.stop === "idle" && pastDeadline) out.stop = "deadline"; + if (out.stop === "idle" && pastDeadline && !latestCut) out.stop = "deadline"; out.tweets = seen.size; return out; } diff --git a/common/testing/jobs/asEditorJob.ts b/common/testing/jobs/asEditorJob.ts @@ -0,0 +1,28 @@ +// A CALL MADE AS THE EDITOR'S JOB, for tests of code that runs only inside +// one: an X posts fetch (controller/fetchPosts.ts X_ONLY_AS_A_JOB) asks +// `currentJobContext()` and refuses a caller that is no job. The real funnel +// (jobs/streamCommand.ts runManagedFunction) gives every job this context; a +// test that calls the controller directly, to look at what it does with a +// fake gallery-dl, has to say it stands where a job does. +// +// X's queue by default (`platform:twitter`). Nothing of the funnel's guards +// runs here: no queue, no gap, no jar rule — a test of THOSE goes through +// runManagedFunction (jobs/pacingGuard.test.ts). + +import { runInJobContext, type JobContext } from "../../lib/jobContext"; + +export const X_QUEUE_KEY = "platform:twitter"; + +export function editorJobContext(over: Partial<JobContext> = {}): JobContext { + return { jobId: "test-job", kind: "fetch-posts", queueKey: X_QUEUE_KEY, onLog: () => {}, staleServices: new Set(), ...over }; +} + +// Run `fn` as a job's body. +export function asEditorJob<T>(fn: () => T, over: Partial<JobContext> = {}): T { + return runInJobContext(editorJobContext(over), fn); +} + +// The same function, every call of it made as a job's body. +export function insideEditorJob<A extends unknown[], R>(fn: (...args: A) => R, over: Partial<JobContext> = {}): (...args: A) => R { + return (...args: A) => asEditorJob(() => fn(...args), over); +} diff --git a/common/views/jobRowView.ts b/common/views/jobRowView.ts @@ -98,6 +98,9 @@ export type JobRowView = { // boot pass's reason for a job a restart left queued ("server restarted; // the scheduler re-derives syncs"). History rows only; see listJobs.ts. cancelReason?: string; + // A `done` row that did not run: X's job cap was reached at its start + // (JobRecord.deferred). Drawn as "deferred" in place of "done". + deferred?: { until: number; sentence: string }; // A network job its queue has started, waiting out the gap after the // previous one on that platform queue (jobs/queueGap.ts): when it may begin // (epoch ms) and why. Live rows only. Drawn as "waiting 4m12s: X jobs are diff --git a/common/views/jobRows.ts b/common/views/jobRows.ts @@ -305,6 +305,7 @@ export function fromEntry(e: JobListEntry): JobRowView { replayable: e.replayable, detail: e.detail, ...(e.cancelReason ? { cancelReason: e.cancelReason } : {}), + ...(e.deferred ? { deferred: e.deferred } : {}), source: "archive", }; } diff --git a/common/views/schedulerStatus.ts b/common/views/schedulerStatus.ts @@ -46,6 +46,8 @@ export type SchedulerStatusInputs = { // Why no Instagram job starts now, when none does (the shell asks the // guard: jobs/instagramGuard.ts). instagramHeld?: string | null; + // Why no X job starts now, when X's job cap is reached (jobs/networkGuard.ts xCapHeldReason). + xCapHeld?: string | null; }; export function buildSchedulerStatusPayload( @@ -60,6 +62,7 @@ export function buildSchedulerStatusPayload( priority: settings.channelPriority, jitter: settings.pacing?.jitter ?? 0, ...(inputs.instagramHeld ? { instagramHeld: inputs.instagramHeld } : {}), + ...(inputs.xCapHeld ? { xCapHeld: inputs.xCapHeld } : {}), }); return { now, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,88 @@ # Changelog ## [Unreleased] +- **X jobs run on X's queue only, under a cap no setting can raise.** + - A job that asks X is refused on any queue but `platform:twitter`, when it is queued and where it runs: a posts + fetch in any mode, a resumed backfill, a Sync, a capture, a trending read, an import of an X post, an + availability check, an X run. A job moved to another queue used to run beside the one on X's, with no gap. + - **At most 12 X jobs start in any 60 minutes and 150 in any 24 hours, on this machine**, over every kind + together. It is one count, whatever the login source, cookie spec or channel: switching the login source or + respelling a cookie spec no longer starts a fresh count. A job past the cap is refused when you queue it and + says when the next may start. The scheduler skips X channels meanwhile and a trending watch waits. + `pnpm ops get x-session` shows the count. + - A job that meets the cap when its queue starts it ends **deferred**, not failed. It did not run, it is no + strike against its channel's sync, and nothing queues it again before the time it gives. The /jobs row says + "deferred". + - Only a job that can ask x.com with the login or X's cookies counts. A trending watch's media-only capture, + which downloads files from X's media servers with no cookie and no page, does not count and is not held by the + cap. It still runs on X's queue, after X's gap. + - The numbers are constants of the code (`common/lib/xJobRule.ts`). No setting, option, environment variable, + flag or queue changes them. The count survives a restart, and an unreadable count stops every X job. If the + count's file is deleted, the last day's X jobs are counted again from the job records. If X jobs ran and + their records cannot be read, or cannot be shown to be all there, every X job is refused (at most for a + day). The jobs list's retention and Clear logs keep each X job's record for the day it can count. A start + stamped in the future counts, and never pushes the real ones out of the count. + - **A clip window is X's by the address it fetches, in any channel.** An x.com video filed on a YouTube channel, + a window sent to `POST /api/media/fetch-window` with an x.com `webpageUrl`, or one item of a batch across + channels runs on X's queue and counts. A window of an archive.org or Wayback copy, or of a mirror on another + platform, is not X's. A window cut from a saved copy that is gone by the time it runs fails with a sentence + and asks X nothing. A `t.co` link is X's, and so are X's media hosts (`video.twimg.com`, `pbs.twimg.com`). + - **Importing a file by an X page's address runs on X's queue on any channel**, `t.co` links included, and + counts. A `webpageUrl` given for a local channel to `POST /api/media/fetch-window` or to a fetch-windows item + must be a full `http(s)://` address; one without its scheme is refused before anything is asked. + - The scheduler queues no more X syncs than the cap has starts left; the others wait for a later tick instead of + each ending deferred. + - An X channel's jobs that never ask X run on their own queues again: a transcription (whisper-video's hand-off + to it included), clip windows cut from a saved copy, a local file's import, an archive.org import. An X clip + window, an import of an x.com address and an X channel's kept-videos check now run on X's queue. Recording an X + live stream stays refused, because it would hold X's queue for hours. + - The Add-channel form's Fetch details no longer starts gallery-dl against X for an X address: it reads the + handle off the URL. `pnpm archilyzer posts check` refuses an X channel as `posts fetch` does. +- **A trending read covers Top and Latest in one job, and can reach the page's end.** + - After Top is read, the read presses the page's Latest tab and reads it under the same caps. `"tabs"` on + `read-x-trending` and on a watch picks one tab; the channel page's form has the same choice. + - A Latest tab that cannot be opened ends the read `Top read; Latest not read: <why>`. It is still a read. The + read presses only the page's own tab, inside its tab list. If the press leaves the trending page, the read + stops there: `Top read; Latest not read: the page changed`. A click that fails is the same kind of ending. If + the read runs out of time inside Latest, Top's read is kept: `Top read; Latest stopped at the deadline`. + - "Gone" is said per tab: gone from Latest while Top still shows it, or gone from the page. **Gone from the + page** needs one read in which every tab that showed the post was read to its end without it. Marks from + different reads stay per tab. A post seen before tabs were read counts as the Top tab's (the tab named Top, + wherever the page lists it), so a complete Latest read no longer calls it gone. + - When a press takes the page elsewhere, what that other page sends stays in the capture and is not added to the + topic: only the trending page's own tabs are read, on the read and on a reparse. + - The caps are higher so a read can reach the end, which is what lets it say a post is gone: 20 scrolls and + 200 posts per tab by default (were 8 and 60), at most 40 and 400. A read's deadline is 2 minutes plus 12 s per + scroll per tab: 10 minutes for both tabs at the defaults. +- **A trending page's topic carries X's title and summary, and a read says which tab it saw.** The first real read + of a trending page named its topic `Trending <number>`: the page's own answer was never parsed. + - A topic you did not name is called by the page's title. One still called `Trending <number>` takes the title at + the next read or `reparse` of a capture that has it, and the job's sentence says so. A topic made with a name, + or renamed since by you or an agent, is never renamed by a read. + - The channel page's Topics, `pnpm ops get trending`, the MCP's `x_trending_topics` and umtool's library page + (and `umtool library topics`) show X's title, its summary and when X last updated them, as X's words. + - A trending page has tabs (`Top`, `Latest`). A read sees the one the page opens on and says which, in its + sentence, in `read.json` and per post. The other tab is not read. "Gone from the page" compares reads of the + same tab only. + - The page's end is found in what the real page sends: a timeline's later answers carry their cursors in + replacement instructions, not as entries. The end of a timeline itself has not been seen yet (the first read + stopped at its post cap), so its shape is not assumed: nothing is marked gone until a read reaches an end. +- **`pnpm archilyzer posts fetch` refuses an X channel.** Run from the command line a fetch had no queue, no gap + between X jobs, no fresh-jar rule, no X alert and no cooldown after a rate limit. It now answers with one sentence + naming `pnpm ops fetch-posts`, in every mode and for every X fetcher and an X search channel. A Bluesky account, + a forum thread (`--pages N`) and a web page are fetched from there as before. +- **A resumed X history walk no longer ends as "caught up" and loses its place.** A long first + full-history walk of an X account stopped at its 180-minute budget; Resume backfill then read 100 posts already + archived, said "caught up", wrote nothing and cleared the saved place. + - The cause: below what X's timeline pages back, gallery-dl goes on by search and logs no cursor there, so the + place saved was the last timeline page, thousands of posts above where the walk stood. The search's own page + marker is now the place. + - A resumed backfill skips posts already archived and reads on. It ends at the timeline's end, its budget or a + cap, and only the timeline's end clears its place. + - A resume whose first posts are the timeline's newest did not continue from its place: it stops at once with a + sentence and keeps the place, instead of walking the whole timeline again. + - A place already lost is not restored by this. `pnpm ops fetch-posts --json '{"slug":"…","older":true}'` walks + down from the oldest archived post. - **An Instagram account can be archived as a posts channel.** - An `instagram.com/<account>/` URL on the New channel form (or `pnpm ops create-channel`) makes one: posts and reels with their text, date, link and media. A carousel is one post with several media. diff --git a/editor/app/api/jobs/[id]/log/route.ts b/editor/app/api/jobs/[id]/log/route.ts @@ -61,5 +61,7 @@ export async function GET( // The job its work went on in (JobRecord.handedOffTo): `pnpm ops --wait` // follows it there. ...(record?.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), + // Ended deferred by X's job cap (JobRecord.deferred): it did not run. + ...(record?.deferred ? { deferred: record.deferred } : {}), }); } diff --git a/editor/app/api/media/fetch-window/route.test.ts b/editor/app/api/media/fetch-window/route.test.ts @@ -68,6 +68,17 @@ test("maxHeight out of range, fractional or not a number is refused with 400", a } }); +// Review 4 C: a caller's page address is a full http(s) address, or nothing +// is asked — before the cache, the archive or any job. +test("a webpageUrl that is not an http(s) address is refused with 400", async () => { + for (const webpageUrl of ["x.com/u/status/1", "t.co/AbC", "//x.com/u/status/1", "ftp://example.org/a.mp4", "javascript:alert(1)", "www.youtube.com/watch?v=abc123"]) { + const res = await post({ ...base, webpageUrl }); + assert.equal(res.status, 400, webpageUrl); + const body = (await res.json()) as { error: string }; + assert.match(body.error, /^webpageUrl must be an http\(s\) address/, webpageUrl); + } +}); + test("a cached window answers with its probed height", async () => { await writeFile(path.join(VIDEO_DIR, "clips", "5.00-25.00.mp4"), "not really an mp4"); const res = await post({ ...base, maxHeight: 720 }); diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts @@ -6,6 +6,8 @@ import { MAX_FETCH_MAX_HEIGHT, MIN_FETCH_MAX_HEIGHT, isFetchMaxHeight, + isFullPageAddress, + pageAddressRefusal, } from "yt-dlp-transcript-common/lib/clipWindow"; import { sourceVideoQualityForMaxHeight } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { @@ -260,6 +262,12 @@ export async function POST(request: Request) { { status: 409 }, ); } + } else if (webpageUrl !== undefined && !isFullPageAddress(webpageUrl)) { + // A LOCAL CHANNEL'S PAGE ADDRESS, from the caller, is a full http(s) + // address (review 4 C), before the cache or any job: one written + // without its scheme ("x.com/…") is read by no rule the same way twice. + // (A remote-only channel's is parsed and written back above.) + return NextResponse.json({ error: pageAddressRefusal(webpageUrl) }, { status: 400 }); } } diff --git a/editor/app/api/ops/_xTrendingWatch.ts b/editor/app/api/ops/_xTrendingWatch.ts @@ -22,7 +22,7 @@ export function xTrendingWatchDeps(): WatchScanDeps { 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 }); + const started = await readXTrendingAction({ slug: tick.slug, url: tick.url, topic: tick.topic, watch: true, ...(tick.tabs ? { tabs: tick.tabs } : {}) }); if (!started.ok) return { ok: false, error: started.error }; void started.stream.cancel(); return { ok: true, jobId: started.jobId }; diff --git a/editor/app/api/ops/read-x-trending/route.test.ts b/editor/app/api/ops/read-x-trending/route.test.ts @@ -119,7 +119,7 @@ test("read-x-trending refuses, before any job, with a sentence", async () => { assert.match(await refused({ slug: "account-x", url: TREND }), /account-x is not an X trending library/); assert.match(await refused({ slug: "trending" }), /Give "url" .* or "reparse"/); assert.match(await refused({ slug: "trending", url: "https://x.com/example/status/1" }), /not a trending page URL/); - assert.match(await refused({ slug: "trending", url: TREND, scrolls: 21 }), /"scrolls" is a whole number, 1–20/); + assert.match(await refused({ slug: "trending", url: TREND, scrolls: 41 }), /"scrolls" is a whole number, 1–40/); assert.match(await refused({ slug: "trending", url: TREND, posts: 0 }), /"posts" must be a whole number above zero/); assert.match(await refused({ slug: "trending", url: TREND, probe: "yes" }), /"probe" must be a boolean/); assert.match(await refused({ slug: "trending", url: TREND, pages: 3 }), /pages/); @@ -171,7 +171,7 @@ test("create-channel refuses a library on a site and a library with a URL; nothi assert.equal(withUrl.status, 400); assert.match(String(withUrl.json.error), /^An X trending library has no URL/); const badCap = await call(create, { fields: { ...fields, xTrendingMaxPosts: 500 } }); - assert.match(String(badCap.json.error), /post cap is a whole number, 1–200/); + assert.match(String(badCap.json.error), /post cap is a whole number, 1–400/); assert.equal(await exists(path.join(ROOT, "channels", "made-trending")), false); }); diff --git a/editor/app/api/ops/read-x-trending/route.ts b/editor/app/api/ops/read-x-trending/route.ts @@ -3,7 +3,7 @@ import { jobResponse, ops, optBool, optPositiveInt, optString, reqSlug } from ". export const dynamic = "force-dynamic"; -// POST { slug, url, topic?, scrolls?, posts?, probe?, headed? } -> { ok: true, jobId } +// POST { slug, url, topic?, scrolls?, posts?, tabs?, probe?, headed? } -> { ok: true, jobId } // POST { slug, reparse: "<readId>", topic? } -> { ok: true, jobId } // // ONE X trending page (https://x.com/i/trending/<number>) read into `slug`, @@ -17,10 +17,15 @@ export const dynamic = "force-dynamic"; // // topic the topic's id or name, or a new one's name. Absent: the topic // this page was read into before, else a new one named for it. -// scrolls at most this many moves to the bottom of the page (1–20; the -// channel's cap, else 8). posts: stop once this many are seen -// (1–200; else 60). A read also stops after two scrolls that -// brought nothing new, and at once on a 429 or a login wall. +// scrolls at most this many moves to the bottom of a tab (1–40; the +// channel's cap, else 20). posts: stop once this many are seen on +// a tab (1–400; else 200). A tab's read also stops after two +// scrolls that brought nothing new, and the whole read at once on +// a 429 or a login wall. +// tabs the page's tabs to read: ["top"], ["latest"] or both (the +// default). Both are read in THIS one job: Top to its stop, then +// the page's Latest tab is pressed. A Latest that cannot be +// opened ends the read "Top read; Latest not read: <why>", ok. // probe save the capture and its summary; write no post. // headed open a window on the editor's desktop instead of a headless one. // reparse a saved read's id: its capture parsed again, OFFLINE (a @@ -39,7 +44,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "url", "reparse", "topic", "scrolls", "posts", "probe", "headed"], + ["slug", "url", "reparse", "topic", "scrolls", "posts", "tabs", "probe", "headed"], async (body) => { const url = optString(body, "url"); const reparse = optString(body, "reparse"); @@ -56,6 +61,7 @@ export async function POST(request: Request) { ...(topic !== undefined ? { topic } : {}), ...(scrolls !== undefined ? { scrolls } : {}), ...(posts !== undefined ? { posts } : {}), + ...(body.tabs !== undefined ? { tabs: body.tabs } : {}), ...(probe ? { probe: true } : {}), ...(headed ? { headed: true } : {}), }), diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -20,10 +20,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}], watch?}], +// title?, summary?, lastUpdatedAt?, tabs?, lastReadTab?, reads, +// lastReadAt}], watch?}], // posts: [{id, author, authorName?, createdAt, url, text, // media: {count, kinds, thumbnail?}, topic, -// reads: [{read, trendId, at}], gone?, capture?, thread, +// reads: [{read, trendId, at, tab?}], gone?, capture?, thread, // judgement?}], // total, reads: [<readId>, …] } // diff --git a/editor/app/api/ops/watch-trending/route.ts b/editor/app/api/ops/watch-trending/route.ts @@ -4,7 +4,7 @@ import { ops, opsFail, optBool, optString, reqSlug } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, topic, on, intervalMinutes?, hours?, shots?, by? } +// POST { slug, topic, on, intervalMinutes?, hours?, shots?, tabs?, by? } // -> { ok: true, slug, topic, watch, sentence } // POST { slug, settings: {maxVideoMb?, intervalMinutes?, hours?, maxTopics?} } // -> { ok: true, slug, settings, sentence } @@ -23,6 +23,8 @@ export const dynamic = "force-dynamic"; // // on true watches the topic (again: its terms change, its history // stays); false stops (the watch ends "switched off") +// tabs the page's tabs each tick reads: ["top"], ["latest"] or both +// (the default; both are read in the one job). // 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" @@ -67,7 +69,7 @@ export const dynamic = "force-dynamic"; // 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) => { + return ops(request, ["slug", "topic", "on", "intervalMinutes", "hours", "shots", "tabs", "by", "settings", "tick"], async (body) => { const topic = optString(body, "topic"); const on = optBool(body, "on"); const shots = optBool(body, "shots"); @@ -81,6 +83,7 @@ export async function POST(request: Request) { ...(body.intervalMinutes !== undefined ? { intervalMinutes: body.intervalMinutes } : {}), ...(body.hours !== undefined ? { hours: body.hours } : {}), ...(shots !== undefined ? { shots } : {}), + ...(body.tabs !== undefined ? { tabs: body.tabs } : {}), ...(body.by !== undefined ? { by: body.by } : {}), }); if (!result.ok) return opsFail(result.error); diff --git a/editor/app/channels/[slug]/components/XTrendingPanel.tsx b/editor/app/channels/[slug]/components/XTrendingPanel.tsx @@ -187,6 +187,8 @@ export function XTrendingPanel({ const [posts, setPosts] = useState(""); const [probe, setProbe] = useState(false); const [headed, setHeaded] = useState(false); + // The page's tabs one read covers: both (Top, then Latest, in the one job), or one. + const [tabs, setTabs] = useState<"both" | "top" | "latest">("both"); const [reparse, setReparse] = useState(listing.reads[0] ?? ""); const input = "rounded border border-border bg-card px-2 py-1 text-sm"; const num = (v: string) => (v.trim() ? Number(v) : undefined); @@ -248,6 +250,14 @@ export function XTrendingPanel({ className={`${input} w-20`} /> </label> + <label className="flex flex-col gap-1"> + <span className="font-medium">Tabs</span> + <select value={tabs} onChange={(e) => setTabs(e.target.value as "both" | "top" | "latest")} aria-label="tabs" className={`${input} w-40`}> + <option value="both">Top, then Latest</option> + <option value="top">Top only</option> + <option value="latest">Latest only</option> + </select> + </label> <label className="flex items-center gap-2" title="Save the page's answers and a summary; write no post"> <input type="checkbox" checked={probe} onChange={(e) => setProbe(e.target.checked)} /> Probe (save only) @@ -265,6 +275,7 @@ export function XTrendingPanel({ ...(topic.trim() ? { topic: topic.trim() } : {}), ...(num(scrolls) !== undefined ? { scrolls: num(scrolls) } : {}), ...(num(posts) !== undefined ? { posts: num(posts) } : {}), + ...(tabs === "both" ? {} : { tabs: [tabs] }), ...(probe ? { probe: true } : {}), ...(headed ? { headed: true } : {}), }) @@ -317,11 +328,31 @@ export function XTrendingPanel({ </h4> <ul className="flex flex-col gap-0.5 text-xs text-muted-foreground"> {t.sources.map((s) => ( - <li key={s.trendId}> - <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline"> - {s.url} - </a>{" "} - · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} + <li key={s.trendId} data-x-trending-source={s.trendId} className="flex flex-col gap-0.5"> + <span> + <a href={s.url} target="_blank" rel="noreferrer" className="font-mono underline"> + {s.url} + </a>{" "} + · read {s.reads}×{s.lastReadAt ? `, last ${s.lastReadAt.slice(0, 16).replace("T", " ")} UTC` : ""} + {s.lastReadTabs ? ( + <span data-x-trending-tab=""> · the last read saw the {s.lastReadTabs.map((tab) => `“${tab}”`).join(" and ")} tabs</span> + ) : s.lastReadTab ? ( + <span data-x-trending-tab=""> + {" "} + · the last read saw the “{s.lastReadTab}” tab + {s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((tab) => `“${tab}”`).join(", ")}` : ""} + </span> + ) : null} + </span> + {s.title ? ( + <span data-x-trending-x-title="" className="text-foreground"> + X’s title: {s.title} + {s.lastUpdatedAt ? ( + <span className="text-muted-foreground"> · X updated it {s.lastUpdatedAt.slice(0, 16).replace("T", " ")} UTC</span> + ) : null} + </span> + ) : null} + {s.summary ? <span data-x-trending-x-summary="">X’s summary: {s.summary}</span> : null} </li> ))} </ul> @@ -348,6 +379,11 @@ export function XTrendingPanel({ Gone from the page at {when(p.gone.at)} UTC. </span> )} + {p.goneTabs?.map((g) => ( + <span key={g.tab} data-x-trending-gone-tab={g.tab} className="text-xs text-amber-700 dark:text-amber-400"> + Gone from the “{g.tab}” tab at {when(g.at)} UTC; another tab still shows it. + </span> + ))} <span className="whitespace-pre-wrap">{p.text}</span> <PostJudge slug={slug} post={p} /> </li> diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -17,6 +17,7 @@ import { downloadQueueKey, resolveQueueKey, } from "yt-dlp-transcript-common/lib/queueKeys"; +import { isXUrl, X_QUEUE_KEY } from "yt-dlp-transcript-common/lib/xJobRule"; import { detectPlatform, platformQueueKey, @@ -685,7 +686,9 @@ export async function importVideoAction( // queue control starts at the CHANNEL's queue, which is therefore read as // "no choice made"; any other queue the operator picks still wins. const channelQueue = downloadQueueKey(channelConfig); - const ownQueue = archiveOrg || pacedPlatform ? platformQueueKey(urlPlatform) : null; + // An x.com URL is X's: X's queue (review 2 S5; lib/xJobRule.ts) — and so + // is a t.co short link, which X answers (review 3 S6). + const ownQueue = isXUrl(videoUrl) ? X_QUEUE_KEY : archiveOrg || pacedPlatform ? platformQueueKey(urlPlatform) : null; const override = ownQueue && queueKey !== undefined && queueKey.trim() === channelQueue ? undefined diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -27,6 +27,7 @@ import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-trans 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 { xJobCounts } from "yt-dlp-transcript-common/lib/xJobRule"; 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"; @@ -452,6 +453,24 @@ export async function capturePostsAction( } const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey); + // THE JOB'S PLAN: its spec, and what the network guard reads to decide + // whether it counts against X's job cap (lib/xJobRule.ts xJobCounts). + const params = { + queueKey, ids: wanted, shots, media, force, articles, + ...(thread !== undefined ? { thread } : {}), + ...(threadRedact !== undefined ? { threadRedact } : {}), + ...(avatars !== undefined ? { avatars } : {}), + ...(avatarsOnly ? { avatarsOnly } : {}), + ...(context !== undefined ? { context } : {}), + ...(contextOnly ? { contextOnly } : {}), + ...(keptMedia ? { keptMedia } : {}), + ...(watch ? { watch } : {}), + }; + const counts = xJobCounts({ + kind: "capture-posts", + params, + channel: { library, ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) }, + }); return runManagedFunction({ kind: "capture-posts", queueKey: key, @@ -460,17 +479,7 @@ export async function capturePostsAction( spec: { kind: "capture-posts", slug, - params: { - queueKey, ids: wanted, shots, media, force, articles, - ...(thread !== undefined ? { thread } : {}), - ...(threadRedact !== undefined ? { threadRedact } : {}), - ...(avatars !== undefined ? { avatars } : {}), - ...(avatarsOnly ? { avatarsOnly } : {}), - ...(context !== undefined ? { context } : {}), - ...(contextOnly ? { contextOnly } : {}), - ...(keptMedia ? { keptMedia } : {}), - ...(watch ? { watch } : {}), - }, + params, }, fn: async (onLog, signal, _progress, ctx) => { // AN X CAPTURE'S START (lib/cookieRefreshGuard.ts xCaptureStartRefusal), @@ -489,7 +498,8 @@ export async function capturePostsAction( // 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); + // A media-only capture asks x.com nothing: X's job cap does not hold it (ruling R-a). + const refusal = await refuseWatchJob(paths, slug, undefined, { counts }); 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 diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -38,6 +38,7 @@ import { downloadQueueKey, resolveQueueKey, } from "yt-dlp-transcript-common/lib/queueKeys"; +import { isXUrl, X_QUEUE_KEY, xJobContextRefusal } from "yt-dlp-transcript-common/lib/xJobRule"; import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; @@ -1907,8 +1908,10 @@ export async function fetchWindowAction(req: { kind: "fetch-window", // The platform's CLIP queue, not its download queue: a window must not // wait behind a multi-hour persist or sync (lib/queueKeys.ts, - // clipWindowQueueKey). An explicit override still wins. - queueKey: resolveQueueKey(clipWindowQueueKey(downloadQueueKey(r.config)), req.queueKey), + // clipWindowQueueKey). An explicit override still wins. AN X PAGE IS + // X'S WHEREVER IT IS FILED (review 3 M2): its window runs on X's queue, + // and an override elsewhere is refused (lib/xJobRule.ts xJobAsksX). + queueKey: resolveQueueKey(isXUrl(url) ? X_QUEUE_KEY : clipWindowQueueKey(downloadQueueKey(r.config)), req.queueKey), paths, channelSlug: slug, videoId, @@ -1931,6 +1934,9 @@ export async function fetchWindowAction(req: { }, fn: async (onLog, signal) => { onLog(`${requesterLine(req.provenance)}\n`); + // X is asked only by a job on X's queue (lib/xJobRule.ts), checked where it is asked. + const notHere = isXUrl(url) ? xJobContextRefusal(`The window of ${slug}/${videoId}`, "POST /api/media/fetch-window (it queues an X window on X's queue)") : null; + if (notHere) throw new Error(notHere); const once = (target: (StoredMediaUrl & { why: StoredUrlWhy }) | null) => fetchWindowManaged({ channelSlug: slug, diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts @@ -158,6 +158,22 @@ test("a held window a queued saved-video job will already cut is answered in inF } }); +// Review 4 C: an item's page address is a full http(s) address, or that item +// is refused with the reason (and its batch, at the job's door). +test("an item whose webpageUrl is not an http(s) address is refused", async () => { + const bad = ["x.com/u/status/1", "t.co/AbC", "ftp://example.org/a.mp4"]; + const r = await fetchWindowsAction({ items: bad.map((webpageUrl, i) => ({ slug: SLUG, id: "held1", from: 1 + i, to: 2 + i, webpageUrl })), requestedBy: "test", dryRun: true }); + assert.ok(r.ok); + if (!r.ok) return; + assert.equal(r.groups.length, 0); + assert.deepEqual(r.unresolved.map((u) => u.item.webpageUrl), bad); + for (const u of r.unresolved) assert.match(u.error, /^webpageUrl must be an http\(s\) address/); + const { fetchWindowsJobAction } = await import("./fetchWindowsAction"); + const job = await fetchWindowsJobAction({ items: [{ slug: SLUG, id: "held1", from: 1, to: 2, webpageUrl: "x.com/u/status/1" }], requestedBy: "test", queueKey: "platform:twitter" }); + assert.equal(job.ok, false); + assert.match(job.ok ? "" : job.error, /webpageUrl must be an http\(s\) address/); +}); + // Release 29 E2: a recording gone from its platform (lib/sourceGone.ts) has no // page to fetch from — refused at the door — unless the item names a copy's // URL (find-copy), which is the only way such a window is fetched. diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -1,6 +1,7 @@ "use server"; import { localMediaFetchRefusal } from "yt-dlp-transcript-common/lib/localMedia"; +import { isFullPageAddress, pageAddressRefusal } from "yt-dlp-transcript-common/lib/clipWindow"; import path from "node:path"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; @@ -12,6 +13,7 @@ import { clipWindowQueueKey, resolveQueueKey, } from "yt-dlp-transcript-common/lib/queueKeys"; +import { isXUrl, X_QUEUE_KEY } from "yt-dlp-transcript-common/lib/xJobRule"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs"; import { detectPlatform, queueKeyForUrl } from "yt-dlp-transcript-common/lib/platform"; @@ -213,6 +215,14 @@ function itemProblem(item: FetchWindowsItem): string | null { return null; } +// A local channel's page address from the caller (lib/clipWindow.ts +// isFullPageAddress, review 4 C). Every item a job is handed has been planned, +// so its address is a checked one. +function pageAddressProblem(item: FetchWindowsItem): string | null { + const page = typeof item.webpageUrl === "string" ? item.webpageUrl.trim() : ""; + return page && !isFullPageAddress(page) ? pageAddressRefusal(page) : null; +} + // Validate, answer the cache, resolve every URL and group by queue. Nothing is // started; nothing touches the network. async function planFetchWindows( @@ -300,6 +310,11 @@ async function planFetchWindows( unresolved.push({ item, error: localRefusal }); continue; } + const pageRefusal = isRemoteOnlyChannel(config) ? null : pageAddressProblem(item); + if (pageRefusal) { + unresolved.push({ item, error: pageRefusal }); + continue; + } // The item names a RECORD; its directory may be another id — a Twitch // record's v<n> is data/<n>/ (release 23 F1). The item keeps its id. const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { @@ -465,8 +480,9 @@ async function planFetchWindows( }); continue; } + // An X page (a t.co link too) is X's: X's queue (review 3 M2/S6). const queueKey = resolveQueueKey( - whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)), + isXUrl(url) ? X_QUEUE_KEY : whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)), queueOverride, ); // One job per queue. Two platforms sharing a queue (an override) share a @@ -538,7 +554,7 @@ export async function fetchWindowsJobAction(req: { }; } for (const item of req.items) { - const problem = itemProblem(item); + const problem = itemProblem(item) ?? pageAddressProblem(item); if (problem) return { ok: false, error: `${fetchWindowsItemLabel(item)}: ${problem}` }; } const paths = getPaths(); diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -9,8 +9,10 @@ import { import { TRANSCRIPTION_QUEUE, channelQueueKey, + downloadQueueKey, resolveQueueKey, } from "yt-dlp-transcript-common/lib/queueKeys"; +import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { countNotYetTranscribed, readChannelStat, @@ -389,9 +391,13 @@ export async function checkKeptDeletedAction( queueKey?: string, ): Promise<StreamActionResult> { const paths = getPaths(); + // An X channel's check asks x.com (an availability probe per video): X's + // queue, X's gap and X's job cap (review 2 S5; lib/xJobRule.ts). + const config = await readChannelConfig(paths, slug).catch(() => null); + const own = config && downloadQueueKey(config) === "platform:twitter" ? "platform:twitter" : channelQueueKey(slug); return runManagedFunction({ kind: "check-kept-deleted", - queueKey: resolveQueueKey(channelQueueKey(slug), queueKey), + queueKey: resolveQueueKey(own, queueKey), paths, channelSlug: slug, spec: { kind: "check-kept-deleted", slug, params: { queueKey } }, diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -28,6 +28,7 @@ import { reparseXTrendingRead, runXTrendingRead, X_TRENDING_QUEUE, + xTrendingTabsAsked, type ReadXTrendingAsk, type ReadXTrendingResult, } from "yt-dlp-transcript-common/controller/readXTrending"; @@ -79,6 +80,7 @@ import { import { publishXTrendingTopic, type PublishXTrendingResult } from "yt-dlp-transcript-common/controller/publishXTrending"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { capturePostsAction } from "./socialActions"; +import { xJobCounts } from "yt-dlp-transcript-common/lib/xJobRule"; import { recompileChannelPriorityAction } from "../actions"; import { xPressInFlight } from "../../lib/cookieRefreshGuard"; @@ -169,7 +171,11 @@ async function afterXTrendingRead( // 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); + // Media only (no shots) asks x.com nothing and does not count against X's + // job cap (lib/xJobRule.ts xJobCounts, ruling R-a): the cap does not hold it. + const plan = { shots: follow.shots, media: true, articles: false, ...(follow.shots ? {} : { avatars: false, context: false }) }; + const counts = xJobCounts({ kind: "capture-posts", params: plan, channel: { library: true } }); + const refusal = await refuseWatchJob(getPaths(), slug, undefined, { counts }); if (refusal) { onLog(`The media of ${what} was not queued, and the watch is paused: ${refusal.sentence}`); return; @@ -267,6 +273,7 @@ export type WatchXTrendingAsk = { intervalMinutes?: unknown; hours?: unknown; shots?: boolean; + tabs?: unknown; by?: unknown; }; @@ -346,6 +353,9 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc 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; + // The tabs each tick reads: as a read's ("top", "latest" or both). + const tabs = ask.tabs === undefined ? undefined : xTrendingTabsAsked(ask.tabs); + if (tabs && !tabs.ok) return { ok: false, error: tabs.error }; const now = Date.now(); const set = await setXTrendingWatch(lib.channelRoot, { topics: await readXTrendingTopics(lib.channelRoot), @@ -354,6 +364,7 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc intervalMinutes: terms.terms.intervalMinutes, hours: terms.terms.hours, ...(ask.shots !== undefined ? { shots: ask.shots } : {}), + ...(tabs?.ok ? { tabs: tabs.tabs } : {}), by: ask.by === "operator" ? "operator" : "agent", maxTopics: xTrendingWatchMaxTopics(config), now, diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -457,9 +457,9 @@ test("a library refuses a URL and a cap out of range, in sentences", () => { parseChannelForm(form({ handling: "transcribe", platform: "x-trending", ...fields })); assert.throws(refused({ url: "https://x.com/i/trending/1900000000000000001" }), /An X trending library has no URL/); assert.throws(refused({ url: "https://x.com/example_user" }), /An X trending library has no URL/); - assert.throws(refused({ xTrendingMaxScrolls: "21" }), /scroll cap is a whole number, 1–20/); - assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–200/); - assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–200/); + assert.throws(refused({ xTrendingMaxScrolls: "41" }), /scroll cap is a whole number, 1–40/); + assert.throws(refused({ xTrendingMaxPosts: "0" }), /post cap is a whole number, 1–400/); + assert.throws(refused({ xTrendingMaxPosts: "many" }), /post cap is a whole number, 1–400/); // An ordinary X account is not a library. assert.equal(parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config.xTrending, undefined); }); diff --git a/editor/app/jobs/[id]/page.tsx b/editor/app/jobs/[id]/page.tsx @@ -98,6 +98,15 @@ export default async function JobDetailPage({ /> {/* Why, when no person pressed Cancel: the boot pass's reason for a job a restart left queued (JobMeta.cancelReason). */} + {/* A job X's job cap deferred at its start: it did not run (JobMeta.deferred). */} + {job.status === "done" && job.deferred && ( + <Cell + label="Deferred" + value={job.deferred.sentence} + className="col-span-2 sm:col-span-4" + testId="job-deferred" + /> + )} {job.status === "cancelled" && job.cancelReason && ( <Cell label="Cancelled because" diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx @@ -264,9 +264,9 @@ function JobRowHeading({ ? `uppercase tracking-wide px-1.5 py-0.5 rounded text-[10px] ${statusColor(job.status)}` : `text-xs uppercase tracking-wide px-2 py-0.5 rounded ${statusColor(job.status)}` } - title={cancelReasonOf(job)} + title={cancelReasonOf(job) ?? job.deferred?.sentence} > - {job.status} + {job.status === "done" && job.deferred ? "deferred" : job.status} </span> )} <span diff --git a/editor/app/scheduler/runTick.ts b/editor/app/scheduler/runTick.ts @@ -5,6 +5,7 @@ // row and two forms import from it. import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard"; +import { xCapHeldReason, xCapRoom } from "yt-dlp-transcript-common/jobs/networkGuard"; import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; @@ -12,9 +13,12 @@ import { activeSyncJobs } from "yt-dlp-transcript-common/jobs/syncJobs"; import type { SyncSchedulerSettings } from "yt-dlp-transcript-common/lib/settings"; import { isInQuietHours, - nextEligibleAfterFailure, + foldScheduledSyncOutcome, selectDueChannels, isInstagramPostsConfig, + limitXSyncs, + xJobsWaiting, + xSyncHold, type ChannelEntry, } from "yt-dlp-transcript-common/jobs/syncScheduler"; import { @@ -141,6 +145,8 @@ export async function runSchedulerTick(): Promise<SchedulerTickResult> { jitter: pacingJitter(), // Instagram's alert or cooldown: its channels take no slot while it is up. instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null, + // X's job cap (common/lib/xJobRule.ts): its channels take no slot while it is reached. + xCapHeld: channels.some((c) => xSyncHold(c.config, "x") !== null) ? await xCapHeldReason(paths) : null, focusSlugs: resolveFocusSlugs( priority, siteChannels, @@ -151,10 +157,23 @@ export async function runSchedulerTick(): Promise<SchedulerTickResult> { // Concurrency cap doubles as the stagger: queue at most (cap - running) // channels; the rest roll to the next tick instead of fanning out at once. const slots = Math.max(0, scheduler.maxConcurrentSyncs - running); - const toQueue = due.slice(0, slots); + let toQueue = due.slice(0, slots); for (const slug of due.slice(slots)) { skipped.push({ slug, reason: "concurrency cap (deferred to next tick)" }); } + // NO MORE X SYNCS THAN X'S CAP HAS STARTS LEFT (review 3 N9): the rest + // would each be deferred at its start. A look at the count, no start. + const isXSync = (slug: string) => { + const config = channels.find((c) => c.slug === slug)?.config; + return config ? xSyncHold(config, "x") !== null : false; + }; + if (toQueue.some(isXSync)) { + // Queued on X's queue, or running there with no start counted yet (review 4 D). + const waiting = xJobsWaiting(getRegistry().list()); + const limited = limitXSyncs(toQueue, isXSync, { room: await xCapRoom(paths), waiting }); + toQueue = limited.queue; + skipped.push(...limited.held); + } const queued: string[] = []; const bySlug = new Map(channels.map((c) => [c.slug, c.config])); @@ -277,23 +296,8 @@ function reconcileOutcomes( cs.lastQueuedJobId = null; // evicted; can't read outcome continue; } - if (job.status === "queued" || job.status === "running") continue; - if (job.status === "done") { - cs.consecutiveFailures = 0; - cs.nextEligibleAt = null; - cs.lastOutcome = "ok"; - cs.lastOutcomeAt = job.endedAt ?? now; - } else if (job.status === "failed") { - cs.consecutiveFailures += 1; - cs.nextEligibleAt = nextEligibleAfterFailure( - now, - cs.consecutiveFailures, - scheduler, - pacingJitter(), - ); - cs.lastOutcome = "failed"; - cs.lastOutcomeAt = job.endedAt ?? now; - } - cs.lastQueuedJobId = null; + // Done, failed, cancelled — and DEFERRED by X's job cap, which is + // neither a success nor a failure (common/jobs/syncScheduler.ts). + foldScheduledSyncOutcome(cs, job, now, scheduler, pacingJitter()); } } diff --git a/editor/app/scheduler/status.ts b/editor/app/scheduler/status.ts @@ -7,7 +7,8 @@ import { } from "yt-dlp-transcript-common/views/schedulerStatus"; import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState"; import { instagramHeldReason } from "yt-dlp-transcript-common/jobs/instagramGuard"; -import { isInstagramPostsConfig } from "yt-dlp-transcript-common/jobs/syncScheduler"; +import { isInstagramPostsConfig, xSyncHold } from "yt-dlp-transcript-common/jobs/syncScheduler"; +import { xCapHeldReason } from "yt-dlp-transcript-common/jobs/networkGuard"; import { resolveHeartbeatSeconds } from "./heartbeat"; // THE SHELL. The payload is `common/views/schedulerStatus.ts`; this reads the @@ -30,5 +31,6 @@ export async function buildSchedulerStatusPayload(): Promise<SchedulerStatusPayl heartbeatSeconds: resolveHeartbeatSeconds(), // Asked only when there is an Instagram channel to say it about. instagramHeld: channels.some((c) => isInstagramPostsConfig(c.config)) ? await instagramHeldReason(paths) : null, + xCapHeld: channels.some((c) => xSyncHold(c.config, "x") !== null) ? await xCapHeldReason(paths) : null, }); } diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs @@ -138,7 +138,16 @@ const TWEETS = [ }, ]; -for (const tweet of TWEETS.slice(0, limit)) { +// A RESUMED WALK IS BELOW WHAT IT SHOWED BEFORE. Handed a resume point +// (`-o extractor.twitter.cursor=<place>`; "1/" asks for the top), the real +// gallery-dl continues from it and never prints the timeline's newest posts +// again: a resumed backfill whose first posts ARE the newest is taken for one +// that began again from the top, and is stopped (xGalleryDlFetcher.ts). This +// account has three posts, so below them is the timeline's end: nothing more. +const place = args.find((a) => a.startsWith("extractor.twitter.cursor="))?.slice("extractor.twitter.cursor=".length); +const resumed = Boolean(place) && place !== "1/"; + +for (const tweet of resumed ? [] : TWEETS.slice(0, limit)) { process.stdout.write(JSON.stringify(tweet) + "\n"); } diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -20,11 +20,16 @@ import { baseUrl } from "./baseUrl"; // under playwright's loader (digest.spec.ts says why). import { FIXTURE_FIRST_PAGE, - FIXTURE_TIMELINE_OP, + FIXTURE_SUMMARY, + FIXTURE_TITLE, + FIXTURE_TOP_TIMELINE, FIXTURE_TREND_URL, fixtureContinuation, fixtureTimelineBody, + fixtureTimelineUrl, fixtureTrendingResponses, + fixtureTwoTabResponses, + FIXTURE_LATEST_PAGE, } from "../../common/social/__fixtures__/xTrendingCapture"; const TOKEN = "test-worker-token"; @@ -96,6 +101,8 @@ test("an X trending library: the form, one read, the library by topic, the listi // One read, into a named topic. await page.getByLabel("trending page URL").fill(`${FIXTURE_TREND_URL}?src=trend_click`); await page.getByLabel("topic", { exact: true }).fill("Kettle Festival"); + // One tab here: the page's other tab is the two-tab test's (the last one in this file). + await page.getByLabel("tabs", { exact: true }).selectOption("top"); await page.getByRole("button", { name: "Read trending page" }).click(); // Four posts: the promoted entry, the quoted post and another surface's post are not the page's. await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); @@ -111,24 +118,38 @@ test("an X trending library: the form, one read, the library by topic, the listi await expect .poll(async () => (await readdir(`${readsDir}/${readId}`)).sort(), { timeout: 15_000 }) .toEqual(["page.png", "read.json", "responses.jsonl"]); - const record = await readJson<{ outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; sentence: string }>( - rel(`channels/${SLUG}/trending/reads/${readId}/read.json`), - ); + // read.json is written TWICE: when the read starts (stop "started", outcome "error": what a read that + // died is left as) and when it ends. The posts are on disk before the second write, so the record is + // read until it is the final one — never once, and never after a wait. + type ReadRecord = { outcome: string; stop: string; scrolls: number; posts: { onPage: number; added: number }; operations: { op: string }[]; tabs?: Record<string, unknown>[]; sentence: string }; + const recordFile = rel(`channels/${SLUG}/trending/reads/${readId}/read.json`); + // A read between the two halves of the atomic write finds no file, or half of one: asked again. + const readRecord = () => readJson<ReadRecord>(recordFile).catch(() => null); + await expect.poll(async () => (await readRecord())?.stop ?? "started", { timeout: 30_000 }).not.toBe("started"); + const record = (await readRecord())!; expect(record.outcome).toBe("read"); expect(record.stop).toBe("idle"); expect(record.scrolls).toBe(3); expect(record.posts).toEqual({ onPage: 4, added: 4 }); expect(record.operations.map((o) => o.op)).toEqual(["ExampleTrendPage", "ExampleTrendTimeline", "HomeTimeline"]); - expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival).`); + // Which of the page's tabs the read saw: the label and a count. + expect(record.tabs).toEqual([{ tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: false }]); + expect(record.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 4 posts on the page, 4 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" tab.`); const recordText = await readFile(t(`channels/${SLUG}/trending/reads/${readId}/read.json`), "utf8"); expect(recordText).not.toContain("teapot_news"); expect(recordText).not.toContain("festival opens"); + expect(recordText).not.toContain(FIXTURE_TOP_TIMELINE); // The library by topic. await page.reload(); const topic = page.locator('[data-x-trending-topic="kettle-festival"]'); await expect(topic).toContainText("Kettle Festival · 4 posts"); await expect(topic).toContainText(FIXTURE_TREND_URL); + // X's own words for the page, beside the operator's name for the topic; and the tab the read saw. + const source = topic.locator("[data-x-trending-source]"); + await expect(source.locator("[data-x-trending-x-title]")).toContainText(`X’s title: ${FIXTURE_TITLE}`); + await expect(source.locator("[data-x-trending-x-summary]")).toHaveText(`X’s summary: ${FIXTURE_SUMMARY}`); + await expect(source.locator("[data-x-trending-tab]")).toContainText("the last read saw the “Top” tab of “Top”, “Latest”"); await expect(topic.locator("[data-x-trending-post]")).toHaveCount(4); const first = topic.locator('[data-x-trending-post="1900000000000001001"]'); await expect(first).toContainText("@teapot_news (Teapot News)"); @@ -143,12 +164,12 @@ test("an X trending library: the form, one read, the library by topic, the listi const listed = await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}&topic=kettle-festival`, { headers: AUTH }); expect(listed.status()).toBe(200); const body = (await listed.json()) as { - topics: { id: string; title: string; posts: number; sources: { url: string; reads: number }[] }[]; + topics: { id: string; title: string; posts: number; sources: { url: string; reads: number; title?: string; summary?: string; tabs?: string[]; lastReadTab?: string }[] }[]; posts: { id: string; author: string; text: string; media: { count: number; kinds: string[] }; topic: string; reads: { read: string }[] }[]; total: number; reads: string[]; }; - expect(body.topics).toMatchObject([{ id: "kettle-festival", title: "Kettle Festival", posts: 4, sources: [{ url: FIXTURE_TREND_URL, reads: 1 }] }]); + expect(body.topics).toMatchObject([{ id: "kettle-festival", title: "Kettle Festival", posts: 4, sources: [{ url: FIXTURE_TREND_URL, reads: 1, title: FIXTURE_TITLE, summary: FIXTURE_SUMMARY, tabs: ["Top", "Latest"], lastReadTab: "Top" }] }]); expect(body.posts.map((p) => p.id)).toEqual(["1900000000000001001", "1900000000000001002", "1900000000000001004", "1900000000000001005"]); expect(body.posts[3]).toMatchObject({ author: "lid_watch", media: { count: 1, kinds: ["gif"] }, topic: "kettle-festival", reads: [{ read: readId }] }); expect(body.total).toBe(4); @@ -235,7 +256,8 @@ test("an X trending library: judgements, a watch tick, media kept once, gone fro trending: { load: [ { - url: `https://x.com/i/api/graphql/fixtureQueryId2/${FIXTURE_TIMELINE_OP}?variables=%7B%7D`, + // The timeline's first request, as the page sends it: it names the timeline and carries no cursor. + url: fixtureTimelineUrl(), status: 200, body: fixtureTimelineBody([FIXTURE_FIRST_PAGE[0], { id: NEW, handle: "spout_clips", text: "Two pictures of the queue.", media: ["photo", "photo"] }]), }, @@ -542,3 +564,90 @@ test("an X trending library: rename, move, merge; a topic published into an ordi const twice = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); expect(String(twice.json.error)).toContain("@saucer_fan is already archived: saucer_fan-x."); }); + +// ADDED SCOPE R3 (lane x-followups): one job reads the page's "Top" tab and +// then presses its "Latest" tab. The fake page has both (invented data); no +// browser, no request. +test("an X trending library: one read covers Top and Latest; a Latest that never loads is said and is no failure; a post that leaves Latest is gone from that tab only", async ({ page, request }) => { + test.setTimeout(240_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> }; + }; + type Tab = { tab?: string; asked?: string; posts: number; scrolls?: number; stop?: string; pageEnd?: boolean; why?: string }; + type Record_ = { stop: string; outcome: string; sentence: string; tabs?: Tab[] }; + const fake = (trending: unknown) => + writeFile(t(".fake-x-profile-cookies.json"), JSON.stringify({ cookies: [{ name: "auth_token", value: "fixture-not-a-real-token", domain: ".x.com" }], trending })); + const readsDir = t(`channels/${SLUG}/trending/reads`); + const readIds = async () => (await readdir(readsDir).catch(() => [] as string[])).filter((n) => n.startsWith("tr-")).sort(); + // The n-th read's final record (read.json is written when a read starts and again when it ends). + const finished = async (n: number): Promise<Record_> => { + await expect.poll(async () => (await readIds()).length, { timeout: 60_000 }).toBe(n); + const file = rel(`channels/${SLUG}/trending/reads/${(await readIds())[n - 1]}/read.json`); + const read = () => readJson<Record_>(file).catch(() => null); + await expect.poll(async () => (await read())?.stop ?? "started", { timeout: 90_000 }).not.toBe("started"); + return (await read())!; + }; + const idle = () => + expect.poll(async () => ((await (await request.get(`${baseUrl}/api/ops/jobs?active=1&slug=${SLUG}`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs?.length ?? 0, { timeout: 60_000 }).toBe(0); + const listing = async () => + (await (await request.get(`${baseUrl}/api/ops/trending?slug=${SLUG}`, { headers: AUTH })).json()) as { + topics: { sources: { lastReadTab?: string; lastReadTabs?: string[] }[] }[]; + posts: { id: string; reads: { tab?: string }[]; gone?: { at: string }; goneTabs?: { tab: string }[] }[]; + }; + expect((await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } })).status).toBe(200); + + // 1. BOTH TABS, ONE JOB (the default): Top's four posts, and the one only Latest shows. + await fake(fixtureTwoTabResponses()); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); + const first = await finished(1); + expect(first.outcome).toBe("read"); + expect(first.tabs).toEqual([ + { tab: "Top", asked: "top", posts: 4, scrolls: 3, stop: "idle", pageEnd: true }, + { tab: "Latest", asked: "latest", posts: 3, scrolls: 2, stop: "idle", pageEnd: true }, + ]); + expect(first.sentence).toBe(`Read ${FIXTURE_TREND_URL}: 5 posts on the page, 5 new, in topic "Kettle Festival" (kettle-festival), shown by the page's "Top" and "Latest" tabs.`); + expect((await readdir(`${readsDir}/${(await readIds())[0]}`)).sort()).toEqual(["page-latest.png", "page.png", "read.json", "responses.jsonl"]); + await idle(); + const one = await listing(); + expect(one.topics[0].sources[0].lastReadTabs).toEqual(["Top", "Latest"]); + expect(one.posts.find((p) => p.id === "1900000000000001001")?.reads.map((r) => r.tab)).toEqual(["Top", "Latest"]); + expect(one.posts.find((p) => p.id === "1900000000000001009")?.reads.map((r) => r.tab)).toEqual(["Latest"]); + await page.goto(`${baseUrl}/channels/${SLUG}`); + await expect(page.locator("[data-x-trending-source] [data-x-trending-tab]")).toContainText("the last read saw the “Top” and “Latest” tabs"); + // "tabs" is top, latest or both: anything else is refused with a sentence, before any job. + const bad = await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, tabs: ["media"] }); + expect(bad.status).toBe(400); + expect(String(bad.json.error)).toBe('"tabs" is ["top"], ["latest"] or ["top", "latest"] (the default: both, read in one job)'); + + // 2. A POST LEAVES LATEST between two reads: Latest now lists one post; 1001 is still on Top, 1009 was only ever on Latest. + await fake(fixtureTwoTabResponses([FIXTURE_LATEST_PAGE[2]])); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); + const second = await finished(2); + expect(second.sentence).toContain('1 post this page showed before is gone from the page at'); + expect(second.sentence).toContain('1 post is gone from the "Latest" tab and still shown by another.'); + await idle(); + const two = await listing(); + expect(two.posts.find((p) => p.id === "1900000000000001001")?.goneTabs?.map((g) => g.tab)).toEqual(["Latest"]); + expect(two.posts.find((p) => p.id === "1900000000000001001")?.gone).toBeUndefined(); + expect(two.posts.find((p) => p.id === "1900000000000001009")?.gone).toBeTruthy(); + await page.reload(); + await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone-tab="Latest"]')).toContainText("Gone from the “Latest” tab at"); + await expect(page.locator('[data-x-trending-post="1900000000000001001"] [data-x-trending-gone]')).toHaveCount(0); + await expect(page.locator('[data-x-trending-post="1900000000000001009"] [data-x-trending-gone]')).toContainText("Gone from the page at"); + + // 3. A LATEST TAB THAT NEVER LOADS: pressed, and the page asks nothing for it. The read waits its 20 s, says so, and is a read. + const never = fixtureTwoTabResponses(); + never.tabs.Latest = {}; + await fake(never); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); + const third = await finished(3); + expect(third.outcome).toBe("read"); + expect(third.tabs?.[1]).toEqual({ tab: "Latest", asked: "latest", posts: 0, scrolls: 0, stop: "not-read", pageEnd: false, why: 'pressing "Latest" brought no answer for its timeline within 20 s' }); + expect(third.sentence).toContain('Top read; Latest not read: pressing "Latest" brought no answer for its timeline within 20 s.'); + await idle(); + // Nothing is retried: three reads were asked for, and three there are; nothing new is said of Latest's posts. + expect(await readIds()).toHaveLength(3); + expect((await listing()).posts.find((p) => p.id === "1900000000000001005")?.gone).toBeUndefined(); +}); diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -20,7 +20,19 @@ const LISTING = { id: "kettle-festival", title: "Kettle Festival", posts: 2, - sources: [{ trendId: "1900000000000000001", url: TREND, reads: 2, lastReadAt: "2026-11-17T12:00:00.000Z" }], + sources: [ + { + trendId: "1900000000000000001", + url: TREND, + title: "Kettle festival opens", + summary: "The annual kettle festival opened this morning.", + lastUpdatedAt: "2026-11-16T11:30:00.000Z", + tabs: ["Top", "Latest"], + lastReadTab: "Top", + reads: 2, + lastReadAt: "2026-11-17T12:00:00.000Z", + }, + ], }, ], posts: [ @@ -33,7 +45,7 @@ const LISTING = { text: "The kettle festival\nopens today.", media: { count: 2, kinds: ["image"] }, topic: "kettle-festival", - reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z" }], + reads: [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", tab: "Top" }], }, { id: "1900000000000001002", @@ -69,7 +81,9 @@ test("x_trending_topics: the library's topics, their pages and reads", async () [ "X trending library trending: 1 topic, 5 posts (private: on no site, in no index)", '- kettle-festival — "Kettle Festival": 2 posts', - ` ${TREND} · read 2×, last 2026-11-17 12:00 UTC`, + ` ${TREND} · read 2×, last 2026-11-17 12:00 UTC · the last read saw the "Top" tab of "Top", "Latest"`, + " X's title: Kettle festival opens (X updated it 2026-11-16 11:30 UTC)", + " X's summary: The annual kettle festival opened this morning.", `Saved reads (newest first): ${READ}`, ].join("\n"), ); @@ -90,7 +104,7 @@ test("x_trending_posts: each post's id, author, words, media, reads and topic", "1. 1900000000000001001 @teapot_news (Teapot News) · 2026-11-16 12:00 UTC · 2 media (image) · topic kettle-festival", " https://x.com/teapot_news/status/1900000000000001001", " The kettle festival / opens today.", - ` shown by: ${READ} (2026-11-17 10:00 UTC)`, + ` shown by: ${READ} (2026-11-17 10:00 UTC, the "Top" tab)`, "2. 1900000000000001002 @saucer_fan · 2026-11-16 13:00 UTC · no media · topic kettle-festival", " https://x.com/saucer_fan/status/1900000000000001002", " Second.", @@ -156,7 +170,7 @@ test("the tools say a topic's watch, and a post's thread, capture, gone-from-the 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)`, + ` shown by: ${READ} (2026-11-17 10:00 UTC, the "Top" tab)`, " 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", @@ -203,3 +217,32 @@ test("the MCP has a tool to read a library's accounts and none to organise or pu const names = (await client.listTools()).tools.map((t) => t.name).filter((n) => /trending/.test(n)); assert.deepEqual(names.sort(), ["x_trending_accounts", "x_trending_posts", "x_trending_topics"]); }); + +// Review 1: X's summary is listed at most 600 characters long. +test("x_trending_topics cuts a long summary of X's at 600 characters, at a word", async () => { + const summary = Array.from({ length: 150 }, (_, i) => `word${i}`).join(" "); + const listing = { ...LISTING, topics: [{ ...LISTING.topics[0], sources: [{ ...LISTING.topics[0].sources[0], summary }] }] }; + const { deps } = fakeEditor(() => ({ status: 200, body: listing }), env); + const client = await connectWith(deps); + const line = body(await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } })).split("\n").find((l) => l.includes("X's summary: "))!; + const said = line.replace(" X's summary: ", ""); + assert.ok(said.length <= 600 && said.endsWith("…"), String(said.length)); + assert.ok(summary.startsWith(said.slice(0, -1))); +}); + +// Added scope R3: a read covers both tabs; a post may be gone from one tab only. +test("the tools say both tabs of a two-tab read, and a post gone from one tab while another still shows it", async () => { + const listing = { + ...LISTING, + topics: [{ ...LISTING.topics[0], sources: [{ trendId: "1900000000000000001", url: TREND, tabs: ["Top", "Latest"], lastReadTabs: ["Top", "Latest"], reads: 1, lastReadAt: "2026-11-17T12:00:00.000Z" }] }], + posts: [{ ...LISTING.posts[0], goneTabs: [{ tab: "Latest", at: "2026-11-18T10:30:00.000Z", read: READ }] }], + 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, / · read 1×, last 2026-11-17 12:00 UTC · the last read saw the "Top" and "Latest" tabs$/m); + const posts = body(await client.callTool({ name: "x_trending_posts", arguments: { channel: "trending" } })); + assert.match(posts, new RegExp(`^ gone from the "Latest" tab at 2026-11-18 10:30 UTC \\(read ${READ}\\); another tab still shows it$`, "m")); + assert.doesNotMatch(posts, /gone from the page/); +}); diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -25,7 +25,19 @@ type Topic = { id: string; title: string; posts: number; - sources?: Array<{ trendId: string; url: string; title?: string; summary?: string; reads: number; lastReadAt: string | null }>; + sources?: Array<{ + trendId: string; + url: string; + title?: string; + summary?: string; + // When X last rewrote its title and summary; the page's tabs by label; the tab the last read saw. + lastUpdatedAt?: string; + tabs?: string[]; + lastReadTab?: string; + lastReadTabs?: 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 } }; }; @@ -39,16 +51,28 @@ type PostRow = { text: string; media?: { count: number; kinds?: string[]; thumbnail?: string }; topic: string; - reads?: Array<{ read: string; trendId: string; at: string }>; + reads?: Array<{ read: string; trendId: string; at: string; tab?: 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 }; + // A tab's read reached its end without it while another tab still shows it. + goneTabs?: Array<{ tab: string; at: string; read: 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[] }; +// X's summary of a page, at most this long here (the editor's listing cuts it +// the same way; the whole text stays in the library). +export const X_TRENDING_SUMMARY_MAX = 600; +function listedSummary(summary: string): string { + if (summary.length <= X_TRENDING_SUMMARY_MAX) return summary; + const cut = summary.slice(0, X_TRENDING_SUMMARY_MAX - 1); + const word = cut.lastIndexOf(" "); + return `${(word > X_TRENDING_SUMMARY_MAX * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; +} + const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "?"); export function renderXTrendingTopics(slug: string, body: ListingBody): string { @@ -58,8 +82,14 @@ export function renderXTrendingTopics(slug: string, body: ListingBody): string { for (const t of topics) { lines.push(`- ${t.id} — "${t.title}": ${t.posts} post${t.posts === 1 ? "" : "s"}`); for (const s of t.sources ?? []) { - lines.push(` ${s.url}${s.title ? ` "${s.title}"` : ""} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC`); - if (s.summary) lines.push(` X's summary: ${s.summary}`); + const tab = s.lastReadTabs?.length + ? ` · the last read saw the ${s.lastReadTabs.map((t) => `"${t}"`).join(" and ")} tabs` + : s.lastReadTab + ? ` · the last read saw the "${s.lastReadTab}" tab${s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((t) => `"${t}"`).join(", ")}` : ""}` + : ""; + lines.push(` ${s.url} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC${tab}`); + if (s.title) lines.push(` X's title: ${s.title}${s.lastUpdatedAt ? ` (X updated it ${day(s.lastUpdatedAt)} UTC)` : ""}`); + if (s.summary) lines.push(` X's summary: ${listedSummary(s.summary)}`); } if (t.watch) lines.push(` watch: ${t.watch.sentence}`); } @@ -78,7 +108,7 @@ export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: st const lines = [`X trending library ${slug}${topic ? `, topic ${topic}` : ""}: ${posts.length} of ${total} post${total === 1 ? "" : "s"}`]; if (posts.length === 0) lines.push("No post."); for (const [i, p] of posts.entries()) { - const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC)`).join(", "); + const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC${r.tab ? `, the "${r.tab}" tab` : ""})`).join(", "); lines.push( `${i + 1}. ${p.id} @${p.author}${p.authorName ? ` (${p.authorName})` : ""} · ${day(p.createdAt)} UTC · ${mediaText(p.media)} · topic ${p.topic}`, ); @@ -86,6 +116,7 @@ export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: st lines.push(` ${p.text.replace(/\s*\n\s*/g, " / ")}`); if (reads) lines.push(` shown by: ${reads}`); if (p.thread && p.thread !== p.id) lines.push(` in thread ${p.thread}`); + for (const g of p.goneTabs ?? []) lines.push(` gone from the "${g.tab}" tab at ${day(g.at)} UTC (read ${g.read}); another tab still shows it`); 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" : ""; @@ -210,7 +241,9 @@ export const X_TRENDING_TOOLS = [ name: "x_trending_topics", description: "An X TRENDING LIBRARY's topics: the operator's topics, each with the X trending pages " + - "(x.com/i/trending/<id>) read into it, how often and when, and its post count; and the " + + "(x.com/i/trending/<id>) read into it, how often and when, X's own title and summary of " + + "the page (X's words, not the operator's), which of the page's tabs the last read saw (a " + + "read covers Top and Latest in one job unless asked for one), and its post count; and the " + "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 " + @@ -230,10 +263,10 @@ export const X_TRENDING_TOOLS = [ name: "x_trending_posts", description: "The posts of an X TRENDING LIBRARY (or of one of its topics): each post's id, author, " + - "date, words, media by kind and count, the reads that showed it, its topic, and — once " + + "date, words, media by kind and count, the reads that showed it (and the page's tab), its topic, and — once " + "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 " + + "thread's), whether ONE TAB of the page stopped showing it while another still does, 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 " + diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -341,9 +341,195 @@ again by the watch; keeping the post asks again. - A file system that keeps no birth time leaves the directory proof with the inode alone. - The library's settings still have no form. +## The first real read, as fixed (lane `lane/x-followups`, 18 Nov) + +The first real read of a trending page saved 12 answers and 79 posts and stopped at its post cap after three +scrolls. What it showed, and what changed (shapes with invented data: `common/social/__fixtures__/xTrendingRealShape.ts`): + +- **The page's own answer was never parsed.** Slice 1 reserved `title` and `summary` on a topic's source "once the + parser knows where the page keeps them" and named every unnamed topic `Trending <number>`. The page keeps them in + one answer: `data.<key>.result.page` with `article.title`, `article.article_text.text`, `last_updated_at_ms` and + `post_timelines[] = {label, post_timeline.id}` (two tabs). `trendPageOf` finds it by shape. +- **The topic's name.** An unnamed topic is born with the page's title (its id stays `t-<number>`). A topic still + carrying the fallback name for that page takes the title at a read or a reparse. A topic made with a name asked + for, or whose last organise step is a rename, is never renamed by a read; a title another topic answers to is + not taken. One function decides, inside the topics file's lock (`recordXTrendingRead`). +- **Tabs.** A timeline request names its timeline (`variables.timelineId`) and, after the first, its cursor. The + read's tab is the page's tab with that timeline id: kept in `read.json` (`tabs`: label and count), on the + source's read and on each sighting (`seen[].tab`); a reparse fills it in. (R3 below: a read now covers both tabs.) +- **The page's end.** The first answer of a timeline ends with cursor entries; every later one carries its cursors + in `TimelineReplaceEntry` instructions. `timelineShapeOf` reads both. The continuation that shows the end is the + last answer's own timeline's; a capture listing two timelines shows no end; and "gone" does not count a sighting + known to be another tab's. +- **Not in the capture: the end of a timeline.** No builder guesses it. The rule stays what review 2 N4 made it + (the continuation from the previous bottom cursor brought nothing new, and nothing failed), which needs no + knowledge of the end's shape; whether the real page ever sends such an answer is still unseen. + +**Review 1, as fixed.** M1: the Add-channel form's Fetch details started gallery-dl against X outside any job; +the gallery-dl fetcher's probe now reads the handle off the URL (Nitter's, the Playwright fallback's and +Instagram's already made no request; the gallery-dl fetcher claims every x.com URL, so the form's yt-dlp probe is +never reached for one). S1: a search-phase place `3_<N>/` is checked exactly (a first-page post above N). S2: a +timeline-phase place says it may pass through archived posts first; it is not rewritten (nothing in gallery-dl's +source proves the archive unbroken down to its oldest post). S3: the read's tab is the one named timeline's. S4: +a topic is named from what its source holds, under the source's age guard. S5: a publish dry run says when the +topic is named by X's page (`titleFrom`). A topic's `titleFrom` is its own field; a listing gives 600 characters +of X's summary; no shipped module imports `common/testing` (`common/architecture.test.ts`). + +## Rulings of 18 Nov (the operator), as built in `lane/x-followups` + +**R1. The caps are raised so a read can reach a page's end.** Defaults 20 scrolls and 200 posts PER TAB (were 8 +and 60); maxima 40 and 400. A read's deadline is `120 s + tabs × scrolls × 12 s` (`readDeadlineMs`): 6 minutes for +one tab at 20 scrolls (what a read always had), 10 for both tabs at the defaults, 18 for both at the maximum. + +**R2. X jobs run on X's queue only, under an immutable cap.** `common/lib/xJobRule.ts` holds the rule +and its numbers: 12 X jobs started in any rolling 60 minutes, 150 in any rolling 24 hours, over every kind of X +job — ONE count for the machine (review 2 below; it was per login as first built). No setting, config key, environment variable, option, flag or queue changes them. +- The network guard treats a job as X's when its queue is X's OR its channel is on X (a job on another + platform's queue used to be taken for that platform's and met none of X's rules); refuses any queue but + `platform:twitter` at enqueue and at the start; refuses at enqueue when the cap is reached; and checks and + records one start in one step at the LAST guard before the job's work. An X run's own start asks X nothing: + each of its channels is one start. +- Where X is about to be asked the code asks again (`xJobContextRefusal`: a job of the editor's, on X's queue): + `fetchPosts`, `capturePosts`, `importPost`, `checkPostAvailability`, `runXTrendingRead`. +- The count is `transcripts/.x-session/job-starts.json` (`common/jobs/xJobCap.ts`), written under its lock, + kept across a restart; a file that cannot be read refuses every X job; a clock set back never frees a start + early. Its clock is the queue gap's. +- The scheduler skips X posts channels while the cap is reached; a watch's tick is skipped as for a cooldown. +- A job replayed at boot re-enters through its action and the same funnel, so both rules hold for it. + +**R3. A read covers "Latest" as well as "Top", in one job.** The reader scrolls the tab the page opens on to its +stop, then presses the page's own tab (by role `tab`, else `link`, else `button`, with the label the page's +answer gave), waits up to 20 s for the page's request for that tab's timeline, and scrolls it under the same +caps. It builds no request. +- One `responses.jsonl`; `page-latest.png` beside `page.png` (the page after the press, or after the try). +- The parser's end rule and post lists are per timeline. `read.json` `tabs`: per tab its label, what was asked, + posts, scrolls, stop, `pageEnd`, and `why` for a tab not read. +- Sightings are per read and tab; `goneTabs[<tab>]` marks a post a tab's complete read no longer shows; `gone` + (the page) is set once every tab that showed the post has such a mark. A read that cannot name its tab judges + only sightings that name none; a capture with no page answer is named through the tabs the source already knows + for its timeline ids. +- "Top read; Latest not read: <why>" is a read: no error, no strike, no retry. A 429, a 403 or a login wall on + either tab stops the whole read. +- `"tabs"` on `read-x-trending` and per watch; the default is both. +- NOT YET SEEN: the real Latest tab. Whether its control has the role and name assumed, and whether its timeline + answers have the shape of Top's, is confirmed by the first real two-tab read. The capture alone is enough to + put a wrong guess right: every answer the page fetched is in it, each with the timeline its request named, and + `read.json` says what the press did. + +**Ignored in the capture, listed.** `TrendRelevantUsers` and the first timeline answer's accounts module: the +accounts X names for the trend (the library's accounts listing counts authors of posts instead). `useStoryTopicQuery`: +other trends of the same story, with names and post counts (could propose pages to read). `result.contexts.topics` +and the page's `disclaimer`. A failed answer of ANY of the page's own operations (the badge poll included) makes a +read assert nothing about the page's end: conservative, left so. + +## Review 2 rulings (19 Nov), as built in `lane/x-followups` + +These are rulings, not reasons. + +- **ONE CAP FOR THE MACHINE.** Every counted X start is counted together, whatever the login source, the + cookie spec or the channel. A count keyed by a config string gave the same X account a fresh 12/150 for a + flipped source, a respelled spec or a channel's own spec. A count file of the first shape (one list per login) + is read as the sum of its lists. `get x-session` shows the one count and names no login. +- **WHAT COUNTS.** A job counts only if it can ask x.com with the login or X's cookies. One predicate, + `xJobCounts`, decides from the job's own plan at its start (its kind, its spec, its channel), never from a flag + a caller passes. A trending library's capture of media only (screenshots, articles, avatars and context off by + name; no thread shot, no avatars-only or context-only run, not a keep capture) takes files from X's two media + hosts with no cookie, no page and no logged-in fallback, so it does not count and the cap does not hold it. It + still runs on X's queue, under X's gap, X's cooldown and the watch's jar rule. A capture that could fall back to + the login counts. So do reads, fetches, imports, availability checks and each channel of an X run. The + transcription worker counts nowhere. +- **DEFERRED, NOT FAILED.** A job that reaches the cap at its start (it passed its enqueue while slots remained) + ends `done` with `deferred: {until, sentence}` on its record and meta and `[deferred] …` in its log. It is no + failure and no strike, and raises no banner. The scheduler folds it as neither success nor failure: the + failures stay, and the channel is not eligible before `until` (`foldScheduledSyncOutcome`). Nothing re-queues + it by itself. (A status of its own was not added: a new terminal status would reach every reader of job + statuses. `done` + `deferred` is what the /jobs row and the job page show as "deferred".) +- **A DELETED COUNT IS REBUILT, OR REFUSES.** With `job-starts.json` absent, the last 24 hours of counted starts + are rebuilt from the job records: every meta of X's queue carries `xStarts` (the starts it was counted for, + `[]` for none); a meta from before that counts once at its start when its kind and plan count. The rebuilt + count is written. If X's queue gap records an X job's end in the last 24 hours and the records cannot be listed, + a record of that day cannot be read, or no record of an X job is left, every X job is refused until they can be + (at the latest until that end is a day old). A corpus where no X job ever ran starts at zero. +- **GONE FROM THE PAGE NEEDS ONE READ OF EVERY TAB.** A post is gone from the page only when every tab that + showed it was read to its end without it IN THE SAME READ, and no tab of that read shows it. Marks from + different reads stay per tab ("gone from Latest at <time>") and never combine. A sighting from before tabs + were read names no tab and was the opening tab's (the source's first known tab, else "Top"): only a complete + read of that tab, or a read that cannot name its own tab, judges it. +- **THE LATEST PRESS IS THE PAGE'S OWN TAB.** Role `tab` only, looked up inside the page's tab list, by the exact + name the trend answer gave; never a link or a button. After the press the page must still be the trending page + (host and path), or the read stops at once, closes the browser and ends `Top read; Latest not read: the page + changed`. A press that fails (a throw, not actionable, a look-up deadline) is `Top read; Latest not read: + <why>`. The read's deadline inside Latest keeps Top's read: `Top read; Latest stopped at the deadline`, Latest's + `pageEnd` false. None is a strike. The wait for Latest's answer has its own 20 s wall clock. A tab the read says + was not read gives the library nothing. +- **WHICH JOBS ASK X** (`xJobAsksX`). X's queue (and its old clip queue) whatever the kind; an import of one URL + by that URL's host; an X channel's job unless its work asks no platform: `transcribe-one`, windows cut from the + saved copy (`clips:saved-video`), `import-media` of a local file, `import-archive-org`. Those pass off X's + queue (the transcription and every whisper-video's hand-off to it had been refused). X clip windows, an import + of an x.com address and an X channel's `check-kept-deleted` are queued on X's queue. `record-live` of an X + channel stays refused (it would hold X's queue for hours), and so does `redownload-incomplete-bucket` on one. + A caller's `network: false` (fetch-chat's replay on disk) still skips the guard, as before. + +## Review 3 (19 Nov), as built in `lane/x-followups` + +These are rulings, not reasons. + +- **A WINDOW ON `clips:saved-video` NEVER ASKS X.** It passes X's queue rule because it cuts from disk. If its + saved copy is gone or short when it runs, an X source's window fails ("the saved copy no longer covers this + window; ask again and it runs on X's queue"). Any other X window in a batch asks `xJobContextRefusal` before it is + fetched, and so does the single window's job. +- **A WINDOW IS X'S BY ITS URL, ON ANY CHANNEL.** `xJobAsksX` reads `params.webpageUrl` and + `params.items[].webpageUrl`: an X address makes the job X's (X's queue, the jar rule, the cap). A window with no + URL is its channel's (each item's channel, in a batch across channels). "No URL" never passes by itself. A copy's + or a mirror's address on another platform passes. `fetch-copies` passes, and its controller refuses a copy + whose address is X's. The single window and the batch queue an X address on X's queue. +- **X'S ADDRESSES** (`isXUrl`): x.com, twitter.com and their subdomains, and `t.co`. A host that merely ends in + "twitter.com" is not X's. +- **A LOST COUNT IS REBUILT ONLY FROM RECORDS SHOWN TO COVER THE DAY.** Retention never deletes an X job's + record while it may count. That covers retention by count and by age, and Clear logs. Since when it has kept + them is in `.jobs/x-records-kept.json`, written once. A rebuild that finds X activity in the day counts only + when that is over a day old. Otherwise it refuses and writes nothing. The refusal ends by itself within a day. + (Review 3 also took an old finished record as proof; review 4 removed it.) +- **THE WINDOWS ARE NOW MINUS THEIR LENGTH.** A start stamped after now counts in both windows. It never moves + the windows off the real starts and never prunes them. A start is recorded at the clock's time. +- **THE OPENING TAB IS THE ONE NAMED TOP**, wherever the page's answer lists it, else its first tab. +- **AFTER THE PAGE CHANGED, ONLY THE TREND'S OWN TIMELINES ARE READ.** Before this, the parser's filter was by + operation only. Now a tab not read because the page changed sets `pageTabsOnly` (on the read and on a + reparse). Only the timelines the trend answer names as its tabs are then ingested. The other answers stay + counted in the capture. +- **THE SCHEDULER QUEUES NO MORE X SYNCS THAN THE CAP HAS STARTS LEFT**, less the X jobs already waiting on X's + queue. It looks at the count and records nothing. + +## Review 4 (19 Nov), as built in `lane/x-followups` + +These are rulings, not reasons. + +- **THE MARKER IS THE ONLY PROOF THAT THE DAY'S RECORDS ARE ALL THERE.** A finished job that ended over a day ago + proves nothing: a job cancelled while queued has no log and is never pruned, and retention goes by id and + queue time, not by start. Without the marker over a day old, a rebuild refuses and writes nothing. The first + day after rollout with a missing starts file refuses: accepted. A marker dated after now is no proof: it is + said again at now, so the refusal ends within a day. +- **AN IMPORT BY AN X PAGE'S ADDRESS IS X'S, ON ANY CHANNEL.** `import-media` decides by `isXUrl`, so a `t.co` + link goes on X's queue under the jar rule and the cap. `xJobAsksX` judges `import-media` by its `url`. The + guards read it from `askParams`, because import-media has no replay descriptor. The metadata pass asks + `xJobContextRefusal` before it hands an X address to yt-dlp. +- **X'S ADDRESSES BY THE HOST ALONE:** lowercased, a trailing dot dropped. `twimg.com` and its subdomains are X's. + An address written without a scheme is X's when its first segment is an X host. A caller's `webpageUrl` for a + local channel, at `POST /api/media/fetch-window` or on a fetch-windows item, must begin `http://` or + `https://`. Otherwise it is refused (400, or the item's problem). A remote-only channel's is parsed and + written back, as before. +- **AN X JOB RUNNING WITH NO START RECORDED TAKES THE CAP'S ROOM** in the scheduler's count of X jobs waiting, + as a queued one does. + ## Open -- The real page's shape is confirmed only by the first probe. The parser is built so that a change is +- The END of a timeline is confirmed by no capture yet (above). The parser is built so that a change is local to `common/social/xTrendingParse.ts`. +- The first real read stopped at the old post cap (60) after three scrolls. With 200 posts and 20 scrolls per + tab a read can reach a page's end; whether a busy page has one within the caps is still to be seen. +- X's daily job cap (150) is below what the app can ask for at its own defaults: two topics watched at 30 + minutes (a watch's media-only capture no longer counts, so a topic is nearer 48 jobs a day than 96), an X run + over more than 150 channels, or more than 150 X channels on a daily sync. The cap refuses the excess; raising it + is the operator's code change. - 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 @@ -1316,7 +1316,16 @@ export function usage() { " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,", " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes", " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,", - " allowed, and reason (the refusal an X job would get). <slug> names a", + " allowed, and reason (the refusal an X job would get); and X's JOB CAP:", + " cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} -", + " at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON", + " THIS MACHINE: one count over every kind of X job, whatever the login", + " source, cookie spec or channel. A job past it is refused when queued,", + " with the time the next may start; one that meets it when its queue", + " starts it ends done, deferred (not failed). A library's media-only", + " capture is not counted. The numbers are constants of the code", + " (common/lib/xJobRule.ts): no setting, option or queue raises them.", + " <slug> names a", " channel whose own cookiesFromBrowser may decide the source. Nothing is", " asked of X: a refresh is Refresh cookies / Connect X account on", " /settings. Ask it before queueing fetch-posts or capture-posts on X.", @@ -1972,13 +1981,20 @@ export function usage() { " 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.", + " read into before, else a new one named for the page's own title).", + " \"tabs\": [\"top\"], [\"latest\"] or both (the default): BOTH ARE READ IN", + " THIS ONE JOB - Top to its stop, then the page's own Latest tab is", + " pressed and read under the same caps. A Latest that cannot be opened", + " ends the read \"Top read; Latest not read: <why>\", ok, nothing retried.", + " \"scrolls\": 1-40 moves to the bottom of a tab (default: the channel's", + " cap, else 20); \"posts\": stop a tab once 1-400 are seen on it (else", + " 200); a tab also stops after two scrolls with nothing new, and the whole", + " read 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.", + " the read within its deadline: 2 minutes plus 12 s for every scroll each", + " tab may make (both tabs at 20 scrolls: 10 minutes; one tab: 6; both at", + " 40: 18). Nothing retries.", " \"probe\": true saves the capture and its summary and writes no", " post. \"headed\": true opens a window on the editor's desktop. {\"slug\",", " \"reparse\": \"<readId>\"} parses a saved read again OFFLINE (X is asked", @@ -2104,6 +2120,8 @@ export function usage() { " 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.", + " \"tabs\": the page's tabs each tick reads, as read-x-trending's (the", + " default: both, in the one job).", ' "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,", @@ -2150,7 +2168,11 @@ export function usage() { ' "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.", + " search channel. It ends only at the timeline's end, its budget or a cap:", + " posts already archived are skipped, never taken for the end, and its", + " place is cleared only by the timeline's end. A resume that began again", + " from the top (the first posts read are the newest) stops at once with a", + " sentence and keeps its place.", "", 'capture-posts captures archived posts of a social channel (X, forum,', ' Bluesky): a screenshot of each through the connected X profile (a forum', diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -8,7 +8,7 @@ import type { Post } from "yt-dlp-transcript-common/lib/posts"; import { Badge } from "@/components/ui/badge"; import { Button, buttonVariants } from "@/components/ui/button"; import { useHydrated } from "@/components/ui/use-hydrated"; -import { captureSentence, filterWords, goneSentence, libraryHref } from "@/lib/library/filters.mjs"; +import { captureSentence, filterWords, goneSentence, goneTabSentence, libraryHref } from "@/lib/library/filters.mjs"; import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "@/lib/library/keys.mjs"; import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; @@ -521,10 +521,18 @@ export default function LibraryView({ data: opened }: { data: Ok }) { {goneSentence(row.gone, utc)} </span> )} + {row.goneTabs?.map((g) => ( + <span key={g.tab} data-library-gone-tab={g.tab} className="text-doubt-text"> + {goneTabSentence(g, utc)} + </span> + ))} {row.capture && <span data-library-capture={row.capture.state}>{captureSentence(row.capture, utc)}</span>} {row.capture?.mediaOwed && <span>media owed: {row.capture.mediaOwed === "kept" ? "fetched once the post is kept" : "asked for again by the next capture"}</span>} {!row.capture && row.media.count > 0 && <span>{row.media.count} media, not captured</span>} - <span>first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)}</span> + <span> + first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)} + {row.reads[0]?.tab ? ` on the “${row.reads[0].tab}” tab` : ""} + </span> </div> <div className="mt-2 flex flex-wrap items-center gap-1.5" data-library-actions=""> @@ -758,6 +766,36 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: strin )} </div> + {topic && + topic.sources + .filter((src) => src.title || src.summary || src.lastReadTab || src.lastReadTabs) + .map((src) => ( + <div key={src.trendId} data-library-source={src.trendId} className="mt-2 text-[12.5px] text-text-2"> + {src.title && ( + <p className="m-0 break-words" data-library-x-title=""> + X’s title: <span className="text-text">{src.title}</span> + {src.lastUpdatedAt ? <span className="text-muted"> · X updated it {utc(src.lastUpdatedAt)}</span> : null} + </p> + )} + {src.summary && ( + <p className="m-0 break-words" data-library-x-summary=""> + X’s summary: {src.summary} + </p> + )} + {src.lastReadTabs && ( + <p className="m-0 text-muted" data-library-tab=""> + The last read saw the page’s {src.lastReadTabs.map((tab) => `“${tab}”`).join(" and ")} tabs. + </p> + )} + {src.lastReadTab && ( + <p className="m-0 text-muted" data-library-tab=""> + The last read saw the page’s “{src.lastReadTab}” tab + {src.tabs && src.tabs.length > 1 ? ` (the page has ${src.tabs.map((tab) => `“${tab}”`).join(", ")}).` : "."} + </p> + )} + </div> + ))} + {topic && ( <div className="mt-2" data-library-watch-panel={!w ? "none" : w.ended ? "ended" : failing ? "failing" : w.paused ? "paused" : w.on ? "on" : "off"}> <p className="m-0 text-[12.5px] text-text-2" data-library-watch-sentence=""> diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -66,6 +66,7 @@ function row(p, detail) { topic: p.topic, reads: [{ read: "tr-01JA0000000000000000000000", trendId: "1900000000000000001", at: p.firstSeenAt }], ...(p.gone ? { gone: p.gone } : {}), + ...(p.goneTabs ? { goneTabs: p.goneTabs } : {}), ...(p.capture && (captured || p.capture.state !== "captured") ? { capture: { ...p.capture, shot: captured, files: captureFiles(p)?.media.length ?? 0 } } : {}), thread: p.thread, ...(judgement ? { judgement } : {}), @@ -118,7 +119,7 @@ function listing(sp) { } const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null; const pub = detail ? state.published?.[t.id] : undefined; - return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] }; + return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: t.sources ?? [] }; }), posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), total: rows.length, diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs @@ -62,11 +62,18 @@ export function libraryState() { title: "Cup shortage", watch: { on: true, intervalMinutes: 60, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: true, by: "agent", ticks: 5, failures: 3, nextSource: 0, goneSources: [], paused: { reason: "failing", since: READ_3, sentence: "The last read ended rate-limited." } }, }, - { id: "lids", title: "Lids" }, + // A topic whose page X described: its own title and summary, and the tab the last read saw (as the editor's listing gives them). + { + id: "lids", + title: "Lids", + sources: [{ trendId: "1900000000000000009", url: "https://x.com/i/trending/1900000000000000009", title: "Lid makers meet", summary: "Lid makers met to agree on one thread size.", lastUpdatedAt: "2026-11-17T09:30:00.000Z", tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: READ_1 }], + }, ], posts: [ post(P.opening, "teapot_news", "Teapot News", "The kettle festival opens today.", "kettle-festival", READ_1, { mediaCount: 2, kinds: ["image", "video"], capture: { at: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "ok" } }), post(P.reply, "saucer_fan", "Saucer Fan", "A reply about spouts.", "kettle-festival", READ_1, { + // Gone from one tab of the page while the other still shows it (a two-tab read). + goneTabs: [{ tab: "Latest", at: READ_2, read: "tr-01JB0000000000000000000000" }], thread: P.opening, isReply: true, replyTo: { platform: "twitter", id: P.opening, author: "teapot_news" }, diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -137,6 +137,9 @@ test("a post is drawn with its captured media, its thread context, and the words // Gone from the page, in those words; a capture's own state verbatim. await expect(post(page, P.gone).locator("[data-library-gone]")).toHaveText("Gone from the page at 17 Nov 2026, 11:00 UTC"); + // PER TAB: a post one tab stopped showing while the other still shows it says which tab, and is not "gone from the page". + await expect(post(page, P.reply).locator('[data-library-gone-tab="Latest"]')).toHaveText("Gone from the “Latest” tab at 17 Nov 2026, 11:00 UTC; another tab still shows it."); + await expect(post(page, P.reply).locator("[data-library-gone]")).toHaveCount(0); await expect(post(page, P.fresh).locator("[data-library-capture]")).toHaveText("capture: deleted at 17 Nov 2026, 12:05 UTC"); // No post is called deleted: the only place the word may stand is a capture's recorded state. const text = await page.locator("[data-library-posts]").innerText(); @@ -383,6 +386,13 @@ test("the watch: why it is paused, that only the operator restarts a failing one await open(page, { topic: "lids" }); await expect(panel).toHaveAttribute("data-library-watch-panel", "none"); await expect(panel.locator("[data-library-watch-sentence]")).toHaveText("Not watched."); + // X's own title and summary of the page read into the topic, beside the operator's name for it, and the tab the last read saw. + const source = page.locator('[data-library-panel="lids"] [data-library-source]'); + await expect(source.locator("[data-library-x-title]")).toContainText("X’s title: Lid makers meet"); + await expect(source.locator("[data-library-x-summary]")).toHaveText("X’s summary: Lid makers met to agree on one thread size."); + await expect(source.locator("[data-library-tab]")).toHaveText("The last read saw the page’s “Top” tab (the page has “Top”, “Latest”)."); + // A topic with no words from X shows none. + await expect(page.locator('[data-library-panel="lids"] [data-library-source]')).toHaveCount(1); await panel.locator("[data-library-watch-shots]").check(); await panel.locator("[data-library-watch-on]").click(); await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -95,7 +95,7 @@ async function filterOf(flags, lib, reportsRoot) { const line = (p) => { const j = p.judgement ? `${p.judgement.state}${p.judgement.from === "thread" ? " (thread)" : ""} by ${p.judgement.by}` : "unjudged"; - const gone = p.gone ? ` · gone from the page at ${p.gone.at}` : ""; + const gone = (p.gone ? ` · gone from the page at ${p.gone.at}` : "") + (p.goneTabs ?? []).map((g) => ` · gone from the "${g.tab}" tab at ${g.at}`).join(""); const capture = p.capture ? ` · capture: ${p.capture.state} at ${p.capture.at}` : ""; return `${p.id} @${p.author} ${j}${gone}${capture}\n ${String(p.text).replace(/\s+/g, " ").slice(0, 160)}`; }; @@ -132,7 +132,18 @@ export async function libraryCommand(args, deps = {}) { const seen = await seenOf(reportsRoot, need(lib)); const listing = await listLibrary(ask, { slug: lib, detail: true, limit: 1, seen }); const topics = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts })); - say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); + // X's own words for each page read into the topic, and the tab its last read saw. + const pages = (t) => + (t.sources ?? []) + .flatMap((src) => [ + src.title ? ` X's title: ${src.title}` : "", + src.summary ? ` X's summary: ${src.summary.length > 600 ? `${src.summary.slice(0, 599).trimEnd()}…` : src.summary}` : "", + src.lastReadTabs?.length ? ` The last read saw the ${src.lastReadTabs.map((tab) => `"${tab}"`).join(" and ")} tabs.` : src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", + ]) + .filter(Boolean) + .map((line) => `\n${line}`) + .join(""); + say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new${pages(t)}\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); return 0; } if (sub === "posts") { diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs @@ -22,7 +22,7 @@ function harness(answers = {}) { return { ok: true, total: 1, - topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), watch: { on: true, sentence: "Watched every 30 min." }, sources: [] }], + topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), watch: { on: true, sentence: "Watched every 30 min." }, sources: answers.sources ?? [] }], posts: [{ id: "11", author: "teapot_news", text: "The kettle\nfestival opens.", thread: "11", gone: { at: "2026-11-17T11:00:00.000Z" }, capture: { state: "captured", at: "2026-11-17T10:05:00.000Z" } }], }; } @@ -126,6 +126,37 @@ test("watch and purge: the switch with its terms; the editor's refusal is exit 1 }); }); +test("topics says X's own title and summary of each page, and the tab the last read saw", async () => { + await withRoot(async (root) => { + const h = harness({ + sources: [ + { trendId: "1", url: "https://x.com/i/trending/1", title: "Kettle festival opens", summary: "The festival opened this morning.", tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + { trendId: "2", url: "https://x.com/i/trending/2", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, + ], + }); + assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0); + assert.equal( + h.lines[0], + [ + "kettles Kettles 3 posts · 2 unjudged · 3 new", + " X's title: Kettle festival opens", + " X's summary: The festival opened this morning.", + ' The last read saw the "Top" tab of "Top", "Latest".', + " Watched every 30 min.", + ].join("\n"), + ); + }); +}); + +test("topics cuts a long summary of X's at 600 characters", async () => { + await withRoot(async (root) => { + const h = harness({ sources: [{ trendId: "1", url: "https://x.com/i/trending/1", summary: "s".repeat(900), reads: 1, lastReadAt: null }] }); + assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0); + const said = h.lines[0].split("\n").find((l) => l.includes("X's summary: ")).replace(" X's summary: ", ""); + assert.equal(said, `${"s".repeat(599)}…`); + }); +}); + test("seen marks topics in umtool's own state, and --new counts from it", async () => { await withRoot(async (root) => { const h = harness(); diff --git a/umtool/lib/library/filters.mjs b/umtool/lib/library/filters.mjs @@ -83,6 +83,11 @@ export function filterWords(view) { } /** "gone from the page at <time>": the one sentence for a gone mark. Never "deleted". */ +/** "Gone from the “Latest” tab at <time>; another tab still shows it." — one tab's read reached its end without the post (never "deleted"). */ +export function goneTabSentence(g, fmt = (iso) => iso) { + return `Gone from the “${g.tab}” tab at ${fmt(g.at)}; another tab still shows it.`; +} + export function goneSentence(gone, fmt = (iso) => iso) { return gone && typeof gone.at === "string" ? `Gone from the page at ${fmt(gone.at)}` : ""; } diff --git a/umtool/lib/library/view.test.mjs b/umtool/lib/library/view.test.mjs @@ -68,3 +68,8 @@ test("undo puts back each id's OWN entry, or removes the judgement it had none o // S7: an undone entry becomes the operator's, and the bar says so. assert.match(UNDO_SAYS, /written as the operator's whoever wrote them before/); }); + +test("gone from one tab is its own sentence, never \"deleted\"", async () => { + const { goneTabSentence } = await import("./filters.mjs"); + assert.equal(goneTabSentence({ tab: "Latest", at: "2026-11-17T12:00:00.000Z" }, (iso) => iso.slice(11, 16)), "Gone from the “Latest” tab at 12:00; another tab still shows it."); +});