Archilyzer · Source

archilyzer

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

commit e7825351f779938a100a5eb27d5dc52290371be7
parent 92d83bd41eb73b94d0dcd71ff6849174196b8d71
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 20:02:32 -0400

Merge r38/x-search: an X search channel (saved query across accounts, resumable walk, leads ranked by author, Archive / Never archive, never on a site)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 1+
MCOMMANDS.md | 5+++--
MOPERATING.md | 26++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 5++++-
Mcommon/controller/channels.ts | 5+++++
Mcommon/controller/fetchPosts.ts | 31+++++++++++++++++++++++++++++++
Acommon/controller/fetchXSearch.test.ts | 298+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/fetchXSearch.ts | 234+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/xSearchLeads.test.ts | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/xSearchLeads.ts | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 6++++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/posts-server.ts | 26++++++++++++++++++++++++++
Mcommon/lib/site.ts | 26++++++++++++++++++++++++++
Acommon/lib/xSearch/config.test.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xSearch/config.ts | 253+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xSearch/leads.test.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xSearch/leads.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xSearch/walk.test.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xSearch/walk.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/fetchers.ts | 33+++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/channel/[slug]/route.ts | 22+++++++++++++++++++++-
Aeditor/app/api/ops/x-search-lead/route.test.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/x-search-lead/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 24++++++++++++++++++++----
Aeditor/app/channels/[slug]/components/XSearchLeadsPanel.tsx | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 16++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 4++++
Aeditor/app/channels/[slug]/xSearchActions.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/actions.ts | 26++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 40+++++++++++++++++++++++++++++++++-------
Aeditor/app/channels/components/XSearchFields.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 18++++++++++++++++--
Meditor/app/channels/components/parseChannelForm.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Meditor/e2e/fixtures/bin/fake-gallery-dl.mjs | 26++++++++++++++++++++++++++
Aeditor/e2e/x-search.spec.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/protocol.test.ts | 1+
Mmcp/src/server.ts | 5+++++
Amcp/src/xSearchLeads.test.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amcp/src/xSearchLeads.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-38/x-search.md | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 46++++++++++++++++++++++++++++++++++++++++------
Mscripts/archilyzer-ops.test.mjs | 13+++++++++++++
48 files changed, 3349 insertions(+), 44 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -51,6 +51,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | | `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. | +| `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. | #### `downloadFilter` diff --git a/COMMANDS.md b/COMMANDS.md @@ -107,7 +107,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | | `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` | | `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/&lt;id&gt;/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/&lt;id&gt;/) and compose's staging for it (export/.export-index/sites/&lt;id&gt;/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` | -| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` | +| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | | `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` | @@ -162,6 +162,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` | | `check-post-availability` | check-post-availability checks which of a posts channel's archived posts are gone at their source: {"slug", "mode"?: "stale" (default) \| "unchecked" \| "all", "limit"?: 200}, as a check-post-availability job. A Wayback pages channel's records are checked by their ORIGINAL URL at its own site (never the Wayback Machine), one request per distinct URL through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD is refused or the platform has a "gone" page; available (2xx on the same site), deleted (404/410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page), account\_unavailable (suspended, not shared), error otherwise — with the status. A deleted original means the Wayback copy is the only copy. Verdicts go to posts-availability.json. | `pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait` | | `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now, with archive.org's S3 keys): {"url", "slug"?, "dryRun"?}. A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. Refused, before any job: no keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait` | +| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` | | `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | | `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -&gt; {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` | | `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -&gt; {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` | @@ -182,7 +183,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) ```text Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] [--wait-timeout <seconds>] [--quiet] - pnpm ops get channel <slug> [--counts] + pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]] pnpm ops get channels pnpm ops get tags [<tagId>] pnpm ops get publish diff --git a/OPERATING.md b/OPERATING.md @@ -220,6 +220,32 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait - Forum pages saved from a browser: `pnpm archilyzer posts import-html <slug> <file-or-dir> --dry-run`. - Which archived posts were deleted at the source: `pnpm archilyzer posts check --slug <slug>`. +### X search + +```sh +pnpm ops create-channel --json '{"fields":{"name":"Zephyr search","handling":"transcribe","url":"https://x.com/search?q=%22zephyr%20archive%22%20OR%20zephyrs"}}' +pnpm ops create-channel --json '{"fields":{"name":"Zephyr search","handling":"transcribe","platform":"x-search","xSearchQuery":"zephyr -from:spam_bot","xSearchSince":"2024-01-01"}}' +pnpm ops fetch-posts --json '{"slug":"zephyr-search"}' --wait +pnpm ops get channel zephyr-search --leads --limit 20 +pnpm ops x-search-lead --json '{"slug":"zephyr-search","handle":"example","action":"archive","dryRun":true}' +pnpm ops x-search-lead --json '{"slug":"zephyr-search","handle":"example","action":"never"}' +``` + +- An X search page URL (`x.com/search?q=…`, as copied from X), or **X search** in the New channel form's Platform + with a query, makes an X search channel: the posts that match the query, from any account (`config.xSearch`, + CHANNEL.md). The query is X's own — OR, quotes, `-term`, `from:`, `to:`, `@name`, `url:`, `filter:`, `lang:` — + but never `since:`/`until:` (a pasted URL's are lifted into the channel's Since and Until) or `max_id:`. +- A fetch walks the search backwards in windows (3 months, `xSearchWindowMonths`), newest first, from Until (blank: + tomorrow) down to Since (blank: until a year of windows matches nothing) — the older walk's windows, pacing, login + and 3-hour budget. A cut-short run resumes where it stopped; later fetches search only the new days (and the + earlier ones when Since moves back); a new query starts afresh; **Search again from the top** re-walks it all. + Each matching post is the search channel's own copy, deduped by id within the channel, as every posts channel. +- The channel page's **Leads** ranks the accounts by matching posts (first and last day, a sample). + **Archive this account** creates `<handle>-x` on no site and starts its fetch; **Never archive** hides the + account (the channel's `xSearch.exclude`; **Restore** undoes it). The MCP's `x_search_leads` reads the same list. +- An X search channel is never put on a site (refused on create, on Configure, and by every site writer); its posts + follow `social.x.visibility` like any X channel's. + ## Transcribe ```sh diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -15,6 +15,7 @@ // Article's link is known as one before its page is opened. import path from "node:path"; +import { isXSearchChannel } from "../lib/xSearch/config"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; import type { Post, PostAvailability } from "../lib/posts"; @@ -144,7 +145,9 @@ export async function capturePosts( const problem = capturePostsProblem(fetcher); if (problem || !fetcher?.captureByIds) return fail(problem ?? "This channel has no post fetcher."); - const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? ""; + // An X search channel has no account (release 38): its posts are any + // author's, and the X capture opens each by its status id alone. + const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? (isXSearchChannel(config) ? slug : ""); if (!handle) return fail(`Could not determine an account handle for ${slug}`); const stray = strayCaptureIds(ids, await readSeenPostIds(channelRoot)); diff --git a/common/controller/channels.ts b/common/controller/channels.ts @@ -531,6 +531,10 @@ export type PatchChannelConfigOptions = { // Keys to delete before the patch is applied — how a caller says "clear // this override" (a key absent from `patch` is left alone). unset?: ReadonlyArray<keyof ChannelConfig>; + // A patch computed from the config as it is NOW, inside the lock — for a key + // whose new value depends on its old one (an X search channel's + // `xSearch.exclude`, release 38). Applied after `patch`. + derive?: (current: ChannelConfig) => Partial<ChannelConfig>; }; // READ-MODIFY-WRITE ONE CHANNEL'S CONFIG, and the only way to change some keys @@ -553,6 +557,7 @@ export async function patchChannelConfig( const next: ChannelConfig = { ...current }; for (const key of opts.unset ?? []) delete next[key]; Object.assign(next, patch); + if (opts.derive) Object.assign(next, opts.derive(next)); return writeChannelConfig(paths, slug, next); }); } diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -15,6 +15,8 @@ import type { Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; import { isSocialChannel } from "../lib/channelConfig"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import { isXSearchChannel } from "../lib/xSearch/config"; +import { fetchXSearchPosts, X_SEARCH_OLDER_REFUSAL } from "./fetchXSearch"; import { alwaysCookies, resolveCookiePolicy, @@ -241,6 +243,35 @@ export async function fetchPosts( }; } + // 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) { + if (opts.older) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_OLDER_REFUSAL }; + } + if (opts.drain?.aborted) { + log("Drained before the fetch started; nothing was read."); + return { ok: true, written: 0, skipped: 0, complete: false, drained: true }; + } + const policy = resolveCookiePolicy(settings, config); + const xLogin = await resolveXCookieSourceFor(paths, settings, policy.cookies); + return fetchXSearchPosts({ + paths, + slug, + config: { ...config, xSearch: config.xSearch }, + fetcher, + full: opts.full, + limit: opts.limit, + cookies: alwaysCookies(policy), + cookieSource: xLogin.source, + browserCookies: xLogin.browserSpec, + windowPauseMs: opts.olderWindowPauseMs, + onLog, + signal, + drain: opts.drain, + }); + } + const handle = config.socialHandle ?? handleFromAccountUrl(accountUrl) ?? ""; if (!handle) { diff --git a/common/controller/fetchXSearch.test.ts b/common/controller/fetchXSearch.test.ts @@ -0,0 +1,298 @@ +// An X SEARCH channel's fetch (fetchPosts on a channel with `xSearch`), end to +// end against a fake gallery-dl that answers X search URLs from a fixed set of +// posts by several authors: the operator's query passes through with each +// window's since:/until: (and no from:), the walk tiles from until down to +// since, resumes across runs at its max_id: point, starts afresh on a new +// query, searches the new days above what was covered, refuses an older walk +// and a guest run, and keeps its own copy of a post another X channel holds. +// No real X traffic. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchXSearch.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-xsearch-")); +const BIN = path.join(ROOT, "fake-gallery-dl.mjs"); +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.GALLERY_DL_BIN = BIN; +process.env.FAKE_ARGS_LOG = ARGS_LOG; + +const TODAY = new Date().toISOString().slice(0, 10); + +// [date, author, text]. Ids carry the creation time in their high bits, as +// X's do, so they order as dates do. +const POSTS: Array<[string, string, string]> = [ + [`${TODAY} 08:00:00`, "dora", "a zephyr today"], + ["2025-11-10 12:00:00", "alice", "the zephyr archive again"], + ["2025-09-01 09:00:00", "bob", "zephyr breeze"], + ["2025-08-01 09:00:00", "carol", "only a breeze"], + ["2025-03-15 18:30:00", "alice", "zephyr, once more"], + ["2024-12-01 22:15:00", "alice", "an old zephyr"], +]; + +// The walk drops a post the channel already holds as it reads (the stream's +// seen-id check), so a re-read shows in the log's "already archived", not in +// `skipped`. +// +// The fake: a search URL's plain words must all be in a post's text (any one +// of them with an OR; an operator — from:, -term, lang:, a quoted phrase — is +// ignored), since:/until: +// bound its day, max_id: its id; newest first; --post-range honoured. +await writeFile( + BIN, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); +const url = new URL(args[args.length - 1]); +if (!url.pathname.startsWith("/search")) process.exit(0); +const q = url.searchParams.get("q"); +const terms = q.split(" "); +const term = (k) => (terms.find((t) => t.startsWith(k + ":")) || "").slice(k.length + 1) || undefined; +const since = term("since"), until = term("until"), maxId = term("max_id"); +const words = terms.filter((t) => /^[a-z]+$/.test(t) && t !== "OR"); +const range = args[args.indexOf("--post-range") + 1]; +const cap = args.includes("--post-range") ? Number(range.split("-")[1]) : Infinity; +const posts = ${JSON.stringify(POSTS)}; +const idOf = (d) => (BigInt(Date.parse(d.replace(" ", "T") + "Z") - 1288834974657) << 22n); +const hits = posts + .filter(([d, , text]) => d.slice(0, 10) >= since && d.slice(0, 10) < until) + .filter(([d]) => !maxId || idOf(d) <= BigInt(maxId)) + .filter(([, , text]) => words[terms.includes("OR") ? "some" : "every"]((w) => text.includes(w))) + .sort((a, b) => (a[0] < b[0] ? 1 : -1)); +for (const [d, author, text] of hits.slice(0, cap)) { + const user = { name: author, nick: author.toUpperCase() }; + process.stdout.write('{"tweet_id": ' + idOf(d) + ', "date": "' + d + '", "content": ' + JSON.stringify(text) + + ', "author": ' + JSON.stringify(user) + ', "user": ' + JSON.stringify(user) + '}\\n'); +} +`, +); +await chmod(BIN, 0o755); + +const channelsDir = path.join(ROOT, "transcripts", "channels"); + +async function makeSearchChannel(slug: string, xSearch: Record<string, unknown>): Promise<string> { + const channelRoot = path.join(channelsDir, slug); + await mkdir(channelRoot, { recursive: true }); + await writeFile( + path.join(channelRoot, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + postFetcher: "x-gallery-dl", + platform: "twitter", + name: `${slug} (X search)`, + url: "https://x.com/search?q=zephyr&f=live", + xSearch, + }), + ); + return channelRoot; +} + +const { fetchPosts } = await import("./fetchPosts"); +const { X_SEARCH_OLDER_REFUSAL } = await import("./fetchXSearch"); +const { readPostFetchState, readSeenPostIds, readAllPosts, writePosts, writePostFetchState } = await import( + "../lib/posts-server" +); +const { normalizeXTweet } = await import("../social/xNormalize"); +const { getPaths } = await import("../lib/paths"); + +const LOGIN = { cookiesFromBrowser: "firefox" }; + +async function argvLines(): Promise<string[][]> { + try { + return (await readFile(ARGS_LOG, "utf8")) + .trim() + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as string[]); + } catch { + return []; + } +} +const queryOf = (argv: string[]) => new URL(argv[argv.length - 1]).searchParams.get("q") ?? ""; + +const run = (slug: string, extra: Record<string, unknown> = {}) => { + const log: string[] = []; + return fetchPosts({ + paths: getPaths(), + slug, + settings: LOGIN, + olderWindowPauseMs: 0, + onLog: (l) => log.push(l), + ...extra, + }).then((r) => ({ ...r, log })); +}; + +test("the first walk tiles from until down to since with the operator's query, from any author", async () => { + const slug = "zephyr-search"; + const channelRoot = await makeSearchChannel(slug, { + query: "zephyr", + since: "2025-01-01", + until: "2026-01-01", + windowMonths: 6, + }); + const before = (await argvLines()).length; + const res = await run(slug); + assert.equal(res.ok, true, res.log.join("\n")); + assert.equal(res.complete, true); + assert.equal(res.written, 3); + const runs = (await argvLines()).slice(before); + assert.deepEqual(runs.map(queryOf), [ + "zephyr since:2025-07-01 until:2026-01-01", + "zephyr since:2025-01-01 until:2025-07-01", + ]); + // The search argv: newest first, paged by max_id, never a from:. + assert.ok(runs[0].includes("extractor.twitter.search-pagination=max_id")); + assert.ok(runs.every((a) => !queryOf(a).includes("from:"))); + const posts = await readAllPosts(channelRoot); + assert.deepEqual( + posts.map((p) => [p.author, p.createdAt.slice(0, 10)]), + [ + ["alice", "2025-11-10"], + ["bob", "2025-09-01"], + ["alice", "2025-03-15"], + ], + ); + assert.ok(posts.every((p) => p.channelSlug === slug)); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.search?.queryKey, "zephyr"); + assert.equal(state?.search?.walk, undefined); + assert.equal(state?.search?.coveredSince, "2025-01-01"); + assert.equal(state?.search?.coveredUntil, "2026-01-01"); + assert.equal(state?.lastFetchedCount, 3); + // A search channel's fetch is a sync: the scheduler paces it by this stamp. + const config = JSON.parse(await readFile(path.join(channelRoot, "config.json"), "utf8")); + assert.ok(config.lastSyncedAt); + + // Everything is covered and until is fixed: a second fetch searches nothing. + const mid = (await argvLines()).length; + const again = await run(slug); + assert.equal(again.ok, true); + assert.equal(again.written, 0); + assert.equal((await argvLines()).length, mid); + assert.match(again.log.join("\n"), /already searched 2025-01-01 – 2026-01-01/); +}); + +test("a run cut short resumes at its max_id: point; nothing is written twice", async () => { + const slug = "resume-search"; + const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01", until: "2026-01-01", windowMonths: 6 }); + const first = await run(slug, { limit: 1 }); + assert.equal(first.ok, true, first.log.join("\n")); + assert.equal(first.complete, false); + assert.equal(first.written, 1, first.log.join("\n")); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.search?.walk?.since, "2025-07-01"); + assert.ok(state?.search?.walk?.maxId, "a resume point inside the window"); + assert.equal(state?.search?.coveredUntil, undefined); + + const before = (await argvLines()).length; + const second = await run(slug); + assert.equal(second.ok, true, second.log.join("\n")); + assert.equal(second.complete, true); + const queries = (await argvLines()).slice(before).map(queryOf); + assert.match(queries[0], new RegExp(`^zephyr since:2025-07-01 until:2026-01-01 max_id:${state!.search!.walk!.maxId}$`)); + assert.equal(second.written, 2); + // The post at the resume point is read again and dropped as archived. + assert.match(second.log.join("\n"), /2025-07-01 – 2026-01-01: read 2 post\(s\), 1 new, 1 already archived/); + assert.equal((await readSeenPostIds(channelRoot)).size, 3); +}); + +test("operators pass through untouched; a new query starts the walk afresh, posts deduped", async () => { + const slug = "operator-search"; + const channelRoot = await makeSearchChannel(slug, { + query: '"zephyr archive" OR zephyr -from:spam_bot', + lang: "en", + since: "2025-07-01", + until: "2026-01-01", + windowMonths: 6, + }); + const before = (await argvLines()).length; + const res = await run(slug); + assert.equal(res.ok, true, res.log.join("\n")); + assert.deepEqual((await argvLines()).slice(before).map(queryOf), [ + '"zephyr archive" OR zephyr -from:spam_bot lang:en since:2025-07-01 until:2026-01-01', + ]); + assert.equal(res.written, 2, res.log.join("\n")); + + const config = JSON.parse(await readFile(path.join(channelRoot, "config.json"), "utf8")); + config.xSearch.query = "zephyr OR breeze"; + await writeFile(path.join(channelRoot, "config.json"), JSON.stringify(config)); + const again = await run(slug); + assert.equal(again.ok, true, again.log.join("\n")); + assert.match(again.log.join("\n"), /The query changed since the last walk: starting it afresh/); + assert.equal(again.written, 1); + assert.match(again.log.join("\n"), /read 3 post\(s\), 1 new, 2 already archived/); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.search?.queryKey, "zephyr OR breeze lang:en"); +}); + +test("with no until, a later fetch searches the new days down to a day below what was covered", async () => { + const slug = "new-days-search"; + const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-01-01" }); + const day = (offset: number) => new Date(Date.parse(`${TODAY}T00:00:00Z`) + offset * 86_400_000).toISOString().slice(0, 10); + await writePostFetchState(channelRoot, { + search: { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: day(-3) }, + }); + const before = (await argvLines()).length; + const res = await run(slug); + assert.equal(res.ok, true, res.log.join("\n")); + assert.deepEqual((await argvLines()).slice(before).map(queryOf), [`zephyr since:${day(-4)} until:${day(1)}`]); + assert.equal(res.written, 1); + const [post] = await readAllPosts(channelRoot); + assert.equal(post.author, "dora"); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.search?.coveredUntil, day(1)); + assert.equal(state?.search?.coveredSince, "2025-01-01"); + assert.match(state?.search?.completeReason ?? "", /searched down to/); +}); + +test("an older walk and a guest run are refused before anything is searched", async () => { + const slug = "refusals-search"; + await makeSearchChannel(slug, { query: "zephyr", until: "2026-01-01" }); + const before = (await argvLines()).length; + const older = await run(slug, { older: true }); + assert.equal(older.ok, false); + assert.equal(older.error, X_SEARCH_OLDER_REFUSAL); + const guest = await fetchPosts({ paths: getPaths(), slug, settings: {}, olderWindowPauseMs: 0 }); + assert.equal(guest.ok, false); + assert.equal(guest.needsCookies, true); + assert.match(guest.error ?? "", /X search needs a logged-in session/); + assert.equal((await argvLines()).length, before); +}); + +test("a post another X channel holds is kept in the search channel too, once — the archive dedupes per channel", async () => { + // An account channel already holding alice's 2025-11-10 post. + const accountRoot = path.join(channelsDir, "alice-x"); + await mkdir(accountRoot, { recursive: true }); + await writeFile( + path.join(accountRoot, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "alice", url: "https://x.com/alice" }), + ); + const id = String(BigInt(Date.parse("2025-11-10T12:00:00Z") - 1288834974657) << 22n); + const held = normalizeXTweet({ tweet_id: id, date: "2025-11-10 12:00:00", content: "the zephyr archive again", author: { name: "alice" } }, "alice-x"); + assert.ok(held); + await writePosts(accountRoot, [held]); + + const slug = "dedupe-search"; + const channelRoot = await makeSearchChannel(slug, { query: "zephyr", since: "2025-07-01", until: "2026-01-01", windowMonths: 6 }); + const res = await run(slug); + assert.equal(res.written, 2, res.log.join("\n")); + const mine = await readAllPosts(channelRoot); + assert.equal(mine.filter((p) => p.id === id).length, 1); + assert.equal(mine.find((p) => p.id === id)?.channelSlug, slug); + // The account channel is untouched. + assert.deepEqual((await readAllPosts(accountRoot)).map((p) => p.id), [id]); + // Searching again from the top re-reads, and writes nothing twice. + const full = await run(slug, { full: true }); + assert.equal(full.ok, true, full.log.join("\n")); + assert.equal(full.written, 0); + 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/); +}); diff --git a/common/controller/fetchXSearch.ts b/common/controller/fetchXSearch.ts @@ -0,0 +1,234 @@ +// An X SEARCH channel's fetch (release 38 lane S): one walk of search windows +// over the channel's query, newest first, resumable, landing the matching +// posts — from any author — in the channel's own posts archive (the same shard +// writer, deduped by status id within the channel, as every posts channel). +// The walk is the older walk's (fetcher.fetchSearch; xGalleryDlFetcher.ts): +// the same windows, the same 45–120 s between them and 4–10 s between +// requests, the same login, the same 3-hour budget, a 429 waited out by +// gallery-dl as there. lib/xSearch/walk.ts plans which stretch a run walks. +// +// Called by fetchPosts for a channel with `config.xSearch`, after its own +// checks (the channel exists, is social, has a fetcher); the walk's state is +// posts-state.json's `search`, every other field carried as it was. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { Post } from "../lib/posts"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { + readPostFetchState, + readSeenPostIds, + writePostFetchState, + writePosts, + type OlderBackfillPosition, + type XSearchWalkState, +} from "../lib/posts-server"; +import { describeXSearch, type XSearchConfig } from "../lib/xSearch/config"; +import { + coverAfterWalk, + planXSearchWalk, + xSearchStateFor, + type XSearchWalk, +} from "../lib/xSearch/walk"; +import type { SocialFetcher } from "../social/fetchers"; +import type { XCookieSource } from "../social/xCookieSource"; +import { patchChannelConfig } from "./channels"; + +// Refused for a search channel, before any job: it has no timeline and no +// older walk — its fetch IS the window walk. +export const X_SEARCH_OLDER_REFUSAL = + "An X search channel has one walk, its search windows: run a plain fetch. " + + "Its dates are the channel's since and until (Configure)."; + +export function xSearchFetcherProblem( + fetcher: Pick<SocialFetcher, "label" | "fetchSearch"> | undefined, +): string | null { + if (!fetcher) return "This channel has no post fetcher."; + return typeof fetcher.fetchSearch === "function" + ? null + : `${fetcher.label} cannot walk an X search (use x-gallery-dl).`; +} + +export type FetchXSearchOptions = { + paths: Paths; + slug: string; + config: ChannelConfig & { xSearch: XSearchConfig }; + fetcher: SocialFetcher; + // Start the walk afresh: forget what was covered (posts are kept and + // deduped, so this re-reads, never duplicates). + full?: boolean; + limit?: number; + cookies?: string; + cookieSource?: XCookieSource; + browserCookies?: string; + windowPauseMs?: number; + now?: Date; + onLog?: (line: string) => void; + signal?: AbortSignal; + drain?: AbortSignal; +}; + +export type FetchXSearchResult = { + ok: boolean; + written: number; + skipped: number; + complete: boolean; + error?: string; + needsCookies?: boolean; + drained?: boolean; +}; + +export async function fetchXSearchPosts(opts: FetchXSearchOptions): Promise<FetchXSearchResult> { + const { paths, slug, config, fetcher } = opts; + const log = (line: string) => opts.onLog?.(line); + const search = config.xSearch; + const channelRoot = path.join(paths.channelsDir, slug); + const problem = xSearchFetcherProblem(fetcher); + if (problem) return { ok: false, written: 0, skipped: 0, complete: false, error: problem }; + + const priorState = await readPostFetchState(channelRoot); + const stored = opts.full ? undefined : priorState?.search; + let state: XSearchWalkState = xSearchStateFor(search, stored); + if (priorState?.search && state !== priorState.search) { + log( + opts.full + ? "Starting the search walk afresh, as asked (posts already archived are kept)." + : "The query changed since the last walk: starting it afresh (posts already archived are kept).", + ); + } + const plan = planXSearchWalk(search, state, opts.now); + const seenIds = await readSeenPostIds(channelRoot); + const startedAt = new Date().toISOString(); + const stateNow = (extra: Partial<XSearchWalkState> = {}): XSearchWalkState => ({ + ...state, + lastRunAt: startedAt, + ...extra, + }); + // Every field but the search walk's (and the run stamps) is carried as it + // was. + const save = (search: XSearchWalkState, more: { lastFetchedCount?: number; lastError?: string; needsCookies?: boolean } = {}) => + writePostFetchState(channelRoot, { + ...(priorState ?? {}), + lastFetchedAt: startedAt, + ...(more.lastFetchedCount !== undefined ? { lastFetchedCount: more.lastFetchedCount } : {}), + lastError: more.lastError, + needsCookies: more.needsCookies, + search, + }); + + if (plan.kind === "none") { + log(`X search ${describeXSearch(search)}: ${plan.reason}. Nothing to walk.`); + await save(stateNow({ lastWritten: 0 }), { lastFetchedCount: 0 }); + await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() }); + return { ok: true, written: 0, skipped: 0, complete: true }; + } + + const walk: XSearchWalk = plan.walk; + log( + `Fetching X search ${describeXSearch(search)} for ${slug} via ${fetcher.label}: ` + + ({ + resume: "resuming the walk at ", + first: "the first walk, starting at ", + new: "the new days, starting at ", + earlier: "the earlier days, starting at ", + } as const)[plan.kind] + + `${walk.since} – ${walk.until}` + + (walk.floor ? `, down to ${walk.floor}` : ", until a year of windows holds no match") + + `; ${seenIds.size} already archived.`, + ); + + let written = 0; + let skipped = 0; + const shards = new Set<string>(); + const walkAt = (at: OlderBackfillPosition): XSearchWalk => ({ + top: walk.top, + ...(walk.floor !== undefined ? { floor: walk.floor } : {}), + since: at.since, + until: at.until, + emptyWindows: at.emptyWindows, + ...(at.maxId ? { maxId: at.maxId } : {}), + }); + const onCheckpoint = async (cp: { posts: Post[]; position: OlderBackfillPosition }) => { + const w = await writePosts(channelRoot, cp.posts); + written += w.written; + skipped += w.skipped; + for (const shard of w.shards) shards.add(shard); + state = { ...state, walk: walkAt(cp.position) }; + await save(stateNow({ lastWritten: written }), { lastFetchedCount: written }); + if (w.written > 0) log(`Saved ${w.written} matching post(s) (${written} so far this run); resume point recorded.`); + }; + + const controller = new AbortController(); + let result; + try { + result = await fetcher.fetchSearch!({ + channelSlug: slug, + seenIds, + cookies: opts.cookies, + cookieSource: opts.cookieSource, + browserCookies: opts.browserCookies, + limit: opts.limit, + signal: opts.signal ?? controller.signal, + drain: opts.drain, + onLog: log, + position: { since: walk.since, until: walk.until, emptyWindows: walk.emptyWindows, ...(walk.maxId ? { maxId: walk.maxId } : {}) }, + ...(walk.floor !== undefined ? { floor: walk.floor } : {}), + ...(search.windowMonths ? { months: search.windowMonths } : {}), + search: { query: search.query, ...(search.lang ? { lang: search.lang } : {}) }, + windowPauseMs: opts.windowPauseMs, + onCheckpoint, + }); + } catch (err) { + const message = (err as Error).message; + log(`[error] ${message}`); + // Whatever was checkpointed is on disk with its position; keep that one. + state = { ...state, walk: state.walk ?? walk }; + await save(stateNow({ lastWritten: written, lastError: message }), { lastFetchedCount: written, lastError: message }); + return { ok: false, written, skipped, complete: false, error: message }; + } + + const final = await writePosts(channelRoot, result.posts); + written += final.written; + skipped += final.skipped; + for (const shard of final.shards) shards.add(shard); + if (result.complete) { + const covered = coverAfterWalk(state, walk, result.position.since); + const reason = + plan.kind === "new" || (plan.kind === "resume" && state.coveredUntil) + ? `searched down to ${walk.floor ?? result.position.since}` + : (result.completeReason ?? "walked to its end"); + const { walk: _done, ...rest } = state; + void _done; + state = { ...rest, ...covered, completeReason: reason, completedAt: new Date().toISOString() }; + } else { + state = { ...state, walk: walkAt(result.position) }; + } + log( + `Wrote ${written} matching post(s), skipped ${skipped} already archived` + + (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") + + (result.complete + ? ` — searched ${state.coveredSince} – ${state.coveredUntil}.` + : ` — the next fetch resumes at ${state.walk!.since} – ${state.walk!.until}.`), + ); + if (result.error) log(`[error] ${result.error}`); + await save( + stateNow({ lastWritten: written, ...(result.error ? { lastError: result.error } : { lastError: undefined }) }), + { + lastFetchedCount: written, + ...(result.error ? { lastError: result.error } : {}), + ...(result.needsCookies ? { needsCookies: true } : {}), + }, + ); + // The scheduler paces a search channel as any posts channel: by its + // lastSyncedAt. A patch, re-read at write time (fetchPosts' rule). + await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() }); + return { + ok: !result.error, + written, + skipped, + complete: result.complete, + ...(result.needsCookies ? { needsCookies: true } : {}), + ...(result.error ? { error: result.error } : {}), + ...(result.drained ? { drained: true } : {}), + }; +} diff --git a/common/controller/xSearchLeads.test.ts b/common/controller/xSearchLeads.test.ts @@ -0,0 +1,154 @@ +// An X search channel's leads, read and acted on, over a temp corpus: the +// ranking names the accounts an X channel already archives, Never archive and +// Restore go through the config lock and keep every other key, Archive this +// account plans `<handle>-x` and refuses an archived account or a taken slug, +// and no site may carry a search channel (writeSite refuses it). +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xSearchLeads.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "xsearch-leads-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const { getPaths } = await import("../lib/paths"); +const { writePosts } = await import("../lib/posts-server"); +const { readXSearchLeads, setXSearchLeadHidden, planArchiveXLead } = await import("./xSearchLeads"); +const { writeSite, X_SEARCH_NOT_ON_A_SITE } = await import("../lib/site"); +const paths = getPaths(); + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +let n = 0; +const post = (author: string, day: string) => { + n++; + const id = String(1899000000000000000n + BigInt(n)); + return { + id, + slug: `demo-search/${id}`, + channelSlug: "demo-search", + author, + createdAt: `${day}T12:00:00.000Z`, + uploadDate: day.replace(/-/g, ""), + text: `zephyr ${n}`, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter" as const, + isReply: false, + isRepost: false, + links: [], + }; +}; + +const searchRoot = await channel("demo-search", { + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + syncIntervalMinutes: 720, + xSearch: { query: "zephyr", since: "2025-01-01" }, +}); +await writePosts(searchRoot, [ + post("alice", "2025-02-01"), + post("alice", "2025-03-01"), + post("bob", "2025-04-01"), + post("carol", "2025-05-01"), +]); +// bob is archived already, by handle (case aside). +await channel("bob-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "Bob", url: "https://x.com/Bob" }); +// A slug taken by something else entirely. +await channel("carol-x", { url: "https://www.youtube.com/@carol" }); +await channel("plain-video", { url: "https://www.youtube.com/@plain" }); + +test("the leads: ranked, archived accounts named, the walk described", async () => { + const view = await readXSearchLeads(paths, "demo-search"); + assert.ok(view.ok); + assert.equal(view.query, "zephyr"); + assert.equal(view.walk, "not searched yet"); + assert.deepEqual(view.leads.map((l) => [l.key, l.count]), [["alice", 2], ["carol", 1], ["bob", 1]]); + assert.deepEqual(view.leads.find((l) => l.key === "bob")?.archivedAs, ["bob-x"]); + const limited = await readXSearchLeads(paths, "demo-search", { limit: 1 }); + assert.ok(limited.ok); + assert.equal(limited.more, 2); + const notSearch = await readXSearchLeads(paths, "plain-video"); + assert.deepEqual(notSearch, { ok: false, error: "plain-video is not an X search channel (its config has no xSearch query)." }); +}); + +test("Never archive and Restore: one handle in or out of xSearch.exclude, every other key kept", async () => { + const hide = await setXSearchLeadHidden(paths, "demo-search", "@Alice", true); + assert.deepEqual(hide, { ok: true, exclude: ["alice"], changed: true }); + const again = await setXSearchLeadHidden(paths, "demo-search", "alice", true); + assert.deepEqual(again, { ok: true, exclude: ["alice"], changed: false }); + const config = JSON.parse(await readFile(path.join(searchRoot, "config.json"), "utf8")); + assert.deepEqual(config.xSearch, { query: "zephyr", since: "2025-01-01", exclude: ["alice"] }); + assert.equal(config.syncIntervalMinutes, 720); + const view = await readXSearchLeads(paths, "demo-search"); + assert.ok(view.ok); + assert.deepEqual(view.leads.map((l) => l.key), ["carol", "bob"]); + assert.deepEqual(view.hidden, [{ handle: "alice", count: 2 }]); + + const restore = await setXSearchLeadHidden(paths, "demo-search", "alice", false); + assert.deepEqual(restore, { ok: true, exclude: [], changed: true }); + const after = JSON.parse(await readFile(path.join(searchRoot, "config.json"), "utf8")); + assert.deepEqual(after.xSearch, { query: "zephyr", since: "2025-01-01" }); + + assert.deepEqual(await setXSearchLeadHidden(paths, "demo-search", "not a handle", true), { + ok: false, + error: '"not a handle" is not an X handle (letters, digits and "_")', + }); + assert.equal((await setXSearchLeadHidden(paths, "plain-video", "alice", true)).ok, false); +}); + +test("Archive this account: <handle>-x on no site; an archived account or a taken slug refused", async () => { + assert.deepEqual(await planArchiveXLead(paths, "demo-search", "Alice", "Alice A"), { + ok: true, + slug: "alice-x", + fields: { + name: "Alice A (X)", + handling: "transcribe", + url: "https://x.com/Alice", + platform: "twitter", + sourceKind: "social", + postFetcher: "x-gallery-dl", + socialHandle: "Alice", + }, + }); + assert.deepEqual(await planArchiveXLead(paths, "demo-search", "bob"), { + ok: false, + error: "@bob is already archived: bob-x.", + }); + const taken = await planArchiveXLead(paths, "demo-search", "carol"); + assert.equal(taken.ok, false); + assert.match((taken as { error: string }).error, /A channel "carol-x" already exists/); + assert.equal((await planArchiveXLead(paths, "plain-video", "alice")).ok, false); +}); + +test("no site may carry an X search channel, as a member or a cited channel", async () => { + const site = { + siteId: "demo-site", + siteTitle: "Demo", + siteDescription: "", + headerTitle: "Demo", + homeTagline: "", + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [{ slug: "plain-video", groupId: "default" }], + }; + await writeSite(site as never, paths); + await assert.rejects( + writeSite({ ...site, channels: [...site.channels, { slug: "demo-search", groupId: "default" }] } as never, paths), + { message: X_SEARCH_NOT_ON_A_SITE("demo-search") }, + ); + await assert.rejects( + writeSite({ ...site, citedChannels: [{ slug: "demo-search" }] } as never, paths), + { message: "demo-search is an X search channel: it is never put on a site." }, + ); +}); diff --git a/common/controller/xSearchLeads.ts b/common/controller/xSearchLeads.ts @@ -0,0 +1,132 @@ +// AN X SEARCH CHANNEL'S LEADS, read and acted on (release 38 lane S): the +// accounts its matching posts came from (lib/xSearch/leads.ts ranks them), +// and the two things the operator does with one — archive the account as its +// own X channel (on no site; the editor's create-channel path does it, from +// planArchiveXLead's fields) or never archive it (`xSearch.exclude`, which +// hides it from the view). No model, no request: everything is on disk. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { readAllPosts, readPostFetchState } from "../lib/posts-server"; +import { + describeXSearch, + isXSearchChannel, + xLeadHandle, +} from "../lib/xSearch/config"; +import { describeXSearchWalk } from "../lib/xSearch/walk"; +import { + rankXSearchLeads, + xLeadChannelFields, + xLeadChannelSlug, + type XSearchLeads, +} from "../lib/xSearch/leads"; +import { handleFromAccountUrl } from "../social/fetchers"; +import { channelExists, listChannelConfigs, patchChannelConfig, readChannelConfig } from "./channels"; + +export const NOT_AN_X_SEARCH_CHANNEL = (slug: string) => + `${slug} is not an X search channel (its config has no xSearch query).`; + +// X channels that archive ONE account (not a search), by lower-case handle. +export async function archivedXAccounts(paths: Paths): Promise<Map<string, string[]>> { + const out = new Map<string, string[]>(); + for (const { slug, config } of await listChannelConfigs(paths)) { + if (config.sourceKind !== "social" || config.platform !== "twitter" || isXSearchChannel(config)) continue; + const handle = xLeadHandle(config.socialHandle ?? handleFromAccountUrl(config.url ?? "") ?? ""); + if (!handle) continue; + out.set(handle, [...(out.get(handle) ?? []), slug]); + } + return out; +} + +export type XSearchLeadsView = XSearchLeads & { + ok: true; + slug: string; + query: string; + search: string; // describeXSearch + walk: string; // describeXSearchWalk +}; + +export async function readXSearchLeads( + paths: Paths, + slug: string, + opts: { limit?: number } = {}, +): Promise<XSearchLeadsView | { ok: false; error: string }> { + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXSearchChannel(config) || !config.xSearch) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) }; + const channelRoot = path.join(paths.channelsDir, slug); + const [posts, state, archived] = await Promise.all([ + readAllPosts(channelRoot), + readPostFetchState(channelRoot), + archivedXAccounts(paths), + ]); + return { + ok: true, + slug, + query: config.xSearch.query, + search: describeXSearch(config.xSearch), + walk: describeXSearchWalk(state?.search), + ...rankXSearchLeads(posts, { + exclude: config.xSearch.exclude, + archived, + ...(opts.limit !== undefined ? { limit: opts.limit } : {}), + }), + }; +} + +// "Never archive" (hidden = true) and its undo: the handle into, or out of, +// the channel's `xSearch.exclude`, re-read and written under the config lock. +export async function setXSearchLeadHidden( + paths: Paths, + slug: string, + handle: string, + hidden: boolean, +): Promise<{ ok: true; exclude: string[]; changed: boolean } | { ok: false; error: string }> { + const key = xLeadHandle(handle); + if (!key) return { ok: false, error: `"${handle}" is not an X handle (letters, digits and "_")` }; + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXSearchChannel(config)) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) }; + let changed = false; + let exclude: string[] = []; + const written = await patchChannelConfig(paths, slug, {}, { + derive: (current: ChannelConfig) => { + if (!current.xSearch) return {}; + const was = current.xSearch.exclude ?? []; + exclude = hidden ? (was.includes(key) ? was : [...was, key]) : was.filter((h) => h !== key); + changed = exclude.length !== was.length; + const { exclude: _old, ...rest } = current.xSearch; + void _old; + return { xSearch: exclude.length > 0 ? { ...rest, exclude } : rest }; + }, + }); + if (!written) return { ok: false, error: `No such channel: ${slug}` }; + return { ok: true, exclude, changed }; +} + +export const LEAD_ALREADY_ARCHIVED = (handle: string, slugs: string[]) => + `@${handle} is already archived: ${slugs.join(", ")}.`; + +// What "Archive this account" creates: `<handle>-x`, an X account channel on +// NO site, with the New channel form's fields. Refused when the account is +// already archived by an X channel, or the slug is taken. +export async function planArchiveXLead( + paths: Paths, + slug: string, + handle: string, + name?: string, +): Promise<{ ok: true; slug: string; fields: Record<string, string> } | { ok: false; error: string }> { + const key = xLeadHandle(handle); + if (!key) return { ok: false, error: `"${handle}" is not an X handle (letters, digits and "_")` }; + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXSearchChannel(config)) return { ok: false, error: NOT_AN_X_SEARCH_CHANNEL(slug) }; + const archived = (await archivedXAccounts(paths)).get(key); + if (archived && archived.length > 0) return { ok: false, error: LEAD_ALREADY_ARCHIVED(handle.replace(/^@/, ""), archived) }; + const newSlug = xLeadChannelSlug(key); + if (await channelExists(paths, newSlug)) { + return { ok: false, error: `A channel "${newSlug}" already exists; create @${key}'s channel by hand with another slug.` }; + } + return { ok: true, slug: newSlug, fields: xLeadChannelFields({ handle: handle.replace(/^@/, ""), ...(name ? { name } : {}) }) }; +} diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -1,5 +1,6 @@ import { PLATFORM_VALUES, type Platform } from "./platform"; import { coerceWaybackPagesConfig, type WaybackPagesConfig } from "./waybackPages/config"; +import { coerceXSearchConfig, type XSearchConfig } from "./xSearch/config"; import { isDownloadFormatPreset, isSourceVideoQuality, @@ -160,6 +161,8 @@ export type ChannelConfig = { mirror?: MirrorConfig; // Release 37: a Wayback pages channel's scope (lib/waybackPages/config.ts). wayback?: WaybackPagesConfig; + // Release 38: an X search channel's query (lib/xSearch/config.ts). + xSearch?: XSearchConfig; }; // In the order parseChannelConfig emits (and CHANNEL.md lists) them. @@ -228,6 +231,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "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.", wayback: '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.', + 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.', }; // Every key a config.json may carry, in emission order. The unknown-key oracle: @@ -436,6 +441,7 @@ export const CHANNEL_CONFIG_COERCIONS: { recordedDate: coerceRecordedDateRule, mirror: coerceMirrorConfig, wayback: coerceWaybackPagesConfig, + xSearch: coerceXSearchConfig, }; // A channel's config.json as a ChannelConfig, or null when it is not a channel diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 37); // release 37: `wayback` + assert.equal(CHANNEL_CONFIG_KEYS.length, 38); // release 38: `xSearch` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -80,6 +80,7 @@ export const channelConfigObjectSchema = z.object({ recordedDate: field("recordedDate"), mirror: field("mirror"), wayback: field("wayback"), + xSearch: field("xSearch"), }); // Drop every own key whose value is `undefined` (the OMIT rule, above). diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -508,6 +508,32 @@ export type PostFetchState = { // place of `cursor`, which a forum fetch no longer writes (an old one is // read once, as the history position, and dropped). forum?: ForumWalkState; + // An X SEARCH channel's walk (release 38, controller/fetchXSearch.ts): its + // only walk — it has no timeline and no older walk. + search?: XSearchWalkState; +}; + +// Where an X search channel's walk stands. A walk goes BACKWARDS in search +// windows from a `top` day to a `floor`; what finished walks have searched +// end to end is [coveredSince, coveredUntil). A later fetch walks only what +// is outside it: the new days above, and below when `since` is moved earlier. +export type XSearchWalkState = { + // The query (and language) this state belongs to (xSearchQueryKey): a + // change of query starts the walk afresh. + queryKey: string; + // The walk in progress, when one is: its bounds and its position. + walk?: OlderBackfillPosition & { + top: string; // YYYY-MM-DD, exclusive — the first window's `until` + floor?: string; // YYYY-MM-DD — the walk stops there; absent = after empty windows + }; + coveredSince?: string; + coveredUntil?: string; + // Why the last walk to finish ended, as a sentence. + completeReason?: string; + completedAt?: string; + lastRunAt?: string; + lastWritten?: number; + lastError?: string; }; // Where the older-posts backfill stands. The window is in UTC days, as X's diff --git a/common/lib/site.ts b/common/lib/site.ts @@ -11,6 +11,8 @@ import { type SocialLink, } from "./settings"; import { socialLinksForSave } from "./socialLinks"; +import { parseChannelConfig } from "./channelConfig"; +import { isXSearchChannel } from "./xSearch/config"; import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; import { isListedSite, @@ -226,6 +228,26 @@ function storedSocialLinks(file: string): SocialLink[] { } } +export const X_SEARCH_NOT_ON_A_SITE = (slug: string) => + `${slug} is an X search channel: it is never put on a site.`; + +// The first member of `site` (or of its cited scope) that is an X search +// channel, by its config.json — or null. One small read per member. +export function xSearchChannelOnSite( + site: Pick<Site, "channels" | "citedChannels">, + paths: Paths, +): string | null { + // A Paths with no channel pool (a test's scratch paths) has nothing to read. + if (!paths.channelsDir) return null; + const slugs = [...site.channels.map((c) => c.slug), ...(site.citedChannels ?? []).map((c) => c.slug)]; + for (const slug of slugs) { + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) continue; + const raw = readJsonFileSync(path.join(paths.channelsDir, slug, "config.json")); + if (raw.ok && isXSearchChannel(parseChannelConfig(raw.value))) return slug; + } + return null; +} + export async function writeSite( site: Site, paths: Paths = getPaths(), @@ -252,6 +274,10 @@ export async function writeSite( // A search-off site publishes only its pages: one with none is refused (D5). const searchProblem = siteSearchProblem(site); if (searchProblem) throw new Error(searchProblem); + // An X search channel is never put on a site (release 38): refused here, at + // the one writer every site edit goes through. + const searchChannel = xSearchChannelOnSite(site, paths); + if (searchChannel) throw new Error(X_SEARCH_NOT_ON_A_SITE(searchChannel)); // undefined socialLinks = inherit the global default; only validate/persist a // key when the site explicitly overrides (an array, even empty). // A link whose SVG is unchanged from the file on disk is kept as it is; a new diff --git a/common/lib/xSearch/config.test.ts b/common/lib/xSearch/config.test.ts @@ -0,0 +1,145 @@ +// An X search channel's config: the query passes X's operators through, the +// walk's own operators are refused, a URL copied from X becomes a config with +// its dates lifted out, and the window query is the operator's terms plus the +// window. Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/config.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + coerceXSearchConfig, + describeXSearch, + isXSearchChannel, + isXSearchUrl, + xLeadHandle, + xQueryHasLang, + xQueryTerms, + xSearchFromUrl, + xSearchQueryKey, + xSearchQueryOfUrl, + xSearchQueryProblem, + xSearchUrl, + xSearchWindowQuery, +} from "./config"; +import { parseChannelConfig } from "../channelConfig"; + +test("X's operators pass through untouched", () => { + for (const q of [ + "zephyr", + '"exact phrase" OR other', + "zephyr -noise -from:spam_bot", + "from:alice OR from:bob", + "to:alice @bob url:example.com", + "zephyr filter:links lang:en", + "(zephyr OR archive) min_faves:10", + "#tag $cash", + ]) { + assert.equal(xSearchQueryProblem(q), null, q); + } +}); + +test("an empty query, a two-line one, an open quote and the walk's own operators are refused", () => { + assert.match(xSearchQueryProblem("")!, /needs a query/); + assert.match(xSearchQueryProblem(" ")!, /needs a query/); + assert.match(xSearchQueryProblem(undefined)!, /needs a query/); + assert.match(xSearchQueryProblem("a\nb")!, /one line/); + assert.match(xSearchQueryProblem('"open phrase')!, /quote open/); + assert.match(xSearchQueryProblem("x".repeat(501))!, /at most 500/); + const dated = xSearchQueryProblem("zephyr since:2020-01-01 until:2021-01-01")!; + assert.match(dated, /Take since:, until: out of the query/); + assert.match(dated, /since and until dates set the search windows/); + assert.match(xSearchQueryProblem("zephyr max_id:123")!, /max_id:/); + assert.match(xSearchQueryProblem("zephyr SINCE:2020-01-01")!, /since:/); + assert.match(xSearchQueryProblem("zephyr -until:2020-01-01")!, /until:/); + // Inside a phrase it is text, not an operator. + assert.equal(xSearchQueryProblem('"since:2020 was a year"'), null); +}); + +test("terms split outside quotes", () => { + assert.deepEqual(xQueryTerms('a "b c" d'), ["a", '"b c"', "d"]); + assert.equal(xQueryTerms('a "b'), null); + assert.equal(xQueryHasLang("zephyr lang:de"), true); + assert.equal(xQueryHasLang("zephyr -lang:de"), false); + assert.equal(xQueryHasLang('"lang:de"'), false); +}); + +test("a search URL from X: its query, + as a space, dates lifted out", () => { + const url = "https://x.com/search?q=%22zephyr%20archive%22+OR+zephyrs%20since%3A2021-01-01%20until%3A2022-06-30&src=typed_query&f=live"; + assert.equal(isXSearchUrl(url), true); + assert.equal(xSearchQueryOfUrl(url), '"zephyr archive" OR zephyrs since:2021-01-01 until:2022-06-30'); + assert.deepEqual(xSearchFromUrl(url), { + query: '"zephyr archive" OR zephyrs', + since: "2021-01-01", + until: "2022-06-30", + }); + assert.equal(isXSearchUrl("https://twitter.com/search?q=zephyr"), true); + assert.equal(isXSearchUrl("https://mobile.twitter.com/search/?q=zephyr"), true); + assert.equal(isXSearchUrl("https://x.com/search?q="), false); + assert.equal(isXSearchUrl("https://x.com/zephyr"), false); + assert.equal(isXSearchUrl("https://example.com/search?q=zephyr"), false); + assert.equal(xSearchFromUrl("https://x.com/zephyr"), null); + // A date that is not a day stays in the query (and is refused there). + assert.deepEqual(xSearchFromUrl("https://x.com/search?q=a%20since%3A2021-02-30"), { query: "a since:2021-02-30" }); +}); + +test("the stored URL is the search page of the query, encoded whole", () => { + assert.equal(xSearchUrl('"a b" c+d'), "https://x.com/search?q=%22a%20b%22%20c%2Bd&f=live"); + assert.equal(xSearchQueryOfUrl(xSearchUrl('"a b" c+d')), '"a b" c+d'); +}); + +test("the coercion keeps what is valid and drops the rest, one member at a time", () => { + assert.equal(coerceXSearchConfig({ query: "" }), undefined); + assert.equal(coerceXSearchConfig({ query: "a since:2020-01-01" }), undefined); + assert.equal(coerceXSearchConfig("zephyr"), undefined); + assert.deepEqual( + coerceXSearchConfig({ + query: " zephyr ", + since: "2020-01-01", + until: "2019-12-31", + windowMonths: 13, + lang: "EN", + exclude: ["@Alice", "alice", "bad handle", 3], + extra: true, + }), + { query: "zephyr", since: "2020-01-01", lang: "en", exclude: ["alice"] }, + ); + assert.deepEqual(coerceXSearchConfig({ query: "z", until: "2021-01-01", windowMonths: 1 }), { + query: "z", + until: "2021-01-01", + windowMonths: 1, + }); +}); + +test("a channel config carries xSearch through the one set of coercions", () => { + const config = parseChannelConfig({ + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + url: xSearchUrl("zephyr"), + xSearch: { query: "zephyr", since: "2024-01-01" }, + }); + assert.deepEqual(config?.xSearch, { query: "zephyr", since: "2024-01-01" }); + assert.equal(isXSearchChannel(config), true); + assert.equal(isXSearchChannel({ sourceKind: "social", platform: "twitter" }), false); + assert.equal(isXSearchChannel({ sourceKind: "social", platform: "bluesky", xSearch: { query: "a" } }), false); +}); + +test("one window's query: the operator's terms, the language, the window and the resume point", () => { + assert.equal( + xSearchWindowQuery({ query: '"zephyr archive" OR -noise from:alice', lang: "en" }, { since: "2024-01-01", until: "2024-04-01" }), + '"zephyr archive" OR -noise from:alice lang:en since:2024-01-01 until:2024-04-01', + ); + assert.equal( + xSearchWindowQuery({ query: "zephyr lang:de", lang: "en" }, { since: "2024-01-01", until: "2024-04-01", maxId: "1899" }), + "zephyr lang:de since:2024-01-01 until:2024-04-01 max_id:1899", + ); + assert.throws(() => xSearchWindowQuery({ query: "a until:2020-01-01" }, { since: "2024-01-01", until: "2024-04-01" }), /until:/); + assert.throws(() => xSearchWindowQuery({ query: "a" }, { since: "2024-01-01", until: "2024-04-01", maxId: "x1" }), /not a post id/); +}); + +test("the query key ignores the dates; leads' handles are lower case", () => { + assert.equal(xSearchQueryKey({ query: " zephyr ", lang: "en" }), "zephyr lang:en"); + assert.equal(xSearchQueryKey({ query: "zephyr" }), "zephyr"); + assert.equal(xLeadHandle("@Alice_1"), "alice_1"); + assert.equal(xLeadHandle("not a handle"), null); + assert.match(describeXSearch({ query: "zephyr", since: "2024-01-01" }), /zephyr · since 2024-01-01/); +}); diff --git a/common/lib/xSearch/config.ts b/common/lib/xSearch/config.ts @@ -0,0 +1,253 @@ +// AN X SEARCH CHANNEL (release 38 lane S, plans/release-38/x-search.md): a saved +// X search across accounts — a posts channel on platform "twitter", +// `sourceKind: "social"`, whose records are the posts that match ONE query, +// from any author. `config.xSearch` holds the query and the dates it is walked +// between; the walk itself (search windows, newest first, resumable) is the +// older-posts backfill's, with the operator's query in place of `from:<handle>`. +// +// Client-safe and a LEAF (no imports): lib/channelConfig.ts composes the +// coercion below into its one set of coercions, and the channel form imports +// the URL and query helpers. + +export type XSearchConfig = { + // The query, as X's search box takes it: words, "quoted phrases", OR, + // -term, from:/to:/@mention, url:, filter:, lang:, … — passed through as + // typed. Never since:/until: (the windows add those) or max_id: and its + // kin (the walk pages with max_id). + query: string; + // The earliest day searched (YYYY-MM-DD, inclusive): the walk stops there. + // Absent: it stops after a year of windows in a row with no match. + since?: string; + // The day the walk starts below (YYYY-MM-DD, exclusive, as X's until:). + // Absent: tomorrow — and each later fetch searches what is new since. + until?: string; + // Each search window's span in months (1–12). Absent: 3, the older walk's. + windowMonths?: number; + // A language code (en, de, pt-br …): `lang:<code>` is added to the query + // unless it names a lang: of its own. + lang?: string; + // Authors hidden from the leads view ("Never archive"), bare handles in + // lower case. The search itself is not narrowed by them. + exclude?: string[]; +}; + +export const X_SEARCH_QUERY_MAX = 500; +export const X_SEARCH_WINDOW_MONTHS_MAX = 12; + +// The operators the walk writes itself, refused in a query. since:/until: +// bound the windows; max_id: is the walk's resume point (gallery-dl rewrites +// it after every page); the others would fight both. +const RESERVED_OPERATORS = ["since", "until", "max_id", "since_id", "until_id", "since_time", "until_time"]; + +const DAY_RE = /^\d{4}-\d{2}-\d{2}$/; +const HANDLE_RE = /^[A-Za-z0-9_]{1,50}$/; +const LANG_RE = /^[a-z]{2,3}(?:-[a-z]{2,4})?$/; + +function isDay(v: unknown): v is string { + if (typeof v !== "string" || !DAY_RE.test(v)) return false; + const ms = Date.parse(`${v}T00:00:00Z`); + return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === v; +} + +// The query's terms, split on whitespace OUTSIDE double quotes: a quoted +// phrase is one term, quotes kept. Null when a quote is left open. +export function xQueryTerms(query: string): string[] | null { + const terms: string[] = []; + let cur = ""; + let quoted = false; + for (const ch of query) { + if (ch === '"') { + quoted = !quoted; + cur += ch; + continue; + } + if (!quoted && /\s/.test(ch)) { + if (cur) terms.push(cur); + cur = ""; + continue; + } + cur += ch; + } + if (quoted) return null; + if (cur) terms.push(cur); + return terms; +} + +// The operator name a term uses (`-from:x` → "from"), or null for a plain word +// or a phrase. +function operatorOf(term: string): string | null { + const m = /^[-(]*([A-Za-z_]+):/.exec(term); + return m ? m[1].toLowerCase() : null; +} + +// Why this query cannot be an X search channel's, as a sentence — or null. +export function xSearchQueryProblem(query: unknown): string | null { + if (typeof query !== "string" || !query.trim()) { + return "An X search channel needs a query (what you would type in X's search box)."; + } + const q = query.trim(); + if (q.length > X_SEARCH_QUERY_MAX) { + return `An X search query is at most ${X_SEARCH_QUERY_MAX} characters (this one is ${q.length}).`; + } + if (/[\r\n]/.test(q)) return "An X search query is one line."; + const terms = xQueryTerms(q); + if (!terms) return "The X search query leaves a quote open."; + const reserved = [ + ...new Set( + terms + .map(operatorOf) + .filter((op): op is string => op !== null && RESERVED_OPERATORS.includes(op)), + ), + ]; + if (reserved.length > 0) { + return ( + `Take ${reserved.map((op) => `${op}:`).join(", ")} out of the query: ` + + "the channel's since and until dates set the search windows, and the walk adds them itself." + ); + } + return null; +} + +// True when the query names a lang: of its own. +export function xQueryHasLang(query: string): boolean { + return (xQueryTerms(query) ?? []).some((t) => operatorOf(t) === "lang" && !t.startsWith("-")); +} + +// A bare X handle in lower case, or null. +export function xLeadHandle(input: unknown): string | null { + if (typeof input !== "string") return null; + const bare = input.trim().replace(/^@/, ""); + return HANDLE_RE.test(bare) ? bare.toLowerCase() : null; +} + +// `config.xSearch`: an object with a valid query, else omitted. The optional +// members are omitted one by one when invalid, never repaired; an `until` at +// or before `since` drops `until`. +export function coerceXSearchConfig(v: unknown): XSearchConfig | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + if (xSearchQueryProblem(r.query) !== null) return undefined; + const out: XSearchConfig = { query: (r.query as string).trim() }; + if (isDay(r.since)) out.since = r.since; + if (isDay(r.until) && !(out.since && r.until <= out.since)) out.until = r.until; + if ( + typeof r.windowMonths === "number" && + Number.isInteger(r.windowMonths) && + r.windowMonths >= 1 && + r.windowMonths <= X_SEARCH_WINDOW_MONTHS_MAX + ) { + out.windowMonths = r.windowMonths; + } + if (typeof r.lang === "string" && LANG_RE.test(r.lang.trim().toLowerCase())) { + out.lang = r.lang.trim().toLowerCase(); + } + if (Array.isArray(r.exclude)) { + const handles = [...new Set(r.exclude.map(xLeadHandle).filter((h): h is string => h !== null))]; + if (handles.length > 0) out.exclude = handles; + } + return out; +} + +// An X search channel: a posts channel on platform "twitter" with a query. +// Structural, so this leaf needs no import of the channel config's type. +export function isXSearchChannel( + config: { sourceKind?: string; platform?: string; xSearch?: unknown } | null | undefined, +): boolean { + return config?.sourceKind === "social" && config.platform === "twitter" && Boolean(config.xSearch); +} + +const X_HOST_RE = /^(?:www\.|mobile\.)?(?:x|twitter)\.com$/i; + +// X's search page for a query — the URL a search channel stores, and the one +// gallery-dl's search extractor matches. The query is percent-encoded whole +// (gallery-dl turns "+" into a space BEFORE it unquotes, so an encoded "+" +// survives); `f=live` is X's "Latest" tab. +export function xSearchUrl(query: string): string { + return `https://x.com/search?q=${encodeURIComponent(query)}&f=live`; +} + +// The query of an X search page URL (x.com or twitter.com /search?q=…), or +// null. `+` reads as a space, as X writes it. +export function xSearchQueryOfUrl(input: string | undefined | null): string | null { + if (!input) return null; + let u: URL; + try { + u = new URL(input.trim()); + } catch { + return null; + } + if (!X_HOST_RE.test(u.hostname)) return null; + if (u.pathname.replace(/\/+$/, "") !== "/search") return null; + const q = u.searchParams.get("q"); + return q && q.trim() ? q.trim() : null; +} + +export function isXSearchUrl(input: string | undefined | null): boolean { + return xSearchQueryOfUrl(input) !== null; +} + +// A search channel's config from a URL copied out of X: its query, with any +// one since:/until: day lifted out into the channel's dates (X writes them in +// the query; the channel keeps them apart). Anything else stays in the query, +// to be refused or kept by xSearchQueryProblem. +export function xSearchFromUrl(input: string | undefined | null): XSearchConfig | null { + const raw = xSearchQueryOfUrl(input); + if (raw === null) return null; + const terms = xQueryTerms(raw); + if (!terms) return { query: raw }; + const out: XSearchConfig = { query: "" }; + const kept: string[] = []; + for (const term of terms) { + const m = /^(since|until):(\d{4}-\d{2}-\d{2})$/i.exec(term); + const key = m?.[1].toLowerCase() as "since" | "until" | undefined; + if (m && key && isDay(m[2]) && out[key] === undefined) { + out[key] = m[2]; + continue; + } + kept.push(term); + } + out.query = kept.join(" "); + return out; +} + +// What the walk's saved state belongs to: a change of query or language starts +// the walk afresh. The dates are not in it — widening them walks only what is +// newly in range. +export function xSearchQueryKey(config: Pick<XSearchConfig, "query" | "lang">): string { + return `${config.query.trim()}${config.lang ? ` lang:${config.lang}` : ""}`; +} + +// The query for ONE window: the operator's terms, the language, the window's +// days and, inside a window, the resume point. Throws on a query the channel +// could not hold (the fetcher never runs one). +export function xSearchWindowQuery( + config: Pick<XSearchConfig, "query" | "lang">, + position: { since: string; until: string; maxId?: string }, +): string { + const problem = xSearchQueryProblem(config.query); + if (problem) throw new Error(problem); + if (!isDay(position.since) || !isDay(position.until)) { + throw new Error(`"${position.since} – ${position.until}" is not a window of days`); + } + const terms = [config.query.trim()]; + if (config.lang && !xQueryHasLang(config.query)) terms.push(`lang:${config.lang}`); + terms.push(`since:${position.since}`, `until:${position.until}`); + if (position.maxId) { + if (!/^\d+$/.test(position.maxId)) throw new Error(`"${position.maxId}" is not a post id`); + terms.push(`max_id:${position.maxId}`); + } + return terms.join(" "); +} + +// One line for the channel page and the ops read. +export function describeXSearch(config: XSearchConfig): string { + const range = + config.since && config.until + ? `${config.since} – ${config.until}` + : config.since + ? `since ${config.since}` + : config.until + ? `before ${config.until}` + : "all dates"; + return `${config.query}${config.lang ? ` (lang ${config.lang})` : ""} · ${range}`; +} diff --git a/common/lib/xSearch/leads.test.ts b/common/lib/xSearch/leads.test.ts @@ -0,0 +1,106 @@ +// An X search channel's leads: authors ranked by matching posts, a sample the +// account wrote itself, hidden handles kept apart, accounts already archived +// named, and the channel an "Archive this account" makes. +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/leads.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { Post } from "../posts"; +import { rankXSearchLeads, xLeadChannelFields, xLeadChannelSlug } from "./leads"; + +let n = 0; +function post(author: string, createdAt: string, extra: Partial<Post> = {}): Post { + n++; + const id = String(1899000000000000000n + BigInt(n)); + return { + id, + slug: `demo-search/${id}`, + channelSlug: "demo-search", + author, + createdAt, + uploadDate: createdAt.slice(0, 10).replace(/-/g, ""), + text: `post ${n} by ${author} about zephyr`, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + ...extra, + }; +} + +test("most matches first, then the most recent, then the handle", () => { + const posts = [ + post("alice", "2026-01-01T00:00:00.000Z", { authorName: "Alice A" }), + post("Alice", "2026-03-01T00:00:00.000Z", { authorName: "Alice B" }), + post("alice", "2026-02-01T00:00:00.000Z", { isRepost: true }), + post("bob", "2026-04-01T00:00:00.000Z"), + post("carol", "2026-05-01T00:00:00.000Z"), + post("dave", "2026-05-01T00:00:00.000Z"), + ]; + // The same post read twice (two shards) counts once. + const out = rankXSearchLeads([...posts, posts[0]]); + assert.deepEqual( + out.leads.map((l) => [l.key, l.count]), + [["alice", 3], ["carol", 1], ["dave", 1], ["bob", 1]], + ); + const alice = out.leads[0]; + assert.equal(alice.handle, "Alice"); + assert.equal(alice.name, "Alice B"); + assert.equal(alice.reposts, 1); + assert.equal(alice.first, "2026-01-01T00:00:00.000Z"); + assert.equal(alice.last, "2026-03-01T00:00:00.000Z"); + assert.equal(alice.sample.id, posts[1].id); + assert.equal(out.posts, 6); + assert.equal(out.authors, 4); + assert.equal(out.more, 0); +}); + +test("the sample is the account's own newest post, else its newest repost; long text is cut", () => { + const own = post("erin", "2026-01-01T00:00:00.000Z", { text: "x".repeat(400) }); + const repost = post("erin", "2026-06-01T00:00:00.000Z", { isRepost: true }); + const [erin] = rankXSearchLeads([own, repost]).leads; + assert.equal(erin.sample.id, own.id); + assert.equal(erin.sample.text.length, 280); + assert.ok(erin.sample.text.endsWith("…")); + const [only] = rankXSearchLeads([post("fay", "2026-01-01T00:00:00.000Z", { isRepost: true })]).leads; + assert.equal(only.sample.createdAt, "2026-01-01T00:00:00.000Z"); +}); + +test("hidden handles are kept apart, archived accounts named, the list capped", () => { + const posts = [ + post("alice", "2026-01-01T00:00:00.000Z"), + post("alice", "2026-01-02T00:00:00.000Z"), + post("bob", "2026-01-03T00:00:00.000Z"), + post("carol", "2026-01-04T00:00:00.000Z"), + ]; + const out = rankXSearchLeads(posts, { + exclude: ["ALICE", "ghost"], + archived: new Map([["bob", ["bob-x", "bob-x-replies"]]]), + limit: 1, + }); + assert.deepEqual(out.leads.map((l) => l.key), ["carol"]); + assert.equal(out.more, 1); + assert.deepEqual(out.hidden, [ + { handle: "alice", count: 2 }, + { handle: "ghost", count: 0 }, + ]); + const all = rankXSearchLeads(posts, { archived: new Map([["bob", ["bob-x-replies", "bob-x"]]]) }); + assert.deepEqual(all.leads.find((l) => l.key === "bob")?.archivedAs, ["bob-x", "bob-x-replies"]); +}); + +test("Archive this account makes <handle>-x with the form's fields", () => { + assert.equal(xLeadChannelSlug("@Some_Account"), "some_account-x"); + assert.equal(xLeadChannelSlug("_under"), "x_under-x"); + assert.throws(() => xLeadChannelSlug("not one"), /not an X handle/); + assert.deepEqual(xLeadChannelFields({ handle: "Some_Account", name: "Some Account" }), { + name: "Some Account (X)", + handling: "transcribe", + url: "https://x.com/Some_Account", + platform: "twitter", + sourceKind: "social", + postFetcher: "x-gallery-dl", + socialHandle: "Some_Account", + }); + assert.equal(xLeadChannelFields({ handle: "@bob" }).name, "bob (X)"); +}); diff --git a/common/lib/xSearch/leads.ts b/common/lib/xSearch/leads.ts @@ -0,0 +1,153 @@ +// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): the accounts its matching +// posts came from, ranked by how many — the "who keeps saying this" view the +// operator acts on (Archive this account / Never archive). Pure: posts in, +// rows out; no model. controller/xSearchLeads.ts reads the posts and the +// channels it needs. + +import type { Post } from "../posts"; +import { xLeadHandle } from "./config"; + +export type XSearchLeadSample = { + id: string; + url: string; + text: string; + createdAt: string; +}; + +export type XSearchLead = { + // The handle as the newest post writes it; `key` is its lower case. + handle: string; + key: string; + name?: string; + // Matching posts by this account (its reposts among them). + count: number; + reposts: number; + first: string; // ISO, the oldest matching post + last: string; // ISO, the newest + // The newest matching post the account wrote itself (else its newest repost). + sample: XSearchLeadSample; + // Posts channels already archiving this account (an X channel whose handle + // is this one), when there are. + archivedAs?: string[]; +}; + +export type XSearchLeads = { + leads: XSearchLead[]; + // Authors hidden by "Never archive", with their counts. + hidden: Array<{ handle: string; count: number }>; + // Matching posts read, and distinct authors among them (hidden included). + posts: number; + authors: number; + // Leads past `limit` that were not listed. + more: number; +}; + +export const X_SEARCH_LEADS_DEFAULT_LIMIT = 100; +export const X_SEARCH_LEAD_SAMPLE_CHARS = 280; + +function sampleOf(p: Post): XSearchLeadSample { + const text = p.text.replace(/\s+/g, " ").trim(); + return { + id: p.id, + url: p.url, + text: text.length > X_SEARCH_LEAD_SAMPLE_CHARS ? `${text.slice(0, X_SEARCH_LEAD_SAMPLE_CHARS - 1)}…` : text, + createdAt: p.createdAt, + }; +} + +// Ranked: most matching posts first, then the most recent, then by handle. +// A post is counted once by id, whatever its shard. +export function rankXSearchLeads( + posts: ReadonlyArray<Post>, + opts: { + exclude?: ReadonlyArray<string>; + // Lower-case handle → the slugs of X channels that archive it. + archived?: ReadonlyMap<string, string[]>; + limit?: number; + } = {}, +): XSearchLeads { + const exclude = new Set((opts.exclude ?? []).map((h) => h.toLowerCase())); + type Acc = { lead: XSearchLead; own?: Post; anyNewest: Post; newestAt: string }; + const byKey = new Map<string, Acc>(); + const seen = new Set<string>(); + for (const p of posts) { + if (seen.has(p.id)) continue; + seen.add(p.id); + const key = xLeadHandle(p.author); + if (!key) continue; + let acc = byKey.get(key); + if (!acc) { + acc = { + lead: { + handle: p.author.replace(/^@/, ""), + key, + count: 0, + reposts: 0, + first: p.createdAt, + last: p.createdAt, + sample: sampleOf(p), + }, + anyNewest: p, + newestAt: p.createdAt, + }; + byKey.set(key, acc); + } + const lead = acc.lead; + lead.count++; + if (p.isRepost) lead.reposts++; + if (p.createdAt < lead.first) lead.first = p.createdAt; + if (p.createdAt > lead.last) lead.last = p.createdAt; + if (p.createdAt >= acc.newestAt) { + acc.newestAt = p.createdAt; + acc.anyNewest = p; + lead.handle = p.author.replace(/^@/, ""); + if (p.authorName) lead.name = p.authorName; + } else if (!lead.name && p.authorName) { + lead.name = p.authorName; + } + if (!p.isRepost && (!acc.own || p.createdAt > acc.own.createdAt)) acc.own = p; + } + const all = [...byKey.values()].map((acc) => { + acc.lead.sample = sampleOf(acc.own ?? acc.anyNewest); + const slugs = opts.archived?.get(acc.lead.key); + if (slugs && slugs.length > 0) acc.lead.archivedAs = [...slugs].sort(); + return acc.lead; + }); + all.sort( + (a, b) => b.count - a.count || (b.last > a.last ? 1 : b.last < a.last ? -1 : 0) || a.key.localeCompare(b.key), + ); + const shown = all.filter((l) => !exclude.has(l.key)); + const hidden = all.filter((l) => exclude.has(l.key)).map((l) => ({ handle: l.handle, count: l.count })); + // A handle excluded that matched nothing (yet) is still listed as hidden. + for (const h of exclude) if (!byKey.has(h)) hidden.push({ handle: h, count: 0 }); + const limit = opts.limit ?? X_SEARCH_LEADS_DEFAULT_LIMIT; + return { + leads: shown.slice(0, limit), + hidden, + posts: seen.size, + authors: byKey.size, + more: Math.max(0, shown.length - limit), + }; +} + +// The channel an "Archive this account" makes: `<handle>-x`, on no site. The +// New channel form's field names (create-channel's `fields`). +export function xLeadChannelSlug(handle: string): string { + const key = xLeadHandle(handle); + if (!key) throw new Error(`"${handle}" is not an X handle (letters, digits and "_")`); + // A slug starts with a letter or a digit; a handle may start with "_". + return /^[a-z0-9]/.test(key) ? `${key}-x` : `x${key}-x`; +} + +export function xLeadChannelFields(lead: { handle: string; name?: string }): Record<string, string> { + const handle = lead.handle.replace(/^@/, ""); + return { + name: `${lead.name?.trim() || handle} (X)`, + handling: "transcribe", + url: `https://x.com/${handle}`, + platform: "twitter", + sourceKind: "social", + postFetcher: "x-gallery-dl", + socialHandle: handle, + }; +} diff --git a/common/lib/xSearch/walk.test.ts b/common/lib/xSearch/walk.test.ts @@ -0,0 +1,81 @@ +// An X search channel's walk, planned: the first walk from until/tomorrow down +// to since, a resume before anything else, the new days with a day of overlap, +// the earlier days when since moves back, and nothing when all is covered. +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xSearch/walk.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + coverAfterWalk, + describeXSearchWalk, + planXSearchWalk, + startXSearchWalk, + xSearchStateFor, +} from "./walk"; + +const NOW = new Date("2026-10-20T12:00:00Z"); + +test("the first walk starts at tomorrow (or until) and its windows reach no lower than since", () => { + const state = xSearchStateFor({ query: "zephyr" }, undefined); + assert.deepEqual(state, { queryKey: "zephyr" }); + assert.deepEqual(planXSearchWalk({ query: "zephyr" }, state, NOW), { + kind: "first", + walk: { top: "2026-10-21", since: "2026-07-21", until: "2026-10-21", emptyWindows: 0 }, + }); + assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2026-09-01", until: "2026-10-01", windowMonths: 1 }, state, NOW), { + kind: "first", + walk: { top: "2026-10-01", floor: "2026-09-01", since: "2026-09-01", until: "2026-10-01", emptyWindows: 0 }, + }); + assert.equal(planXSearchWalk({ query: "zephyr", since: "2026-11-01" }, state, NOW).kind, "none"); +}); + +test("a walk in progress is resumed before anything else", () => { + const walk = { ...startXSearchWalk("2026-10-21", "2025-01-01", 3), maxId: "1899" }; + const plan = planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, { queryKey: "zephyr", walk, coveredUntil: "2026-01-01" }, NOW); + assert.deepEqual(plan, { kind: "resume", walk }); +}); + +test("after a finished walk: the new days with a day of overlap, then the earlier days, then nothing", () => { + const covered = { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: "2026-10-15" }; + assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, covered, NOW), { + kind: "new", + walk: { top: "2026-10-21", floor: "2026-10-14", since: "2026-10-14", until: "2026-10-21", emptyWindows: 0 }, + }); + const upToDate = { ...covered, coveredUntil: "2026-10-21" }; + const none = planXSearchWalk({ query: "zephyr", since: "2025-01-01" }, upToDate, NOW); + assert.equal(none.kind, "none"); + assert.match((none as { reason: string }).reason, /already searched 2025-01-01 – 2026-10-21/); + assert.deepEqual(planXSearchWalk({ query: "zephyr", since: "2024-06-01" }, upToDate, NOW), { + kind: "earlier", + walk: { top: "2025-01-02", floor: "2024-06-01", since: "2024-10-02", until: "2025-01-02", emptyWindows: 0 }, + }); + // A fixed until already covered: nothing new above it. + assert.equal(planXSearchWalk({ query: "zephyr", since: "2025-01-01", until: "2026-10-15" }, covered, NOW).kind, "none"); +}); + +test("a new query starts afresh; the dates alone do not", () => { + const stored = { queryKey: "zephyr", coveredSince: "2025-01-01", coveredUntil: "2026-10-15" }; + assert.equal(xSearchStateFor({ query: "zephyr" }, stored), stored); + assert.deepEqual(xSearchStateFor({ query: "zephyr OR zephyrs" }, stored), { queryKey: "zephyr OR zephyrs" }); + assert.deepEqual(xSearchStateFor({ query: "zephyr", lang: "en" }, stored), { queryKey: "zephyr lang:en" }); +}); + +test("coverage after a walk is the union of what was covered and what was walked", () => { + assert.deepEqual(coverAfterWalk({}, { top: "2026-10-21" }, "2025-01-01"), { + coveredSince: "2025-01-01", + coveredUntil: "2026-10-21", + }); + assert.deepEqual(coverAfterWalk({ coveredSince: "2025-01-01", coveredUntil: "2026-10-15" }, { top: "2026-10-21" }, "2026-10-14"), { + coveredSince: "2025-01-01", + coveredUntil: "2026-10-21", + }); + assert.deepEqual(coverAfterWalk({ coveredSince: "2025-01-01", coveredUntil: "2026-10-21" }, { top: "2025-01-02" }, "2024-06-01"), { + coveredSince: "2024-06-01", + coveredUntil: "2026-10-21", + }); + assert.equal(describeXSearchWalk(undefined), "not searched yet"); + assert.equal( + describeXSearchWalk({ queryKey: "z", coveredSince: "2025-01-01", coveredUntil: "2026-10-21", walk: { top: "2025-01-02", floor: "2024-06-01", since: "2024-10-02", until: "2025-01-02", emptyWindows: 0, maxId: "9" } }), + "searched 2025-01-01 – 2026-10-21; walking 2024-10-02 – 2025-01-02 (down to 2024-06-01), resuming inside the window", + ); +}); diff --git a/common/lib/xSearch/walk.ts b/common/lib/xSearch/walk.ts @@ -0,0 +1,119 @@ +// An X search channel's walk, planned (pure: no I/O, so every step is testable +// without a fetcher). A walk goes BACKWARDS in search windows from a `top` day +// to a `floor`, newest first — the older walk's arithmetic +// (social/olderBackfill.ts) over the channel's query. What finished walks have +// searched end to end is [coveredSince, coveredUntil); each fetch walks ONE +// stretch outside it, newest first: +// - the first walk: from `until` (or tomorrow) down to `since` (or until a +// year of windows in a row holds no match); +// - the new days: from `until`/tomorrow down to the day before +// `coveredUntil` (one day of overlap, deduped); +// - the earlier days, when `since` was moved below `coveredSince`. +// A walk cut short (budget, cancel, drain, a limit, an error) is resumed from +// its saved position by the next fetch before anything else. + +import type { XSearchWalkState } from "../posts-server"; +import { + addUtcDays, + addUtcMonths, + OLDER_WINDOW_MONTHS, + utcDayOf, +} from "../../social/olderBackfill"; +import { xSearchQueryKey, type XSearchConfig } from "./config"; + +export type XSearchWalk = NonNullable<XSearchWalkState["walk"]>; + +export type XSearchWalkKind = "resume" | "first" | "new" | "earlier"; + +export type XSearchWalkPlan = + | { kind: XSearchWalkKind; walk: XSearchWalk } + | { kind: "none"; reason: string }; + +const later = (a: string, b: string | undefined): string => (b !== undefined && b > a ? b : a); + +// The first window of a walk from `top` down to `floor`. +export function startXSearchWalk(top: string, floor: string | undefined, months: number): XSearchWalk { + return { + top, + ...(floor !== undefined ? { floor } : {}), + since: later(addUtcMonths(top, -months), floor), + until: top, + emptyWindows: 0, + }; +} + +// The state this config's walk continues from: the stored one when it belongs +// to the same query, else a fresh one (a new query is a new search). +export function xSearchStateFor( + config: Pick<XSearchConfig, "query" | "lang">, + stored: XSearchWalkState | undefined, +): XSearchWalkState { + const queryKey = xSearchQueryKey(config); + return stored && stored.queryKey === queryKey ? stored : { queryKey }; +} + +// What the next fetch walks. +export function planXSearchWalk( + config: XSearchConfig, + state: XSearchWalkState, + now: Date = new Date(), +): XSearchWalkPlan { + const months = config.windowMonths ?? OLDER_WINDOW_MONTHS; + if (state.walk) return { kind: "resume", walk: state.walk }; + const top = config.until ?? addUtcDays(utcDayOf(now), 1); + if (config.since !== undefined && config.since >= top) { + return { kind: "none", reason: `nothing to search: ${config.since} is not before ${top}` }; + } + if (!state.coveredUntil) { + return { kind: "first", walk: startXSearchWalk(top, config.since, months) }; + } + if (top > state.coveredUntil) { + // One day of overlap below what was covered: a post made on the day the + // last walk started is read again (and skipped) rather than missed. + const floor = later(addUtcDays(state.coveredUntil, -1), config.since); + return { kind: "new", walk: startXSearchWalk(top, floor, months) }; + } + if (config.since !== undefined && state.coveredSince !== undefined && config.since < state.coveredSince) { + return { + kind: "earlier", + walk: startXSearchWalk(addUtcDays(state.coveredSince, 1), config.since, months), + }; + } + return { + kind: "none", + reason: + `already searched ${state.coveredSince ?? "?"} – ${state.coveredUntil}` + + (config.until ? "" : "; the next fetch after today searches the new days"), + }; +} + +// The covered span once `walk` has been walked to its end, its last window +// starting at `endSince`. +export function coverAfterWalk( + state: Pick<XSearchWalkState, "coveredSince" | "coveredUntil">, + walk: Pick<XSearchWalk, "top">, + endSince: string, +): { coveredSince: string; coveredUntil: string } { + return { + coveredSince: + state.coveredSince !== undefined && state.coveredSince < endSince ? state.coveredSince : endSince, + coveredUntil: + state.coveredUntil !== undefined && state.coveredUntil > walk.top ? state.coveredUntil : walk.top, + }; +} + +// One line for the channel page and the ops read. +export function describeXSearchWalk(state: XSearchWalkState | undefined): string { + if (!state) return "not searched yet"; + const parts: string[] = []; + if (state.coveredUntil) parts.push(`searched ${state.coveredSince ?? "?"} – ${state.coveredUntil}`); + if (state.walk) { + parts.push( + `walking ${state.walk.since} – ${state.walk.until}` + + (state.walk.floor ? ` (down to ${state.walk.floor})` : "") + + (state.walk.maxId ? ", resuming inside the window" : ""), + ); + } + if (parts.length === 0) return "not searched yet"; + return parts.join("; "); +} diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -158,6 +158,35 @@ export type OlderPostFetchResult = { drained?: boolean; }; +// Input for an X SEARCH channel's walk (`SocialFetcher.fetchSearch`, release +// 38): the older walk's windows, login, limit, signal, log and checkpoints, +// with a query across accounts in place of an account's handle. +export type SearchPostFetchInput = Pick< + OlderPostFetchInput, + | "channelSlug" + | "seenIds" + | "cookies" + | "cookieSource" + | "browserCookies" + | "limit" + | "signal" + | "drain" + | "onLog" + | "position" + | "floor" + | "windowPauseMs" + | "onCheckpoint" +> & { + // The channel's query and language (lib/xSearch/config.ts); the walk adds + // each window's since:/until: and its max_id: resume point. + search: { query: string; lang?: string }; + // Each window's span in months. Default: the older walk's. + months?: number; + // Windows in a row with no match before the walk ends. Default: none with + // a floor (every window down to it is searched), else the older walk's. + maxEmptyWindows?: number; +}; + export type SocialFetcherProbe = { ok: boolean; // Display name for the account, used to autofill the channel form. @@ -300,6 +329,10 @@ export type SocialFetcher = { // reach (X: search windows). A fetcher without it has no such backfill, and // the channel page offers no "Fetch older posts" for it. fetchOlder?(input: OlderPostFetchInput): Promise<OlderPostFetchResult>; + // Optional: walk a SEARCH across accounts in windows (an X search channel, + // release 38). A fetcher without it cannot hold such a channel, and its + // fetch refuses by name. + fetchSearch?(input: SearchPostFetchInput): Promise<OlderPostFetchResult>; // Optional: capture specific archived posts — a screenshot and the attached // media — into `posts-media/<id>/` (X: the logged-in profile shoots the // post, gallery-dl downloads its media). A fetcher without it cannot, and diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -34,7 +34,13 @@ import { cookieArgs } from "../lib/cookiePolicy"; import type { Post } from "../lib/posts"; import type { OlderBackfillPosition } from "../lib/posts-server"; import { normalizeXTweet, xCreatedAt, type XTweetRaw } from "./xNormalize"; -import { olderFloorDay, stepOlderWindow } from "./olderBackfill"; +import { + OLDER_MAX_EMPTY_WINDOWS, + OLDER_WINDOW_MONTHS, + olderFloorDay, + stepOlderWindow, +} from "./olderBackfill"; +import { xSearchUrl as xSearchPageUrl, xSearchWindowQuery } from "../lib/xSearch/config"; import { launchXProfile, readXSessionStatus, @@ -58,6 +64,7 @@ import { type PostFetchResult, type SocialFetcher, type SocialFetcherProbe, + type SearchPostFetchInput, type OnePostFetchInput, type OnePostFetchResult, } from "./fetchers"; @@ -432,7 +439,7 @@ export function xSearchQuery( // into a space BEFORE it unquotes, so an encoded "+" survives as itself. // `f=live` is X's own "Latest" tab, which is also what gallery-dl asks for. export function xSearchUrl(query: string): string { - return `https://x.com/search?q=${encodeURIComponent(query)}&f=live`; + return xSearchPageUrl(query); } export function buildGalleryDlSearchArgs( @@ -441,6 +448,16 @@ export function buildGalleryDlSearchArgs( position: Pick<OlderBackfillPosition, "since" | "until" | "maxId">; }, ): string[] { + return buildGalleryDlQueryArgs({ ...opts, query: xSearchQuery(opts.handle, opts.position) }); +} + +// The argv for ONE search window, whatever the query: an account's older walk +// (`from:<handle>`, above) or an X search channel's own query +// (lib/xSearch/config.ts, xSearchWindowQuery). The query already carries the +// window's since:/until: and its max_id: resume point. +export function buildGalleryDlQueryArgs( + opts: GalleryDlLoginAndCap & { query: string }, +): string[] { const args = galleryDlCommonArgs(opts); args.push( // Newest first, paged by max_id — the order the resume point relies on. @@ -449,7 +466,7 @@ export function buildGalleryDlSearchArgs( "-o", "extractor.twitter.search-pagination=max_id", ); - args.push(xSearchUrl(xSearchQuery(opts.handle, opts.position))); + args.push(xSearchUrl(opts.query)); return args; } @@ -835,8 +852,6 @@ const SEARCH_NEEDS_LOGIN = export async function fetchOlderViaSearch( input: OlderPostFetchInput, ): Promise<OlderPostFetchResult> { - const { channelSlug, seenIds, signal, onLog } = input; - const bin = getPaths().galleryDlBin; let handle: string; try { handle = xSearchHandle(input.handle); @@ -848,6 +863,61 @@ export async function fetchOlderViaSearch( error: (err as Error).message, }; } + return walkSearchWindows(input, { + queryFor: (at) => xSearchQuery(handle, at), + accountHandle: handle, + opening: `Searching @${handle}'s posts backwards`, + doneLabel: "Older-posts backfill complete", + }); +} + +// AN X SEARCH CHANNEL'S WALK (release 38, controller/fetchXSearch.ts): the +// same windows, pacing, budget, login and resume point as the older walk, +// with the channel's own query (any author) in place of `from:<handle>`. The +// floor is the channel's `since`; with one, every window down to it is +// searched (an empty stretch is not the end of a query's history), and +// without one the walk ends after a year of empty windows. +export async function fetchSearchViaWindows( + input: SearchPostFetchInput, +): Promise<OlderPostFetchResult> { + const months = input.months ?? OLDER_WINDOW_MONTHS; + try { + xSearchWindowQuery(input.search, input.position); + } catch (err) { + return { posts: [], complete: false, position: input.position, error: (err as Error).message }; + } + return walkSearchWindows( + { ...input, handle: "", accountUrl: "" }, + { + queryFor: (at) => xSearchWindowQuery(input.search, at), + opening: `Searching X for ${JSON.stringify(input.search.query)} backwards`, + doneLabel: "Search walk complete", + months, + maxEmptyWindows: + input.maxEmptyWindows ?? + (input.floor !== undefined ? Number.POSITIVE_INFINITY : OLDER_MAX_EMPTY_WINDOWS), + }, + ); +} + +type SearchWalkSpec = { + // The query for one window (its since:/until:/max_id: included). + queryFor: (position: OlderBackfillPosition) => string; + // The account whose `user` record carries its creation date (an older + // walk); a search across accounts has none. + accountHandle?: string; + opening: string; + doneLabel: string; + months?: number; + maxEmptyWindows?: number; +}; + +async function walkSearchWindows( + input: OlderPostFetchInput, + spec: SearchWalkSpec, +): Promise<OlderPostFetchResult> { + const { channelSlug, seenIds, signal, onLog } = input; + const bin = getPaths().galleryDlBin; const { cookies, cookieFile } = await galleryDlLoginFor(input); if (!cookies && !cookieFile) { onLog?.(`[auth] ${SEARCH_NEEDS_LOGIN}`); @@ -911,7 +981,7 @@ export async function fetchOlderViaSearch( }; onLog?.( - `Searching @${handle}'s posts backwards, ${position.since} – ${position.until}` + + `${spec.opening}, ${position.since} – ${position.until}` + (position.maxId ? " from the saved resume point" : "") + ` (up to ${Math.round(BACKFILL_BUDGET_MS / 60_000)} min this run; progress is saved as it goes)`, ); @@ -943,12 +1013,11 @@ export async function fetchOlderViaSearch( channelSlug, seenIds, stopAtKnown: false, - accountHandle: handle, + accountHandle: spec.accountHandle, onLog, }); - const args = buildGalleryDlSearchArgs({ - handle, - position: windowStart, + const args = buildGalleryDlQueryArgs({ + query: spec.queryFor(windowStart), cookies, cookieFile, limit: remainingLimit, @@ -1053,9 +1122,11 @@ export async function fetchOlderViaSearch( hadPosts: stream.distinct > 0 || Boolean(windowStart.maxId), floor: olderFloorDay(input.floor, accountCreatedAt), nothingFound: nothingArchived && read === 0, + ...(spec.months !== undefined ? { months: spec.months } : {}), + ...(spec.maxEmptyWindows !== undefined ? { maxEmptyWindows: spec.maxEmptyWindows } : {}), }); if (step.complete) { - onLog?.(`Older-posts backfill complete: ${step.reason}.`); + onLog?.(`${spec.doneLabel}: ${step.reason}.`); return { posts: carried, complete: true, @@ -1347,6 +1418,8 @@ export const xGalleryDlFetcher: SocialFetcher = { fetchOlder: fetchOlderViaSearch, + fetchSearch: fetchSearchViaWindows, + captureByIds: captureXPostsByIds, }; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Save an X search across accounts, and see who keeps saying it.** Paste an X search page's URL (as copied from X's search box) into the New channel form, or choose **X search** as the platform and type a query: it makes an X search channel whose records are the matching posts from any account. The query is X's own — OR, "quotes", -term, from:, to:, @name, url:, filter:, lang: — and its dates are the channel's **Since** and **Until** (a pasted URL's since:/until: are moved there; typed into the query they are refused with a sentence). Fetch posts searches backwards a window at a time (3 months, or your **Window**), newest first, at the older walk's pace and with its X login; a run cut short resumes where it stopped, later fetches search only the new days, and a new query starts afresh. The channel page's **Leads** lists the accounts by how many matching posts they made, with their first and last day and a sample: **Archive this account** creates `<handle>-x` on no site and starts its fetch, **Never archive** hides the account (Restore brings it back), and an account an X channel already archives says so. An X search channel is never put on a site. From a terminal: `pnpm ops create-channel` with the search URL, `pnpm ops fetch-posts`, `pnpm ops get channel <slug> --leads` and `pnpm ops x-search-lead`; the MCP has `x_search_leads`. Nothing calls a model. Needs a restart of the editor. - **A forum thread's fetch resumes where it stopped instead of reading the thread again.** A forum channel now keeps two places: how far it has caught up with the newest posts, and where its walk back through the older pages stands. **Fetch posts** reads from the last page down to the newest post it already holds, then jumps straight to the older pages it has yet to read — a run capped at a few pages ("Latest N pages") no longer loses the older place, and a page whose posts are all held is stepped past without counting against the cap. Pages that shifted because posts were deleted are still read without a gap. **Full re-walk** (it replaces "Re-fetch full history" on a forum channel) asks first, with the page count and how long it takes at the channel's pace, then reads every page from the last to page 1: edited posts are updated, and posts no page shows any more are counted in the log and kept. The panel's status line says where both stand — "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)". The older place is checked against the pages the archive holds at every run, so a channel whose place was overwritten by the old single resume point heals on its next fetch. A page that reads empty — as one can just after a browser check clears — is loaded once more before the fetch stops on it. **Retry after a block** (the Forum session section) makes Fetch posts wait out a browser check that will not clear or a refused page — 30 minutes, then try again, up to 12 tries, say — and never retries a captcha or a login; `pnpm ops fetch-posts` takes `"retryOnBlock": {"minutes": 30, "max": 12}` (or `true` for the saved setting). Needs a restart of the editor. - **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor. - **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten. diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts @@ -13,6 +13,7 @@ import { tierOf, } from "yt-dlp-transcript-common/lib/channelPriority"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { opsAuth } from "../../_lib"; export const dynamic = "force-dynamic"; @@ -63,7 +64,25 @@ export async function GET( ); } const priority = getSettings().channelPriority; - const wantCounts = new URL(request.url).searchParams.get("counts") === "1"; + const sp = new URL(request.url).searchParams; + const wantCounts = sp.get("counts") === "1"; + // `?leads=1` (release 38): an X search channel's leads — the accounts its + // matching posts came from, ranked (`&limit=N`, default 100). Refused, with + // the sentence, for any other channel. + let leads: unknown = undefined; + if (sp.get("leads") === "1") { + const limitRaw = sp.get("limit"); + const limit = limitRaw === null ? undefined : Number(limitRaw); + if (limit !== undefined && !(Number.isInteger(limit) && limit > 0)) { + return NextResponse.json({ ok: false, error: `"limit" must be a whole number above 0` }, { status: 400 }); + } + const read = await readXSearchLeads(paths, slug, limit !== undefined ? { limit } : {}); + if (!read.ok) return NextResponse.json({ ok: false, error: read.error }, { status: 400 }); + const { ok: _ok, slug: _slug, ...rest } = read; + void _ok; + void _slug; + leads = rest; + } const [snapshot, stat, media] = await Promise.all([ readChannelSnapshot(paths, slug), wantCounts ? readChannelStat(paths, slug) : Promise.resolve(null), @@ -88,6 +107,7 @@ export async function GET( }, // null unless ?counts=1 — see the header. counts: stat, + ...(leads !== undefined ? { leads } : {}), media, report: snapshot ? { diff --git a/editor/app/api/ops/x-search-lead/route.test.ts b/editor/app/api/ops/x-search-lead/route.test.ts @@ -0,0 +1,149 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/x-search-lead/route.test.ts" +// +// An X search channel over ops (release 38 lane S), against a temp corpus: the +// leads read (`GET /api/ops/channel/<slug>?leads=1`), x-search-lead's Never +// archive / Restore and the Archive dry run, and every refusal — create-channel +// of a search channel on a site, a lead on a channel that is not a search, an +// account already archived. A successful create ends in revalidatePath, which +// needs a running Next server: Archive this account is driven in +// e2e/x-search.spec.ts. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-search-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +async function channel(slug: string, config: Record<string, unknown>, posts?: string[]): Promise<void> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + if (posts) { + const lines = posts.map((author, i) => { + const id = String(1899000000000000000n + BigInt(i)); + return JSON.stringify({ + id, + slug: `${slug}/${id}`, + channelSlug: slug, + author, + createdAt: `2025-0${i + 1}-01T00:00:00.000Z`, + uploadDate: `20250${i + 1}01`, + text: `zephyr ${i}`, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }); + }); + await writeFile(path.join(dir, "posts", "2025-01.jsonl"), lines.join("\n") + "\n"); + } +} +await channel( + "demo-search", + { + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr" }, + }, + ["alice", "alice", "bob"], +); +await channel("bob-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "bob", url: "https://x.com/bob" }); +await mkdir(path.join(ROOT, "sites", "demo-site"), { recursive: true }); +await writeFile( + path.join(ROOT, "sites", "demo-site", "site.json"), + JSON.stringify({ siteId: "demo-site", siteTitle: "Demo", channels: [] }), +); + +const lead = (await import("./route")).POST; +const create = (await import("../create-channel/route")).POST; +const read = (await import("../channel/[slug]/route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(handler: (r: Request) => Promise<Response>, body: Record<string, unknown>) { + const res = await handler( + new Request("http://localhost/api/ops/x", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} +async function get(slug: string, query: string) { + const res = await (read as unknown as (r: Request, ctx: { params: Promise<{ slug: string }> }) => Promise<Response>)( + new Request(`http://localhost/api/ops/channel/${slug}?${query}`, { headers: { authorization: "Bearer test-token" } }), + { params: Promise.resolve({ slug }) }, + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} +const exists = (p: string) => access(p).then(() => true, () => false); + +test("the leads read: ranked, archived accounts named; refused for any other channel and a bad limit", async () => { + const res = await get("demo-search", "leads=1"); + assert.equal(res.status, 200); + const leads = res.json.leads as { query: string; leads: { key: string; count: number; archivedAs?: string[] }[]; posts: number }; + assert.equal(leads.query, "zephyr"); + assert.equal(leads.posts, 3); + assert.deepEqual(leads.leads.map((l) => [l.key, l.count, l.archivedAs ?? []]), [["alice", 2, []], ["bob", 1, ["bob-x"]]]); + const plain = await get("demo-search", ""); + assert.equal(plain.json.leads, undefined); + const other = await get("bob-x", "leads=1"); + assert.equal(other.status, 400); + assert.match(String(other.json.error), /bob-x is not an X search channel/); + assert.equal((await get("demo-search", "leads=1&limit=0")).status, 400); +}); + +test("never, restore, and the archive dry run; refusals in the controller's sentences", async () => { + const never = await call(lead, { slug: "demo-search", handle: "@alice", action: "never" }); + assert.deepEqual(never.json, { ok: true, exclude: ["alice"], changed: true }); + const hidden = await get("demo-search", "leads=1"); + assert.deepEqual((hidden.json.leads as { hidden: unknown }).hidden, [{ handle: "alice", count: 2 }]); + const restore = await call(lead, { slug: "demo-search", handle: "alice", action: "restore" }); + assert.deepEqual(restore.json, { ok: true, exclude: [], changed: true }); + + const dry = await call(lead, { slug: "demo-search", handle: "alice", action: "archive", dryRun: true }); + assert.equal(dry.status, 200); + assert.equal(dry.json.slug, "alice-x"); + assert.equal((dry.json.fields as Record<string, string>).url, "https://x.com/alice"); + assert.equal(await exists(path.join(ROOT, "channels", "alice-x")), false); + + const archived = await call(lead, { slug: "demo-search", handle: "bob", action: "archive" }); + assert.equal(archived.status, 400); + assert.equal(archived.json.error, "@bob is already archived: bob-x."); + const notSearch = await call(lead, { slug: "bob-x", handle: "alice", action: "never" }); + assert.equal(notSearch.status, 400); + assert.match(String(notSearch.json.error), /not an X search channel/); + const badAction = await call(lead, { slug: "demo-search", handle: "alice", action: "follow" }); + assert.equal(badAction.status, 400); + assert.match(String(badAction.json.error), /"action" must be one of archive, never, restore/); + const stray = await call(lead, { slug: "demo-search", handle: "alice", action: "never", dryRun: true }); + assert.equal(stray.status, 400); +}); + +test("create-channel makes no X search channel on a site", async () => { + const onSite = await call(create, { + slug: "made-search", + fields: { name: "Made search", handling: "transcribe", url: "https://x.com/search?q=zephyr" }, + sites: [{ siteId: "demo-site" }], + }); + assert.equal(onSite.status, 400); + assert.equal(onSite.json.error, "made-search is an X search channel: it is never put on a site."); + assert.equal(await exists(path.join(ROOT, "channels", "made-search")), false); + const badQuery = await call(create, { + slug: "made-search", + fields: { name: "Made search", handling: "transcribe", platform: "x-search", xSearchQuery: "zephyr until:2025-01-01" }, + }); + assert.equal(badQuery.status, 400); + assert.match(String(badQuery.json.error), /Take until: out of the query/); + const site = JSON.parse(await readFile(path.join(ROOT, "sites", "demo-site", "site.json"), "utf8")); + assert.deepEqual(site.channels, []); +}); diff --git a/editor/app/api/ops/x-search-lead/route.ts b/editor/app/api/ops/x-search-lead/route.ts @@ -0,0 +1,46 @@ +import { NextResponse } from "next/server"; +import { + archiveXSearchLeadAction, + hideXSearchLeadAction, +} from "../../../channels/[slug]/xSearchActions"; +import { oneOf, ops, opsFail, optBool, optString, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, handle, action: "archive" | "never" | "restore", name?, fetch?, dryRun? } +// -> archive: { ok: true, slug, jobIds, jobId? } (dryRun: { ok, slug, fields, dryRun }) +// -> never | restore: { ok: true, exclude, changed } +// +// An X search channel's leads view, over HTTP (release 38 lane S). "archive" +// is Archive this account: a `<handle>-x` X channel on NO site, created by +// the New channel form's path with its first post fetch started (`fetch: +// false` skips it), named `name` (or the handle) + " (X)". Refused: a channel +// that is not an X search channel, a handle that is not one, an account an X +// channel archives already, a slug taken. "never" is Never archive — the +// handle into the channel's `xSearch.exclude`, hidden from the leads — and +// "restore" undoes it. Read the leads with `get channel <slug> --leads`. +export async function POST(request: Request) { + return ops(request, ["slug", "handle", "action", "name", "fetch", "dryRun"], async (body) => { + const slug = reqSlug(body, "slug"); + const handle = reqString(body, "handle"); + const action = oneOf(body, "action", ["archive", "never", "restore"] as const); + if (action === "archive") { + const name = optString(body, "name"); + const res = await archiveXSearchLeadAction(slug, handle, { + ...(name ? { name } : {}), + ...(optBool(body, "dryRun") ? { dryRun: true } : {}), + ...(optBool(body, "fetch") === false ? { fetch: false } : {}), + }); + if (!res.ok) return opsFail(res.error); + if (res.dryRun) return NextResponse.json({ ok: true, dryRun: true, slug: res.slug, fields: res.fields }); + const jobIds = res.jobIds ?? []; + return NextResponse.json({ ok: true, slug: res.slug, jobIds, ...(jobIds.length === 1 ? { jobId: jobIds[0] } : {}) }); + } + if (body.dryRun !== undefined || body.name !== undefined || body.fetch !== undefined) { + return opsFail(`"dryRun", "name" and "fetch" apply only to action "archive"`); + } + const res = await hideXSearchLeadAction(slug, handle, action === "never"); + if (!res.ok) return opsFail(res.error); + return NextResponse.json({ ok: true, exclude: res.exclude ?? [], changed: res.changed === true }); + }); +} diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -48,6 +48,8 @@ export type SocialChannelState = { platform?: string; // A forum thread's browser session (its host's profile), when it is one. forumSession?: ForumSessionStatus; + // An X search channel (release 38): its query and where its walk stands. + search?: { query: string; walk: string }; // A forum thread's two walks (lib/forumWalk.ts): the status line, the // thread's last page as last seen, the mean seconds a page takes at the // channel's pace, and the Fetch posts button's retry after a block. @@ -193,7 +195,16 @@ export function SocialChannelPanel({ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> <h2 className="text-sm font-medium">Posts</h2> <span className="text-xs text-muted-foreground"> - {forum ? state.handle : `@${state.handle}`} · {state.fetcherLabel} + {state.search ? ( + <> + X search <code aria-label="x search query" className="font-mono">{state.search.query}</code> + </> + ) : forum ? ( + state.handle + ) : ( + `@${state.handle}` + )}{" "} + · {state.fetcherLabel} </span> </div> @@ -227,6 +238,7 @@ export function SocialChannelPanel({ {state.canFetchOlder && ( <Stat label="Older posts" value={state.olderStatus} /> )} + {state.search && <Stat label="Search walk" value={state.search.walk} />} </dl> {state.availableFetchers.length > 1 && ( @@ -319,11 +331,15 @@ export function SocialChannelPanel({ type="button" onClick={() => run(true)} disabled={pending} - aria-label="refetch full history" - title="Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + aria-label={state.search ? "search again from the top" : "refetch full history"} + title={ + state.search + ? "Walk the whole search again from its newest window. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + : "Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates." + } className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" > - Re-fetch full history + {state.search ? "Search again from the top" : "Re-fetch full history"} </button> )} {state.canFetchOlder && ( diff --git a/editor/app/channels/[slug]/components/XSearchLeadsPanel.tsx b/editor/app/channels/[slug]/components/XSearchLeadsPanel.tsx @@ -0,0 +1,187 @@ +"use client"; + +// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): the accounts its matching +// posts came from, most matches first — each with Archive this account (a +// `<handle>-x` channel on no site, its first fetch started) and Never archive +// (hidden here, kept in the channel's `xSearch.exclude`; Restore undoes it). +// No model: the counts are the channel's own posts. + +import { useState, useTransition } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import type { XSearchLeads } from "yt-dlp-transcript-common/lib/xSearch/leads"; +import { archiveXSearchLeadAction, hideXSearchLeadAction } from "../xSearchActions"; + +const day = (iso: string) => iso.slice(0, 10); + +export function XSearchLeadsPanel({ slug, leads }: { slug: string; leads: XSearchLeads }) { + const router = useRouter(); + const [pending, startTransition] = useTransition(); + const [note, setNote] = useState<{ kind: "ok" | "error"; text: string; href?: string } | null>(null); + + const archive = (handle: string, name?: string) => + startTransition(async () => { + setNote(null); + const res = await archiveXSearchLeadAction(slug, handle, name ? { name } : {}); + if (!res.ok) { + setNote({ kind: "error", text: res.error }); + return; + } + setNote({ + kind: "ok", + text: `Created ${res.slug} on no site${res.jobIds?.length ? "; its first fetch is queued" : ""}.`, + href: `/channels/${res.slug}`, + }); + router.refresh(); + }); + + const hide = (handle: string, hidden: boolean) => + startTransition(async () => { + setNote(null); + const res = await hideXSearchLeadAction(slug, handle, hidden); + if (!res.ok) { + setNote({ kind: "error", text: res.error }); + return; + } + router.refresh(); + }); + + return ( + <section data-x-search-leads="" className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="text-sm font-medium">Leads</h2> + <span aria-label="leads summary" className="text-xs text-muted-foreground"> + {leads.authors} account{leads.authors === 1 ? "" : "s"} across {leads.posts} matching post + {leads.posts === 1 ? "" : "s"} + {leads.hidden.length > 0 ? ` · ${leads.hidden.length} hidden` : ""} + </span> + </div> + + {note && ( + <p role={note.kind === "error" ? "alert" : "status"} className={`text-xs ${note.kind === "error" ? "text-destructive" : "text-success"}`}> + {note.text}{" "} + {note.href && ( + <Link href={note.href} className="underline"> + Open it + </Link> + )} + </p> + )} + + {leads.leads.length === 0 ? ( + <p className="text-sm text-muted-foreground">No matching posts yet: fetch the search.</p> + ) : ( + <div className="overflow-x-auto"> + <table className="w-full min-w-[40rem] text-sm"> + <thead> + <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted-foreground"> + <th className="py-1 pr-3 font-medium">Account</th> + <th className="py-1 pr-3 font-medium">Matches</th> + <th className="py-1 pr-3 font-medium">First – last</th> + <th className="py-1 pr-3 font-medium">Sample</th> + <th className="py-1 font-medium" /> + </tr> + </thead> + <tbody> + {leads.leads.map((lead) => ( + <tr key={lead.key} data-x-lead={lead.key} className="border-b border-border align-top last:border-0"> + <td className="py-2 pr-3"> + <a + href={`https://x.com/${lead.handle}`} + target="_blank" + rel="noopener noreferrer" + className="font-mono underline" + > + @{lead.handle} + </a> + {lead.name && <div className="text-xs text-muted-foreground">{lead.name}</div>} + </td> + <td className="py-2 pr-3 font-mono" aria-label={`matches for ${lead.handle}`}> + {lead.count} + {lead.reposts > 0 && ( + <span className="text-xs text-muted-foreground"> ({lead.reposts} repost{lead.reposts === 1 ? "" : "s"})</span> + )} + </td> + <td className="py-2 pr-3 font-mono text-xs whitespace-nowrap"> + {day(lead.first)} – {day(lead.last)} + </td> + <td className="py-2 pr-3 text-xs"> + <a href={lead.sample.url} target="_blank" rel="noopener noreferrer" className="hover:underline"> + {lead.sample.text || "(no text)"} + </a> + </td> + <td className="py-2"> + {lead.archivedAs?.length ? ( + <span className="text-xs text-muted-foreground"> + Archived as{" "} + {lead.archivedAs.map((s, i) => ( + <span key={s}> + {i > 0 ? ", " : ""} + <Link href={`/channels/${s}`} className="underline"> + {s} + </Link> + </span> + ))} + </span> + ) : ( + <div className="flex flex-wrap gap-2"> + <button + type="button" + onClick={() => archive(lead.handle, lead.name)} + disabled={pending} + aria-label={`archive ${lead.handle}`} + className="whitespace-nowrap rounded-md border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50" + > + Archive this account + </button> + <button + type="button" + onClick={() => hide(lead.handle, true)} + disabled={pending} + aria-label={`never archive ${lead.handle}`} + className="whitespace-nowrap rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-muted disabled:opacity-50" + > + Never archive + </button> + </div> + )} + </td> + </tr> + ))} + </tbody> + </table> + {leads.more > 0 && ( + <p className="mt-2 text-xs text-muted-foreground"> + {leads.more} more account{leads.more === 1 ? "" : "s"} with fewer matches not listed. + </p> + )} + </div> + )} + + {leads.hidden.length > 0 && ( + <details data-x-search-hidden="" className="text-sm"> + <summary className="cursor-pointer text-xs text-muted-foreground"> + Never archive ({leads.hidden.length}) + </summary> + <ul className="mt-2 flex flex-col gap-1"> + {leads.hidden.map((h) => ( + <li key={h.handle} className="flex items-center gap-2"> + <span className="font-mono">@{h.handle}</span> + <span className="text-xs text-muted-foreground">{h.count} match{h.count === 1 ? "" : "es"}</span> + <button + type="button" + onClick={() => hide(h.handle, false)} + disabled={pending} + aria-label={`restore ${h.handle}`} + className="rounded-md border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50" + > + Restore + </button> + </li> + ))} + </ul> + </details> + )} + </section> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -33,6 +33,10 @@ import { WaybackLivePanel } from "./components/WaybackLivePanel"; import { waybackLiveState } from "./waybackLiveState"; import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk"; +import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { XSearchLeadsPanel } from "./components/XSearchLeadsPanel"; import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; import { pageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view"; import { postsMediaDir, readPostCapture } from "yt-dlp-transcript-common/social/postCapture"; @@ -215,6 +219,9 @@ export default async function ChannelDetailPage({ // capture — no fetcher, nothing to fetch. const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : []; const wayback = isWaybackPagesChannel(config) ? await waybackPagesRows(channelRoot, slug, pageRecords, postAvailability) : null; + // An X SEARCH channel (release 38): its query, its walk and its leads. + const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null; + const leads = xSearch ? await readXSearchLeads(paths, slug) : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -260,6 +267,14 @@ export default async function ChannelDetailPage({ accountUrl: config.url, platform: config.platform, ...(forumSession ? { forumSession } : {}), + ...(xSearch + ? { + search: { query: xSearch.query, walk: describeXSearchWalk(fetchState?.search) }, + canFetchOlder: false, + // Only gallery-dl can walk a search: no method to switch to. + availableFetchers: [], + } + : {}), ...(forumDerived ? { forumWalk: { @@ -273,6 +288,7 @@ export default async function ChannelDetailPage({ }} /> )} + {leads && leads.ok && <XSearchLeadsPanel slug={slug} leads={leads} />} {/* THE SAME DANGER ZONE A VIDEO CHANNEL HAS, which a social channel used to lack entirely: this branch returns before the stage list, so a misspelled X channel could not be renamed from the editor. The diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -21,6 +21,8 @@ import { } from "yt-dlp-transcript-common/controller/channels"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; +import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; +import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; import { @@ -213,6 +215,8 @@ export async function fetchPostsAction( // A Wayback pages channel is never fetched: its captures are imported one // by one (import-page), as chosen — no unattended crawling (release 37). if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; + // An X search channel's one walk is its search windows (release 38). + if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL }; if (older) { await registerBuiltinSocialFetchers(); const problem = olderPostsProblem( diff --git a/editor/app/channels/[slug]/xSearchActions.ts b/editor/app/channels/[slug]/xSearchActions.ts @@ -0,0 +1,64 @@ +"use server"; + +// AN X SEARCH CHANNEL'S LEADS (release 38 lane S): "Archive this account" — +// a `<handle>-x` channel on NO site through the New channel form's own path +// (createChannelFromForm), its first post fetch started — and "Never archive" +// (the handle into the search channel's `xSearch.exclude`, hidden from the +// view) with its undo. The controllers' refusals, in their sentences +// (common/controller/xSearchLeads.ts). No model, no request but the new +// channel's fetch, which runs on X's queue like any other. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + planArchiveXLead, + readXSearchLeads, + setXSearchLeadHidden, + type XSearchLeadsView, +} from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { applyChannelFormPatch } from "../components/channelConfigToForm"; +import { createChannelFromForm } from "../actions"; + +export type XLeadActionResult = + | { ok: true; slug?: string; jobIds?: string[]; exclude?: string[]; changed?: boolean; dryRun?: boolean; fields?: Record<string, string> } + | { ok: false; error: string }; + +export async function readXSearchLeadsAction( + slug: string, + limit?: number, +): Promise<XSearchLeadsView | { ok: false; error: string }> { + return readXSearchLeads(getPaths(), slug, limit !== undefined ? { limit } : {}); +} + +// Archive this account: plan (refused when the account is archived already +// or the slug is taken), then create through the form's path — on no site, +// "Fetch posts now" ticked. `dryRun` answers the plan and creates nothing. +export async function archiveXSearchLeadAction( + slug: string, + handle: string, + opts: { name?: string; dryRun?: boolean; fetch?: boolean } = {}, +): Promise<XLeadActionResult> { + const plan = await planArchiveXLead(getPaths(), slug, handle, opts.name); + if (!plan.ok) return plan; + if (opts.dryRun) return { ok: true, slug: plan.slug, fields: plan.fields, dryRun: true }; + const fd = new FormData(); + applyChannelFormPatch(fd, plan.fields); + fd.set("slug", plan.slug); + if (opts.fetch !== false) fd.set("fetchPostsNow", "on"); + const created = await createChannelFromForm(fd); + if (!created.ok) return { ok: false, error: created.error }; + safeRevalidate([`/channels/${slug}`, `/channels/${created.slug}`, "/channels"]); + return { ok: true, slug: created.slug, jobIds: created.jobIds }; +} + +// Never archive (hidden: true) and its undo (hidden: false). +export async function hideXSearchLeadAction( + slug: string, + handle: string, + hidden: boolean, +): Promise<XLeadActionResult> { + const res = await setXSearchLeadHidden(getPaths(), slug, handle, hidden); + if (!res.ok) return res; + safeRevalidate([`/channels/${slug}`]); + return { ok: true, exclude: res.exclude, changed: res.changed }; +} diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -36,6 +36,8 @@ import { type Site, } from "yt-dlp-transcript-common/lib/site"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site"; +import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; import { saveSettings } from "../settings/saveSettings"; import { LANES, @@ -138,6 +140,22 @@ export async function probeChannelUrlAction( const platformDetected = detectPlatform(trimmed); const queueKey = queueKeyForUrl(trimmed); + // An X search page (release 38): nothing to probe — the query is the + // channel. No request; a name from the query. + const searchQuery = xSearchQueryOfUrl(trimmed); + if (searchQuery !== null) { + const query = xSearchFromUrl(trimmed)?.query || searchQuery; + return { + ok: true, + name: `X search: ${query.length > 60 ? `${query.slice(0, 59)}…` : query}`, + platformDetected: "twitter", + queueKey, + queueKnown: true, + sourceKind: "social", + postFetcher: "x-gallery-dl", + }; + } + // Social accounts never go through yt-dlp: it cannot enumerate a timeline on // either platform (no twitter:user extractor exists). Route them to the // fetcher's own probe instead — for Bluesky that is a free, instant @@ -240,6 +258,11 @@ export async function createChannelFromForm( const requests = parseSiteMembershipsField( formData.get("siteMembershipsJson"), ); + // An X search channel is never put on a site (release 38): refused before + // the channel exists, so nothing is half-made. + if (config.xSearch && requests && requests.length > 0) { + return fail(X_SEARCH_NOT_ON_A_SITE(slug)); + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } @@ -340,6 +363,9 @@ export async function updateChannelAction( const requests = parseSiteMembershipsField( formData.get("siteMembershipsJson"), ); + if (parsed.config.xSearch && requests && requests.length > 0) { + return { error: X_SEARCH_NOT_ON_A_SITE(slug), values }; + } if (requests) { siteWrites = planSiteMembershipWrites(paths, slug, requests); } diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -38,6 +38,8 @@ import { handleFromAccountUrl } from "yt-dlp-transcript-common/social/fetchers"; import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; import { waybackTargetFromUrl, waybackTargetHost } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { WaybackTargetsField } from "./WaybackTargetsField"; +import { XSearchFields } from "./XSearchFields"; +import { isXSearchUrl, xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; import { probeChannelUrlAction } from "../actions"; import { Field, @@ -92,6 +94,12 @@ function shortSlugBase(title: string, max = 48): string { function slugCandidateFromUrl(url: string): string { const trimmed = url.trim(); if (!trimmed) return ""; + // An X search page: its query, not the word "search". + const searched = xSearchFromUrl(trimmed)?.query; + if (searched) { + const base = shortSlugBase(slugify(searched), 40); + return base ? `${base}-x-search` : ""; + } try { const u = new URL(trimmed); const segs = u.pathname @@ -194,7 +202,7 @@ export function ChannelForm({ c?.handling === "transcribe" ? "transcribe" : "youtube", ); const [handlingTouched, setHandlingTouched] = useState(false); - const [platform, setPlatform] = useState<string>(c?.platform ?? ""); + const [platform, setPlatform] = useState<string>(c?.xSearch ? "x-search" : (c?.platform ?? "")); const [platformTouched, setPlatformTouched] = useState(false); // Social sources are ingested into the posts corpus, not the video pipeline, // so every video-only control below is hidden for them. In edit mode this is @@ -205,7 +213,12 @@ export function ChannelForm({ const editSourceKind = c?.sourceKind ?? "video"; const isSocial = isEdit ? editSourceKind === "social" - : isSocialPlatform(platform as Platform) || isSocialPlatform(detectPlatform(url)) || isWaybackPagesUrl(url); + : isSocialPlatform(platform as Platform) || + isSocialPlatform(detectPlatform(url)) || + isWaybackPagesUrl(url) || + platform === "x-search"; + // An X search channel (release 38): a query across accounts, never on a site. + const isXSearch = isEdit ? Boolean(c?.xSearch) : platform === "x-search"; // A Wayback pages channel (release 37): captures of pages, no fetcher; its // scope is its targets. const isWaybackPages = isEdit ? c?.platform === "webpage" : platform === "webpage"; @@ -224,7 +237,9 @@ export function ChannelForm({ // NO network call. Only fills untouched fields, so a hand-set value sticks. useEffect(() => { if (isEdit) return; - const detected = detectPlatform(url) ?? (isWaybackPagesUrl(url) ? "webpage" : null); + const detected = isXSearchUrl(url) + ? "x-search" + : (detectPlatform(url) ?? (isWaybackPagesUrl(url) ? "webpage" : null)); if (!platformTouched) setPlatform(detected ?? ""); if (!handlingTouched && url.trim()) { setHandling(detected === "youtube" ? "youtube" : "transcribe"); @@ -239,7 +254,7 @@ export function ChannelForm({ if (!handleTouched) { setSocialHandle(handleFromAccountUrl(url) ?? ""); } - if (detected === "twitter") setPostFetcher("x-gallery-dl"); + if (detected === "twitter" || detected === "x-search") setPostFetcher("x-gallery-dl"); else if (detected === "bluesky") setPostFetcher("bluesky-atproto"); // A forum thread URL (…/threads/<title>.<id>/): the thread walker. else if (detected === "xenforo") setPostFetcher("xenforo-thread"); @@ -269,7 +284,7 @@ export function ChannelForm({ setName(res.name); if (!slugTouched) setSlug(slugify(res.name)); } - if (!platformTouched) setPlatform(res.platformDetected ?? ""); + if (!platformTouched) setPlatform(isXSearchUrl(url) ? "x-search" : (res.platformDetected ?? "")); // A social URL resolves through the fetcher's own probe, which also // reports which fetcher claimed it and the canonical handle. if (res.postFetcher) setPostFetcher(res.postFetcher); @@ -343,11 +358,17 @@ export function ChannelForm({ )} </Section> <Section title="Sites"> + {isXSearch ? ( + <span data-x-search-no-site="" className="text-xs text-muted-foreground"> + An X search channel is never put on a site. + </span> + ) : ( <SiteMembershipsSection sites={sites} initialMemberships={initialMemberships} activeSiteId={activeSiteId} /> + )} </Section> <Section title="Source"> {isEdit ? ( @@ -386,7 +407,7 @@ export function ChannelForm({ <SeededSelect state={state} name="platform" - initial={c?.platform ?? ""} + initial={c?.xSearch ? "x-search" : (c?.platform ?? "")} className="rounded border border-border bg-card px-2 py-1 text-sm" > <option value="">Auto (detect from URL)</option> @@ -398,6 +419,7 @@ export function ChannelForm({ <option value="archiveorg">archive.org</option> <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> + <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Wayback pages (captures of pages)</option> @@ -521,6 +543,7 @@ export function ChannelForm({ <option value="archiveorg">archive.org</option> <option value="bitchute">BitChute</option> <option value="twitter">X / Twitter (posts)</option> + <option value="x-search">X search (posts from any account)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> <option value="webpage">Wayback pages (captures of pages)</option> @@ -613,7 +636,10 @@ export function ChannelForm({ /> </> )} - {isSocial && !isWaybackPages && ( + {isSocial && isXSearch && ( + <XSearchFields {...(isEdit ? (c?.xSearch ? { initial: c.xSearch } : {}) : { derivedFrom: url })} /> + )} + {isSocial && !isWaybackPages && !isXSearch && ( <> {/* A social source is ingested into the posts corpus, so it carries its fetcher + handle instead of any of the video controls. */} diff --git a/editor/app/channels/components/XSearchFields.tsx b/editor/app/channels/components/XSearchFields.tsx @@ -0,0 +1,110 @@ +"use client"; + +// An X search channel's fields on the channel form (release 38): the query as +// X's search box takes it, the days walked between, the window size and a +// language. Posted as xSearch* fields; parseChannelForm refuses what the +// channel cannot hold, with a sentence. "Never archive"'s hidden authors ride +// along unchanged in a hidden field (they are edited on the channel page). + +import { useState } from "react"; +import { xSearchFromUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; +import type { XSearchConfig } from "yt-dlp-transcript-common/lib/xSearch/config"; + +export function XSearchFields({ + initial, + derivedFrom, +}: { + // Edit: the stored search. Create: none — the query comes from the URL. + initial?: XSearchConfig; + derivedFrom?: string; +}) { + const fromUrl = derivedFrom ? xSearchFromUrl(derivedFrom) : null; + const seed = initial ?? fromUrl ?? undefined; + const [query, setQuery] = useState(seed?.query ?? ""); + const [touched, setTouched] = useState(false); + // Create mode follows the URL until the query is typed by hand. + const shownQuery = !initial && !touched && fromUrl ? fromUrl.query : query; + const sinceSeed = initial?.since ?? fromUrl?.since ?? ""; + const untilSeed = initial?.until ?? fromUrl?.until ?? ""; + return ( + <fieldset data-x-search-fields="" className="flex flex-col gap-3 rounded-md border border-border px-3 py-2"> + <legend className="px-1 text-xs font-medium uppercase tracking-wide text-muted-foreground"> + X search + </legend> + <input type="hidden" name="sourceKind" value="social" /> + <input type="hidden" name="postFetcher" value="x-gallery-dl" /> + {initial?.exclude?.length ? ( + <input type="hidden" name="xSearchExclude" value={JSON.stringify(initial.exclude)} /> + ) : null} + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Query</span> + <input + type="text" + name="xSearchQuery" + value={shownQuery} + onChange={(e) => { + setQuery(e.target.value); + setTouched(true); + }} + aria-label="x search query" + placeholder={'"exact phrase" OR word -noise lang:en'} + className="rounded border border-border bg-card px-2 py-1 font-mono text-sm" + /> + <span className="text-xs text-muted-foreground"> + As typed in X&apos;s search box: OR, &quot;quotes&quot;, -term, from:, to:, @name, url:, filter: and + lang: all work. Leave since: and until: out — the dates below set the search windows. + </span> + </label> + <div className="flex flex-wrap gap-3"> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Since</span> + <input + type="date" + name="xSearchSince" + defaultValue={sinceSeed} + aria-label="x search since" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Until</span> + <input + type="date" + name="xSearchUntil" + defaultValue={untilSeed} + aria-label="x search until" + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Window (months)</span> + <input + type="number" + name="xSearchWindowMonths" + min={1} + max={12} + defaultValue={initial?.windowMonths ?? ""} + placeholder="3" + aria-label="x search window months" + className="w-24 rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Language</span> + <input + type="text" + name="xSearchLang" + defaultValue={initial?.lang ?? ""} + placeholder="any" + aria-label="x search language" + className="w-24 rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + </div> + <span className="text-xs text-muted-foreground"> + A fetch searches back from Until (blank: today) to Since (blank: until a year of windows finds nothing), + newest first, a window at a time; later fetches search the new days. Needs an X login. Never on a site. + </span> + </fieldset> + ); +} diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -64,6 +64,14 @@ export const CHANNEL_FORM_VALUES = [ // A Wayback pages channel's targets (release 37): a JSON array, or (in a // patch) the array itself. "waybackTargets", + // An X search channel's query and dates (release 38); `xSearchExclude` is a + // JSON array of handles (or, in a patch, the array itself). + "xSearchQuery", + "xSearchSince", + "xSearchUntil", + "xSearchWindowMonths", + "xSearchLang", + "xSearchExclude", ] as const; export type ChannelFormFlag = (typeof CHANNEL_FORM_FLAGS)[number]; @@ -131,6 +139,12 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "mirrorOf", config.mirror?.of.join(", ")); if (config.wayback?.targets.length) fd.set("waybackTargets", JSON.stringify(config.wayback.targets)); if (config.wayback?.auto) fd.set("waybackAuto", "on"); + put(fd, "xSearchQuery", config.xSearch?.query); + put(fd, "xSearchSince", config.xSearch?.since); + put(fd, "xSearchUntil", config.xSearch?.until); + putNum(fd, "xSearchWindowMonths", config.xSearch?.windowMonths); + put(fd, "xSearchLang", config.xSearch?.lang); + if (config.xSearch?.exclude?.length) fd.set("xSearchExclude", JSON.stringify(config.xSearch.exclude)); // Ticked when the check is on: said so, or the platform's default (an // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch // that does not name it keeps what the channel has. @@ -176,7 +190,7 @@ export function applyChannelFormPatch( else fd.delete(key); continue; } - if (key === "waybackTargets" && Array.isArray(value)) { + if ((key === "waybackTargets" || key === "xSearchExclude") && Array.isArray(value)) { if (value.length > 0) fd.set(key, JSON.stringify(value)); else fd.delete(key); continue; @@ -212,7 +226,7 @@ export function validateChannelFormPatch(patch: ChannelConfigPatch): void { `"${key}" is not a channel config field — accepted: ${CHANNEL_FORM_FIELD_NAMES.join(", ")}`, ); } - if (key === "waybackTargets" && Array.isArray(value)) continue; + if ((key === "waybackTargets" || key === "xSearchExclude") && Array.isArray(value)) continue; if (key === "ytdlpExtraArgs" && Array.isArray(value)) { if (value.some((v) => typeof v !== "string")) { throw new Error(`"${key}" must be an array of strings`); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -229,3 +229,78 @@ test("a form save keeps wayback.auto and the targets' filters; the checkbox and applyChannelFormPatch(fd, { waybackAuto: true }); assert.equal(parseChannelForm(fd).config.wayback?.auto, true); }); + +// Release 38 lane S: an X SEARCH channel — a pasted x.com/search URL (its +// dates lifted into the channel's), or the platform choice "X search" with +// the query fields. platform twitter, sourceKind social, gallery-dl, the URL +// rebuilt from the query, no handle; the walk's own operators refused; the +// ops patch round-trips every field, the hidden authors included. +test("an X search channel from a pasted search URL: the query, its dates lifted out, the URL rebuilt", () => { + const { config } = parseChannelForm( + form({ + handling: "transcribe", + url: "https://x.com/search?q=%22zephyr%20archive%22%20OR%20zephyrs%20since%3A2025-01-01&src=typed_query", + }), + ); + assert.equal(config.platform, "twitter"); + assert.equal(config.sourceKind, "social"); + assert.equal(config.postFetcher, "x-gallery-dl"); + assert.equal(config.socialHandle, undefined); + assert.deepEqual(config.xSearch, { query: '"zephyr archive" OR zephyrs', since: "2025-01-01" }); + assert.equal(config.url, "https://x.com/search?q=%22zephyr%20archive%22%20OR%20zephyrs&f=live"); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("xSearch")); +}); + +test("the X search choice with its fields; refusals in sentences", () => { + const { config } = parseChannelForm( + form({ + handling: "transcribe", + platform: "x-search", + xSearchQuery: "zephyr -from:spam_bot", + xSearchSince: "2024-01-01", + xSearchUntil: "2025-01-01", + xSearchWindowMonths: "1", + xSearchLang: "EN", + }), + ); + assert.deepEqual(config.xSearch, { + query: "zephyr -from:spam_bot", + since: "2024-01-01", + until: "2025-01-01", + windowMonths: 1, + lang: "en", + }); + assert.equal(config.platform, "twitter"); + const refused = (fields: Record<string, string>) => () => + parseChannelForm(form({ handling: "transcribe", platform: "x-search", ...fields })); + assert.throws(refused({}), /needs a query/); + assert.throws(refused({ xSearchQuery: "zephyr since:2024-01-01" }), /Take since: out of the query/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchSince: "2024-02-30" }), /since date must be a day/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchSince: "2024-02-01", xSearchUntil: "2024-01-01" }), /must be after its since/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchWindowMonths: "13" }), /1–12 months/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchLang: "english!" }), /not a language code/); + assert.throws(refused({ xSearchQuery: "zephyr", xSearchExclude: "[\"bad handle\"]" }), /hidden authors/); + // An ordinary X account URL is not a search. + const account = parseChannelForm(form({ handling: "transcribe", url: "https://x.com/example_user" })).config; + assert.equal(account.xSearch, undefined); + assert.equal(account.socialHandle, "example_user"); +}); + +test("the ops patch round-trips a search channel, its hidden authors kept", () => { + const stored = { + handling: "transcribe" as const, + name: "Zephyr search", + sourceKind: "social" as const, + platform: "twitter" as const, + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr", since: "2024-01-01", lang: "en", exclude: ["alice"] }, + }; + const fd = channelConfigToFormData(stored); + assert.deepEqual(parseChannelForm(fd).config.xSearch, stored.xSearch); + validateChannelFormPatch({ xSearchQuery: "zephyr OR breeze", xSearchExclude: ["alice", "bob"] }); + applyChannelFormPatch(fd, { xSearchQuery: "zephyr OR breeze", xSearchExclude: ["alice", "bob"], xSearchSince: "" }); + const next = parseChannelForm(fd).config; + assert.deepEqual(next.xSearch, { query: "zephyr OR breeze", lang: "en", exclude: ["alice", "bob"] }); + assert.equal(next.url, "https://x.com/search?q=zephyr%20OR%20breeze&f=live"); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -28,6 +28,16 @@ import { type WaybackPagesConfig, } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { isWaybackPagesUrl } from "yt-dlp-transcript-common/lib/waybackPages/urls"; +import { + coerceXSearchConfig, + isXSearchUrl, + X_SEARCH_WINDOW_MONTHS_MAX, + xLeadHandle, + xSearchFromUrl, + xSearchQueryProblem, + xSearchUrl, + type XSearchConfig, +} from "yt-dlp-transcript-common/lib/xSearch/config"; import { isCookieMode } from "yt-dlp-transcript-common/lib/cookiePolicy"; import { isDownloadFormatPreset, @@ -75,6 +85,7 @@ export const CHANNEL_FORM_FIELDS = [ "recordedDate", "mirror", "wayback", + "xSearch", ] as const satisfies ReadonlyArray<keyof ChannelConfig>; // Maps FormData -> ChannelConfig. Throws on invalid input so the server @@ -90,11 +101,21 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { const slug = String(formData.get("slug") ?? "").trim(); - const url = stringOrUndef(formData, "url"); + const typedUrl = stringOrUndef(formData, "url"); const platformRaw = String(formData.get("platform") ?? ""); - const platform: Platform | undefined = PLATFORM_VALUES.includes( - platformRaw as Platform, - ) + // AN X SEARCH CHANNEL (release 38): the platform choice "X search", or an X + // search page's URL (x.com/search?q=…) with the platform on Auto or X. Its + // URL is always the search page of its query, rebuilt here. + const xSearch = + platformRaw === X_SEARCH_PLATFORM_CHOICE || + ((platformRaw === "" || platformRaw === "twitter") && + (isXSearchUrl(typedUrl) || (platformRaw === "twitter" && stringOrUndef(formData, "xSearchQuery") !== undefined))) + ? parseXSearchFields(formData, typedUrl) + : undefined; + const url = xSearch ? xSearchUrl(xSearch.query) : typedUrl; + const platform: Platform | undefined = xSearch + ? "twitter" + : PLATFORM_VALUES.includes(platformRaw as Platform) ? (platformRaw as Platform) : (detectPlatform(url) ?? // A Wayback Machine URL of a page that is not a video (a capture, or a @@ -112,20 +133,25 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { : sourceKindRaw === "video" ? "video" : undefined; - const postFetcher = - sourceKind === "social" ? stringOrUndef(formData, "postFetcher") : undefined; + // A search channel is walked by the one fetcher that can (gallery-dl). + const postFetcher = xSearch + ? "x-gallery-dl" + : sourceKind === "social" + ? stringOrUndef(formData, "postFetcher") + : undefined; const socialHandleRaw = - sourceKind === "social" ? stringOrUndef(formData, "socialHandle") : undefined; + sourceKind === "social" && !xSearch ? stringOrUndef(formData, "socialHandle") : undefined; // A Wayback pages channel's scope: the form's target rows (one hidden JSON // field), else one target derived from the URL. const wayback = platform === "webpage" ? parseWaybackTargets(formData, url) : undefined; const socialHandle = socialHandleRaw?.replace(/^@/, "") || (wayback ? waybackTargetHost(wayback.targets[0]) : undefined) || - (sourceKind === "social" && url + (sourceKind === "social" && url && !xSearch ? (handleFromAccountUrl(url) ?? undefined) : undefined); - if (sourceKind === "social" && !socialHandle) { + // A search channel has no account: its query is what it archives. + if (sourceKind === "social" && !socialHandle && !xSearch) { throw new Error( "A social source needs an account handle (could not derive one from the URL)", ); @@ -436,10 +462,77 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { } if (mirrorOf.length > 0) config.mirror = { of: mirrorOf }; if (wayback) config.wayback = wayback; + if (xSearch) config.xSearch = xSearch; return { name, slug, config }; } +// The platform select's value for an X search channel: not a platform (the +// channel's platform is "twitter"), a kind of X channel. +export const X_SEARCH_PLATFORM_CHOICE = "x-search"; + +// An X search channel's query and dates: the form's fields (xSearchQuery, +// xSearchSince, xSearchUntil, xSearchWindowMonths, xSearchLang, and the +// hidden xSearchExclude carried from the stored config), else what a pasted +// x.com/search URL says. Refused here, with a sentence, rather than dropped +// by the reader. +function parseXSearchFields(formData: FormData, url: string | undefined): XSearchConfig { + const fromUrl = xSearchFromUrl(url); + const query = stringOrUndef(formData, "xSearchQuery") ?? fromUrl?.query ?? ""; + const problem = xSearchQueryProblem(query); + if (problem) throw new Error(problem); + const day = (key: string, fallback: string | undefined, label: string): string | undefined => { + const raw = stringOrUndef(formData, key) ?? fallback; + if (raw === undefined) return undefined; + if (!/^\d{4}-\d{2}-\d{2}$/.test(raw) || !coerceXSearchConfig({ query: "x", since: raw })?.since) { + throw new Error(`The X search's ${label} date must be a day (YYYY-MM-DD), not "${raw}"`); + } + return raw; + }; + const since = day("xSearchSince", fromUrl?.since, "since"); + const until = day("xSearchUntil", fromUrl?.until, "until"); + if (since && until && until <= since) { + throw new Error(`The X search's until date (${until}) must be after its since date (${since})`); + } + const monthsRaw = stringOrUndef(formData, "xSearchWindowMonths"); + let windowMonths: number | undefined; + if (monthsRaw !== undefined) { + const n = Number(monthsRaw); + if (!Number.isInteger(n) || n < 1 || n > X_SEARCH_WINDOW_MONTHS_MAX) { + throw new Error(`The X search's window must be 1–${X_SEARCH_WINDOW_MONTHS_MAX} months`); + } + windowMonths = n; + } + const langRaw = stringOrUndef(formData, "xSearchLang")?.toLowerCase(); + if (langRaw !== undefined && !coerceXSearchConfig({ query: "x", lang: langRaw })?.lang) { + throw new Error(`"${langRaw}" is not a language code (en, de, pt-br …)`); + } + let exclude: string[] = []; + const excludeRaw = stringOrUndef(formData, "xSearchExclude"); + if (excludeRaw !== undefined) { + let parsed: unknown; + try { + parsed = JSON.parse(excludeRaw); + } catch { + throw new Error("The X search's hidden authors must be a JSON list of handles"); + } + if (!Array.isArray(parsed) || parsed.some((h) => xLeadHandle(h) === null)) { + throw new Error("The X search's hidden authors must be a JSON list of handles"); + } + exclude = parsed.map((h) => xLeadHandle(h)!); + } + const config = coerceXSearchConfig({ + query, + ...(since ? { since } : {}), + ...(until ? { until } : {}), + ...(windowMonths ? { windowMonths } : {}), + ...(langRaw ? { lang: langRaw } : {}), + ...(exclude.length > 0 ? { exclude } : {}), + }); + if (!config) throw new Error("An X search channel needs a query (what you would type in X's search box)."); + return config; +} + // `waybackTargets` (a JSON array of {url, match, from?, to?, …}) as the // channel's Wayback scope; with none given, one target derived from the URL // (lib/waybackPages/config.ts, waybackTargetFromUrl). A row that is not a diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs @@ -40,6 +40,32 @@ if (process.env.E2E_FAKE_GALLERY_DL_AUTH_FAIL === "1") { process.exit(1); } +// AN X SEARCH (release 38): a search URL (x.com/search?q=…) answers posts by +// SEVERAL accounts, bounded by the query's since:/until: days and its max_id: +// resume point, newest first — what gallery-dl's search extractor prints for a +// query across accounts. The query's words are not matched: every window gets +// the posts dated inside it. +if (/\/search(\?|$)/.test(url)) { + const q = new URL(url).searchParams.get("q") ?? ""; + const term = (k) => (q.split(" ").find((t) => t.startsWith(k + ":")) ?? "").slice(k.length + 1) || undefined; + const since = term("since") ?? "0000-00-00"; + const until = term("until") ?? "9999-99-99"; + const maxId = term("max_id"); + const SEARCH = [ + ["1899100000000000004", "2026-06-10 10:00:00", "leadone", "Lead One", "zephyr archives, first"], + ["1899100000000000003", "2026-06-05 09:00:00", "leadtwo", "Lead Two", "the zephyr again"], + ["1899100000000000002", "2026-05-10 08:00:00", "leadone", "Lead One", "zephyr archives, second"], + ["1899100000000000001", "2026-05-01 07:00:00", "leadthree", "Lead Three", "one zephyr more"], + ]; + const hits = SEARCH.filter(([id, date]) => date.slice(0, 10) >= since && date.slice(0, 10) < until) + .filter(([id]) => !maxId || BigInt(id) <= BigInt(maxId)); + for (const [id, date, name, nick, content] of hits.slice(0, limit)) { + const author = { name, nick }; + process.stdout.write(JSON.stringify({ tweet_id: id, conversation_id: id, date, content, lang: "en", author, user: author }) + "\n"); + } + process.exit(0); +} + const AUTHOR = { name: handle, nick: "Fake Tester" }; // Ids are deliberately > 2^53 so any accidental numeric parse would corrupt diff --git a/editor/e2e/x-search.spec.ts b/editor/e2e/x-search.spec.ts @@ -0,0 +1,109 @@ +// AN X SEARCH CHANNEL end to end (release 38 lane S): a search URL pasted into +// the New channel form makes one (its dates lifted into the form, the Sites +// section replaced by "never on a site"); its first fetch walks the search +// through the fake gallery-dl's search mode, which answers posts by several +// accounts; the channel page's Leads ranks them, Never archive hides one and +// Restore brings it back, and Archive this account creates `<handle>-x` on no +// site and fetches it. +// +// X is NEVER contacted: e2e/fixtures/bin/fake-gallery-dl.mjs answers every +// read. The login the search needs is a cookies-from-browser spec the fake +// ignores. + +import { test, expect } from "@playwright/test"; +import { readFile } from "node:fs/promises"; +import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings, writeSite } from "./helpers"; + +type Config = { + platform?: string; + sourceKind?: string; + postFetcher?: string; + socialHandle?: string; + url?: string; + xSearch?: { query: string; since?: string; until?: string; exclude?: string[] }; +}; + +const SEARCH_URL = + "https://x.com/search?q=zephyr%20since%3A2026-04-01%20until%3A2026-07-01&src=typed_query"; + +const archiveLines = async (slug: string): Promise<number> => { + const file = `${testPaths().transcriptsDir}/channels/${slug}/posts-archive`; + return (await pathExists(file)) ? (await readFile(resolvePath(file), "utf8")).split("\n").filter(Boolean).length : 0; +}; + +test("an X search channel: the form, the walk, the leads, Never archive and Archive this account", async ({ page }) => { + await resetData("empty"); + await writeSettings({ cookiesFromBrowser: "firefox" }); + await writeSite("demo-site", { siteTitle: "Demo" }); + await generateReport(page, "new"); + await page.goto("/channels/new"); + + await page.locator('input[name="url"]').fill(SEARCH_URL); + await expect(page.locator('select[name="platform"]')).toHaveValue("x-search"); + await expect(page.getByLabel("x search query")).toHaveValue("zephyr"); + await expect(page.getByLabel("x search since")).toHaveValue("2026-04-01"); + await expect(page.getByLabel("x search until")).toHaveValue("2026-07-01"); + await expect(page.locator("[data-x-search-no-site]")).toBeVisible(); + await expect(page.locator('input[name="socialHandle"]')).toHaveCount(0); + await expect(page.locator('select[name="audioFormat"]')).toHaveCount(0); + + await page.locator('input[name="name"]').fill("Zephyr search"); + await page.locator('input[name="slug"]').fill("zephyr-search"); + // "Fetch posts now" is on by default: the create starts the first walk. + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + + const configPath = `${testPaths().transcriptsDir}/channels/zephyr-search/config.json`; + await expect + .poll(async () => ((await pathExists(configPath)) ? await readJson<Config>(configPath) : null), { timeout: 15_000 }) + .toMatchObject({ + platform: "twitter", + sourceKind: "social", + postFetcher: "x-gallery-dl", + url: "https://x.com/search?q=zephyr&f=live", + xSearch: { query: "zephyr", since: "2026-04-01", until: "2026-07-01" }, + }); + expect((await readJson<Config>(configPath)).socialHandle).toBeUndefined(); + // Four matching posts by three accounts. + await expect.poll(() => archiveLines("zephyr-search"), { timeout: 30_000 }).toBe(4); + const site = await readJson<{ channels: { slug: string }[] }>(`${testPaths().transcriptsDir}/sites/demo-site/site.json`); + expect(site.channels).toEqual([]); + + await generateReport(page, "zephyr-search"); + await page.goto("/channels/zephyr-search"); + await expect(page.getByLabel("x search query")).toHaveText("zephyr"); + await expect(page.getByRole("button", { name: "fetch older posts" })).toHaveCount(0); + const leads = page.locator("[data-x-search-leads]"); + await expect(leads.getByLabel("leads summary")).toHaveText(/3 accounts across 4 matching posts/); + // Most matches first, then the most recent. + await expect(leads.locator("tr[data-x-lead]")).toHaveCount(3); + const rows = leads.locator("tr[data-x-lead]"); + await expect(rows.nth(0)).toHaveAttribute("data-x-lead", "leadone"); + await expect(rows.nth(1)).toHaveAttribute("data-x-lead", "leadtwo"); + await expect(rows.nth(2)).toHaveAttribute("data-x-lead", "leadthree"); + await expect(leads.getByLabel("matches for leadone")).toHaveText("2"); + + // Never archive: hidden here, kept in the channel's xSearch.exclude. + await leads.getByRole("button", { name: "never archive leadthree", exact: true }).click(); + await expect(leads.locator('tr[data-x-lead="leadthree"]')).toHaveCount(0); + await expect(leads.locator("[data-x-search-hidden] summary")).toHaveText("Never archive (1)"); + expect((await readJson<Config>(configPath)).xSearch?.exclude).toEqual(["leadthree"]); + await leads.locator("[data-x-search-hidden] summary").click(); + await leads.getByRole("button", { name: "restore leadthree" }).click(); + await expect(leads.locator('tr[data-x-lead="leadthree"]')).toHaveCount(1); + await expect.poll(async () => (await readJson<Config>(configPath)).xSearch?.exclude).toBeUndefined(); + + // Archive this account: leadone-x, an X channel on no site, its first fetch started. + await leads.getByRole("button", { name: "archive leadone", exact: true }).click(); + await expect(leads.getByRole("status")).toHaveText(/Created leadone-x on no site/); + const leadConfig = `${testPaths().transcriptsDir}/channels/leadone-x/config.json`; + await expect + .poll(async () => ((await pathExists(leadConfig)) ? await readJson<Config>(leadConfig) : null), { timeout: 15_000 }) + .toMatchObject({ platform: "twitter", sourceKind: "social", socialHandle: "leadone", url: "https://x.com/leadone" }); + await expect.poll(() => archiveLines("leadone-x"), { timeout: 30_000 }).toBe(3); + const after = await readJson<{ channels: { slug: string }[] }>(`${testPaths().transcriptsDir}/sites/demo-site/site.json`); + expect(after.channels).toEqual([]); + // The lead now names the channel that archives it. + await page.reload(); + await expect(page.locator('tr[data-x-lead="leadone"]')).toContainText("Archived as leadone-x"); + await expect(page.getByRole("button", { name: "archive leadone", exact: true })).toHaveCount(0); +}); diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts @@ -49,6 +49,7 @@ const EXPECTED_TOOLS = [ "enqueue", "channel_coverage", "notes", + "x_search_leads", "generation_policy", "generate", "list_sources", diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -92,6 +92,7 @@ import { notesTool, type ToolAnswer, } from "./archivalTools"; +import { X_SEARCH_TOOLS, xSearchLeadsTool } from "./xSearchLeads"; import { GENERATION_TOOLS, generateTool, @@ -938,6 +939,8 @@ export const TOOLS: Tool[] = [ }, // Archival writes through the editor (release 19 A9): archivalTools.ts. ...(ARCHIVAL_TOOLS as unknown as Tool[]), + // An X search channel's leads, through the editor (release 38 lane S). + ...(X_SEARCH_TOOLS as unknown as Tool[]), // The Claude Code balance (release 27 S9): generation.ts. ...(GENERATION_TOOLS as unknown as Tool[]), { @@ -1335,6 +1338,8 @@ export function createServer( return fromAnswer(await enqueue(args, fetchClipDeps)); case "channel_coverage": return fromAnswer(await channelCoverageTool(args, fetchClipDeps)); + case "x_search_leads": + return fromAnswer(await xSearchLeadsTool(args, fetchClipDeps)); case "notes": return fromAnswer(await notesTool(args, fetchClipDeps)); case "generation_policy": diff --git a/mcp/src/xSearchLeads.test.ts b/mcp/src/xSearchLeads.test.ts @@ -0,0 +1,78 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; + +// ─── x_search_leads (release 38 lane S), through tools/call ─── +// +// One GET on the fake editor (/api/ops/channel/<slug>?leads=1); what is pinned +// is the request sent and the words the agent reads. + +const EDITOR = "http://editor.test"; + +test("x_search_leads: the leads read through the editor, ranked as it answers them", async () => { + const { deps, sent } = fakeEditor(() => ({ + status: 200, + body: { + ok: true, + slug: "zephyr-search", + leads: { + query: "zephyr", + search: "zephyr · since 2025-01-01", + walk: "searched 2025-01-01 – 2026-10-21", + posts: 4, + authors: 3, + more: 1, + hidden: [{ handle: "spam_bot", count: 9 }], + leads: [ + { + handle: "alice", + name: "Alice", + count: 2, + reposts: 1, + first: "2025-02-01T00:00:00.000Z", + last: "2025-03-01T00:00:00.000Z", + sample: { url: "https://x.com/alice/status/1", text: "the zephyr archive", createdAt: "2025-03-01T00:00:00.000Z" }, + }, + { + handle: "bob", + count: 1, + reposts: 0, + first: "2025-04-01T00:00:00.000Z", + last: "2025-04-01T00:00:00.000Z", + sample: { url: "https://x.com/bob/status/2", text: "zephyr", createdAt: "2025-04-01T00:00:00.000Z" }, + archivedAs: ["bob-x"], + }, + ], + }, + }, + }), { ARCHILYZER_EDITOR_URL: EDITOR, WORKER_TOKEN: "t" }); + const client = await connectWith(deps); + const res = await client.callTool({ name: "x_search_leads", arguments: { channel: "zephyr-search", limit: 2 } }); + const url = new URL(sent[0].url); + assert.equal(url.pathname, "/api/ops/channel/zephyr-search"); + assert.equal(url.searchParams.get("leads"), "1"); + assert.equal(url.searchParams.get("limit"), "2"); + const t = textOf(res); + assert.match(t, /^X search zephyr-search: zephyr · since 2025-01-01/); + assert.match(t, /4 matching posts from 3 accounts/); + assert.match(t, /1\. @alice \(Alice\) — 2 matches \(1 reposts\), 2025-02-01 – 2025-03-01/); + assert.match(t, /2\. @bob — 1 match, 2025-04-01 – 2025-04-01 · archived as bob-x/); + assert.match(t, /… 1 more accounts/); + assert.match(t, /Never archive \(hidden\): @spam_bot/); +}); + +test("x_search_leads: refusals — no channel, a bad limit, the editor's own sentence", async () => { + const { deps } = fakeEditor(() => ({ status: 400, body: { ok: false, error: "demo is not an X search channel (its config has no xSearch query)." } }), { + ARCHILYZER_EDITOR_URL: EDITOR, + WORKER_TOKEN: "t", + }); + const client = await connectWith(deps); + const none = await client.callTool({ name: "x_search_leads", arguments: { channel: "" } }); + assert.ok(isError(none)); + assert.match(textOf(none), /channel is required/); + const bad = await client.callTool({ name: "x_search_leads", arguments: { channel: "demo", limit: 0 } }); + assert.match(textOf(bad), /limit is a whole number, 1–500/); + const refused = await client.callTool({ name: "x_search_leads", arguments: { channel: "demo" } }); + assert.ok(isError(refused)); + assert.match(textOf(refused), /the editor refused \(HTTP 400\): demo is not an X search channel/); +}); diff --git a/mcp/src/xSearchLeads.ts b/mcp/src/xSearchLeads.ts @@ -0,0 +1,100 @@ +import { describeEditorFailure, editorGet, type EditorDeps } from "./editorOps"; +import type { ToolAnswer } from "./archivalTools"; + +// ─── x_search_leads (release 38 lane S) ─── +// +// An X SEARCH channel's leads, read through the local editor +// (GET /api/ops/channel/<slug>?leads=1&limit=N): the accounts the channel's +// matching posts came from, most matches first, with each account's first and +// last matching day, a sample post, and whether an X channel archives it +// already. Read only: acting on a lead (archive the account on no site, never +// archive it) is the operator's — the channel page's Leads, or +// `pnpm ops x-search-lead`. An X search channel is never on a site, so only +// the editor can answer. + +const SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/i; +export const X_SEARCH_LEADS_MAX = 500; + +type Lead = { + handle: string; + name?: string; + count: number; + reposts: number; + first: string; + last: string; + sample: { url: string; text: string; createdAt: string }; + archivedAs?: string[]; +}; + +type LeadsBody = { + leads?: { + query?: string; + search?: string; + walk?: string; + leads?: Lead[]; + hidden?: Array<{ handle: string; count: number }>; + posts?: number; + authors?: number; + more?: number; + }; +}; + +export function renderXSearchLeads(slug: string, body: LeadsBody): string { + const l = body.leads ?? {}; + const lines: string[] = []; + lines.push(`X search ${slug}: ${l.search ?? l.query ?? "?"}`); + lines.push(`walk: ${l.walk ?? "?"} · ${l.posts ?? 0} matching posts from ${l.authors ?? 0} accounts`); + const leads = l.leads ?? []; + if (leads.length === 0) lines.push("No leads yet: the search has matched nothing (fetch it first)."); + for (const [i, lead] of leads.entries()) { + lines.push( + `${i + 1}. @${lead.handle}${lead.name ? ` (${lead.name})` : ""} — ${lead.count} match${lead.count === 1 ? "" : "es"}` + + (lead.reposts ? ` (${lead.reposts} reposts)` : "") + + `, ${lead.first.slice(0, 10)} – ${lead.last.slice(0, 10)}` + + (lead.archivedAs?.length ? ` · archived as ${lead.archivedAs.join(", ")}` : ""), + ); + lines.push(` ${lead.sample.createdAt.slice(0, 10)} ${lead.sample.url} — ${lead.sample.text}`); + } + if (l.more) lines.push(`… ${l.more} more accounts with fewer matches (raise limit).`); + if (l.hidden?.length) lines.push(`Never archive (hidden): ${l.hidden.map((h) => `@${h.handle}`).join(", ")}`); + return lines.join("\n"); +} + +export async function xSearchLeadsTool(args: Record<string, unknown>, deps: EditorDeps): Promise<ToolAnswer> { + const channel = typeof args.channel === "string" ? args.channel.trim() : ""; + if (!channel || !SLUG_RE.test(channel)) { + return { text: "x_search_leads: channel is required (the X search channel's slug)", isError: true }; + } + const q = new URLSearchParams({ leads: "1" }); + if (args.limit !== undefined) { + const n = Number(args.limit); + if (!Number.isInteger(n) || n < 1 || n > X_SEARCH_LEADS_MAX) { + return { text: `x_search_leads: limit is a whole number, 1–${X_SEARCH_LEADS_MAX}`, isError: true }; + } + q.set("limit", String(n)); + } + const a = await editorGet(deps, `/api/ops/channel/${encodeURIComponent(channel)}?${q.toString()}`); + if (a.kind !== "ok") return { text: describeEditorFailure("x_search_leads", a), isError: true }; + return { text: renderXSearchLeads(channel, a.body as LeadsBody) }; +} + +export const X_SEARCH_TOOLS = [ + { + name: "x_search_leads", + description: + "An X SEARCH channel's leads: the accounts whose posts matched its saved X query, most " + + "matches first, each with its first and last matching day, a sample post and whether an " + + "X channel archives it already. For finding which accounts keep saying something. Read " + + "only — archiving an account (always on no site) or hiding it is the operator's, on the " + + "channel page or `pnpm ops x-search-lead`. Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", + inputSchema: { + type: "object", + properties: { + channel: { type: "string", description: "The X search channel's slug (the editor's)." }, + limit: { type: "number", description: `Leads to list (default 100, at most ${X_SEARCH_LEADS_MAX}).` }, + }, + required: ["channel"], + additionalProperties: false, + }, + }, +] as const; diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11187,6 +11187,67 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri then parsed; renderers found by key anywhere (`channelAboutFullMetadataRenderer` | `aboutChannelViewModel`, `c4TabbedHeaderRenderer` | `pageHeaderViewModel`, `channelMetadataRenderer`). +## Release 38 lane S: X search channels (verified 2026-10-20, branch `r38/x-search`) + +- **An X search channel is `config.xSearch` on an X posts channel** (`sourceKind: "social"`, `platform: "twitter"`, + `postFetcher: "x-gallery-dl"`, `url` = `xSearchUrl(query)` — `https://x.com/search?q=<query, percent-encoded + whole>&f=live`, rebuilt from the query by the form parser on every save; no `socialHandle`). + `{query, since?, until?, windowMonths?, lang?, exclude?}` — `common/lib/xSearch/config.ts`, a client-safe leaf; + `isXSearchChannel(config)` is the one test. The New channel form's platform choice `"x-search"` is NOT a platform: + `parseChannelForm` maps it (or an `x.com|twitter.com/search?q=` URL with the platform on Auto or X) to + `platform: "twitter"` + `xSearch`. Form fields: `xSearchQuery`, `xSearchSince`, `xSearchUntil`, + `xSearchWindowMonths`, `xSearchLang`, and the hidden `xSearchExclude` (JSON) so a Configure save keeps the + hidden authors. +- **The query is refused, never repaired, when it carries `since:`, `until:`, `max_id:`, `since_id:`, + `until_id:`, `since_time:` or `until_time:`** (outside a quoted phrase, any case, `-` or `(` prefixed), is empty, + two lines, over 500 characters, or leaves a quote open (`xSearchQueryProblem`). A pasted URL's single + `since:<day>`/`until:<day>` are LIFTED into the channel's dates (`xSearchFromUrl`); a typed query's are refused. + Every other operator passes through as typed. `lang` adds `lang:<code>` unless the query names a `lang:` itself. +- **The walk is the older walk's machinery with a different query.** `xGalleryDlFetcher.ts`: `fetchOlderViaSearch` + and the new `fetchSearchViaWindows` (`SocialFetcher.fetchSearch`) both run `walkSearchWindows` — the same + `GalleryDlStream`, 45–120 s between windows, `sleep-request=4.0-10.0`, `ratelimit=wait` (a 429 is waited out by + gallery-dl in-process, as for the older walk), the 3-hour `BACKFILL_BUDGET_MS`, mid-window checkpoints with the + oldest id read as `max_id:`, and the same login (`galleryDlLoginFor`; a guest run refused before spawning, + `needsCookies`). `buildGalleryDlQueryArgs({query})` is the argv for any window query; `buildGalleryDlSearchArgs` + (from:<handle>) now calls it. A search window's query is `xSearchWindowQuery`: `<query> [lang:<l>] + since:<d> until:<d> [max_id:<id>]` — no `from:`, no `include:nativeretweets`. With a `floor` (the channel's + `since`) every window down to it is searched (`maxEmptyWindows: Infinity`); with none the walk ends after + `OLDER_MAX_EMPTY_WINDOWS` (4) empty windows in a row — never the 2-window "nothing archived" shortcut. +- **State: `posts-state.json` `search`** (`XSearchWalkState`, `lib/posts-server.ts`): `{queryKey, walk?: {top, + floor?, since, until, emptyWindows, maxId?}, coveredSince?, coveredUntil?, completeReason?, completedAt?, + lastRunAt?, lastWritten?, lastError?}`. `queryKey` = query + lang (`xSearchQueryKey`); a different key starts + afresh (posts kept, deduped). Each fetch walks ONE stretch (`lib/xSearch/walk.ts` `planXSearchWalk`): a walk in + progress first; else the first walk from `until` (or tomorrow, UTC) down to `since`; else the new days, from + `until`/tomorrow down to `coveredUntil − 1 day` (a day of overlap); else the earlier days when `since` < + `coveredSince`; else nothing ("already searched …"). `full` forgets the state ("Search again from the top"). + `older` is refused (`X_SEARCH_OLDER_REFUSAL`) in the action and the controller. The fetch stamps `lastSyncedAt` + (it is the channel's sync; the scheduler paces it as any posts channel). Controller: + `common/controller/fetchXSearch.ts`, called from `fetchPosts` before the handle is resolved. +- **Cross-channel dedupe is per channel — as for every posts channel.** `writePosts` dedupes by id against the + channel's own `posts-archive`; the LMDB `posts` sub-DB is keyed `[createdAt, channelSlug, id]`. The same status id + in an account channel and a search channel is two records, one per channel; nothing writes into another + channel's archive. The leads view instead marks an account an X channel archives (`archivedAs`). +- **Leads** (`lib/xSearch/leads.ts` `rankXSearchLeads`, pure; `controller/xSearchLeads.ts` reads): one row per + lower-cased author — count (reposts among them), first/last `createdAt`, a sample (the account's own newest post, + else its newest repost, 280 chars), `archivedAs` (X account channels — not search channels — whose + `socialHandle` / URL handle matches). Ranked count desc, last desc, handle asc; `exclude` handles go to `hidden` + (an excluded handle with no posts is listed with count 0); default limit 100, `more` = the rest. + **Archive this account** = `planArchiveXLead` (refuses an archived account and a taken slug) → the New channel + form's fields (`<Name|handle> (X)`, `https://x.com/<handle>`, twitter, social, x-gallery-dl, socialHandle) → + `createChannelFromForm` with slug `<handle lower-case>-x` (`x<handle>-x` when the handle starts with `_`), no + sites, `fetchPostsNow`. **Never archive / Restore** = `setXSearchLeadHidden`, through `patchChannelConfig`'s new + `derive` option (a patch computed from the config re-read inside the lock). +- **Never on a site, at three doors:** `createChannelFromForm` and `updateChannelAction` refuse a search channel + with site memberships before anything is written; `writeSite` (`lib/site.ts`, every site writer — the site form, + `patchSite`/site-config, memberships, rename) refuses a site whose `channels` or `citedChannels` name one + (`xSearchChannelOnSite`, one config read per member; `X_SEARCH_NOT_ON_A_SITE`). `social.x.visibility` applies + unchanged (`isXPostsChannel` — platform twitter). +- **Ops / CLI / MCP:** `GET /api/ops/channel/<slug>?leads=1[&limit=N]` adds `leads` (`pnpm ops get channel <slug> + --leads [--limit N]`; `--limit` without `--leads` is refused); `POST /api/ops/x-search-lead {slug, handle, + action: "archive"|"never"|"restore", name?, fetch?, dryRun?}`; MCP `x_search_leads {channel, limit?}` + (`mcp/src/xSearchLeads.ts`, read only, through the editor). The e2e fake gallery-dl answers a `/search` URL with + four posts by three accounts dated 2026-05/06, bounded by the query's since/until/max_id. + ## Release 37 lane E: liveness, Save Page Now, find-copy for pages (verified 2026-10-20, branch `r37/live`) - **A page record's availability is its ORIGINAL URL's**, never the Wayback Machine's: `checkPostAvailability` diff --git a/plans/release-38/x-search.md b/plans/release-38/x-search.md @@ -0,0 +1,124 @@ +# Release 38 lane S `r38/x-search` (an X search channel: a saved query across accounts) — as shipped + +Operator, 2026-10-20: "Are you able to do an X search query to try to find leads from various accounts?" Plan of +record: `plans/release-38/research-cases-and-assist.md` (stage 8, Leads, for X); the lane brief narrowed it to an X +search channel. No model anywhere; every step is a button, an ops action and (the read) an MCP tool. + +## What + +- **The channel kind** (`common/lib/xSearch/config.ts`, a client-safe leaf): `config.xSearch = {query, since?, + until?, windowMonths?, lang?, exclude?}` on an X posts channel (platform `twitter`, `sourceKind: "social"`, + `postFetcher: "x-gallery-dl"`, `url` the search page rebuilt from the query, no `socialHandle`). In the one set + of coercions (`lib/channelConfig.ts`, `channelConfigSchema.ts`), CHANNEL.md regenerated. Query validation passes + X's operators through and refuses an empty, two-line, over-long or open-quoted query and one carrying `since:`, + `until:`, `max_id:` or their kin (outside quotes, any case). A pasted `x.com/search?q=` URL's one `since:`/`until:` + day each are lifted into the channel's dates. +- **Creation**: the New channel form's Platform gains **X search (posts from any account)** (`"x-search"`, not a + platform — the parser maps it to `twitter` + `xSearch`); pasting a search URL selects it. `XSearchFields` (query, + since, until, window months, language; the hidden authors carried in a hidden field). The Sites section says "An + X search channel is never put on a site." instead of the membership picker. `pnpm ops create-channel` takes the + URL, or `platform: "x-search"` with the `xSearch*` fields; channel-config round-trips them. Fetch details on a + search URL answers without a request. +- **Never on a site, at three doors**: `createChannelFromForm` / `updateChannelAction` refuse memberships for a + search channel before writing anything, and `writeSite` (`lib/site.ts`, every site writer) refuses a site whose + members or cited channels include one. Its posts follow `social.x.visibility` unchanged (platform `twitter`). +- **The fetch** (`common/controller/fetchXSearch.ts`, from `fetchPosts`): one walk per run, planned by + `common/lib/xSearch/walk.ts` — a walk in progress, else the first walk (until/tomorrow → since), else the new days + (→ a day below `coveredUntil`), else the earlier days (when `since` moved back), else nothing. The walk is + gallery-dl's search, shared with the older walk: `xGalleryDlFetcher.ts` `walkSearchWindows` (the older walk's + loop, factored out unchanged) under `fetchOlderViaSearch` and the new `fetchSearchViaWindows` + (`SocialFetcher.fetchSearch`). Same windows, 45–120 s between them, 4–10 s per request, `ratelimit=wait`, the + 3-hour budget, mid-window checkpoints at `max_id:`, the same login and guest refusal. A floor walks every window + down to it; no floor ends after 4 empty windows. State: `posts-state.json` `search` (`XSearchWalkState`). `full` + restarts the walk; `older` is refused. The run stamps `lastSyncedAt`, so the scheduler paces it. +- **Leads** (`common/lib/xSearch/leads.ts`, `common/controller/xSearchLeads.ts`): accounts ranked by matching posts + (count, reposts, first/last, a sample, `archivedAs` for an account an X channel archives already), hidden ones apart, + capped (100). **Archive this account** plans `<handle>-x` (refusing an archived account or a taken slug) and creates + it through `createChannelFromForm` — no sites, Fetch posts now. **Never archive** / **Restore**: + `xSearch.exclude`, written through `patchChannelConfig`'s new `derive` option (re-read inside the lock). +- **Channel page**: the posts panel shows the query and a "Search walk" line, **Search again from the top** in place + of Re-fetch full history, no Fetch older posts; `XSearchLeadsPanel` below it (table, actions, the hidden list). +- **Ops / CLI / MCP**: `GET /api/ops/channel/<slug>?leads=1[&limit=N]` (`pnpm ops get channel <slug> --leads + [--limit N]`); `POST /api/ops/x-search-lead {slug, handle, action: archive|never|restore, name?, fetch?, + dryRun?}`; MCP `x_search_leads {channel, limit?}` (`mcp/src/xSearchLeads.ts`, read only, through the editor — the + MCP's X/post tools read published sites, and a search channel is never on one, so the tool rides the editor like + `channel_coverage`). COMMANDS.md regenerated. +- **Capture** works on a search channel's posts (the X capture opens a post by its status id; the handle fallback is + the slug). +- **Tests and fakes**: unit — `lib/xSearch/{config,walk,leads}.test.ts`, `controller/fetchXSearch.test.ts` (a fake + gallery-dl answering search URLs by several authors: windows, operator pass-through, resume, new query, new days, + refusals, per-channel dedupe), `controller/xSearchLeads.test.ts` (ranking, exclude, archive plan, the writeSite + refusal), `editor/app/channels/components/parseChannelForm.test.ts` (+3), `editor/app/api/ops/x-search-lead/ + route.test.ts`. e2e — the editor's fake gallery-dl answers a `/search` URL with four posts by three accounts; + `editor/e2e/x-search.spec.ts` drives the form, the walk, the leads, Never archive / Restore and Archive this + account. +- **Docs**: OPERATING.md "X search", CHANNEL.md, COMMANDS.md, FACTS "Release 38 lane S", CHANGELOG. + +## Commits + +| sha | what | +|---|---| +| `402dac87` | common: config.xSearch, the window walk over any query (the older walk's loop shared), the leads, writeSite's refusal, tests | +| `a0636761` | editor: the form's kind, the Leads panel, Archive this account / Never archive, ops route + channel read, CLI, MCP, e2e | +| `2bb3d741` | the site guard skips a Paths with no channel pool (a scratch test's); the CLI's --leads / x-search-lead pinned | +| `b8860428` | docs: OPERATING "X search", CHANNEL.md + COMMANDS.md regenerated, FACTS, CHANGELOG | +| `ce5d7b7f` | the e2e's archive-button locators exact | +| `ce30bc71` | this record (first version) | +| `04fdb051` | merge main (r37/forum-resume, r38/video-assist): posts-state `forum` beside `search`; the posts panel's forum Full re-walk beside Search again from the top; both spreads on the page; CHANGELOG/FACTS/ops list both sides | +| `67560eb3` | merge main (r37/cite): the channel page's Wayback rows now main's `waybackPagesRows`, the search block after it | +| `e77d27fd` | x-search-lead after main's check-post-availability / save-page-now in the action list; COMMANDS.md regenerated | +| (tip) | this record, after the merges | + +## Gates + +- tsc, the whole workspace (`pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`): clean. +- common: 4787 at main (`14947e67`; the branch-start run, under load, had 2 failures that did not recur) → 4815 + (4812 pass, 2 skipped, 1 fail — `siteSchema.test.ts`'s scratch Paths through the new writeSite guard, fixed in + `2bb3d741`, the file re-run 38/38 with `xSearchLeads.test.ts`). +28: config 9, walk 5, leads 4, fetchXSearch 6, + xSearchLeads 4. +- editor unit: 357 at main (r37's record; this branch's start run raced the first edits: 341, 4 files not loading) + → 363/363 (+6: parseChannelForm +3, x-search-lead route +3). +- test:scripts: 1316 (1312 + 4 skipped) → 1317 (1313 + 4 skipped; +1, the ops CLI's --leads / x-search-lead). +- mcp: 379 → 381/381 (+2, x_search_leads). +- docs: `docs files` and `docs cli` regenerated (CHANNEL.md, COMMANDS.md); `docs env --check`, `docs files --check`, + `docs cli --check`, `settings example --check` clean. +- editor build: the e2e's stamped `next build` of the editor, 894 s on a loaded machine, compiled clean. +- e2e (detached, through the locks): `x-search.spec.ts` + `social-channel.spec.ts` — social-channel 6/6; x-search + failed at its last step on a locator ("archive leadone" also matched "never archive leadone"; strict mode), every + earlier step green (form, walk, leads, Never archive, Restore); fixed with exact names; the re-run + `x-search.spec.ts` 1/1 (22.8 s; 33.4 s with the server, the stamped build reused). Wall times were nearly all the + session lock and the machine's heavy slot (40 and 49 minutes). + +### After merging main twice (`a9b6b6c2`/`5e62aa1b`, then `e71df65f`) + +- tsc, whole workspace: clean. +- common 4884 (4882 pass, 2 skipped, 0 fail); editor unit 368/368; test:scripts 1328 (1324 + 4 skipped; one + failure first — main's usage test pins `reextract-pages, check-post-availability, save-page-now` in order — fixed + in `e77d27fd`); mcp 384/384. +- docs files/cli regenerated; docs env/files/cli and settings example `--check` clean. +- e2e `x-search.spec.ts` + `social-channel.spec.ts`: 7/7 (2.1 min; the stamped build 92 s; wall 13 min). + +## Rulings followed + +- The brief's: an X search channel is a posts channel, on no site, private by `social.x.visibility`; the fetch is the + existing gallery-dl search path with since:/until: windows (the older walk's machinery, newest first, resumable, + same pacing and login); X's operators pass through, since:/until: refused; leads ranked with Archive (on no site, + the create-channel path) and Never archive (`xSearch.exclude`); no model; no real X traffic in any test; no live + fetch run. +- The prelude's: synthetic fixtures only; commits end with the Co-Authored-By line alone; every heavy step through + the lock; no push, no merge into main. + +## Decisions made in the lane + +The lane report lists them; the ones a later reader needs: "X search" is a Platform-select choice, not a platform; +a pasted URL's since:/until: are lifted into the dates, typed ones refused; one walk per fetch, newest stretch +first; with a since every window down to it is searched, without one 4 empty windows end the walk; a new query +starts afresh; cross-channel dedupe stays per channel (leads name the X channel that archives an account); Never +archive hides from the leads and does not rewrite the query; never on a site at create, Configure and writeSite; +`<handle>-x` (or `x<handle>-x`) on no site for Archive this account; the MCP tool is read only, through the editor. + +## Left for later + +- The first live search run (the orchestrator's): the walk has only met the fakes. +- A search channel's login is any X channel's: `social.x.cookieSource`, the channel's own cookiesFromBrowser + (Configure) over the global one; a guest run is refused before spawning. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -10,7 +10,7 @@ // // pnpm ops <action> [--json '<body>' | --file <path>] [--wait] // [--wait-timeout <seconds>] [--quiet] -// pnpm ops get channel <slug> [--counts] +// pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]] // pnpm ops get channels // pnpm ops get tags [<tagId>] // pnpm ops get job <id> [--tail [<lines>]] @@ -121,6 +121,10 @@ // pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait // pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}' // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait +// pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}' +// pnpm ops get channel demo-search --leads --limit 20 +// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}' +// pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait // pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait @@ -191,8 +195,11 @@ const MAX_PROBE_FAILURES = 10; const GETTERS = { // --counts adds the LIVE on-disk counts, which walk every video directory — // opt-in for the same reason the route makes it opt-in. - channel: (slug, { counts }) => - `/api/ops/channel/${encodeURIComponent(slug)}${counts ? "?counts=1" : ""}`, + // --leads (an X search channel, release 38) adds its leads, --limit how many. + channel: (slug, { counts, leads, jobs }) => { + const q = [counts ? "counts=1" : "", leads ? "leads=1" : "", leads && jobs?.limit ? `limit=${jobs.limit}` : ""].filter(Boolean); + return `/api/ops/channel/${encodeURIComponent(slug)}${q.length ? `?${q.join("&")}` : ""}`; + }, // Every channel, one line each: slug, name, kind, platform and the sites // that carry it ([] = private to this editor). channels: () => "/api/ops/channels", @@ -287,7 +294,7 @@ const GET_ARG_OPTIONAL = new Set([ // The flags each noun takes beyond the shared ones; any other is refused. const GET_FLAGS = { transcript: ["slug"], - channel: ["counts"], + channel: ["counts", "leads", "limit"], job: ["tail"], jobs: ["active", "failed", "kind", "slug", "limit"], }; @@ -464,6 +471,10 @@ const ACTIONS = [ // keys), the capture imported into slug, as a save-page-now job. "check-post-availability", "save-page-now", + // X SEARCH (release 38): an X search channel's lead, acted on — archive the + // account as its own X channel on no site, or never archive it (hidden), + // or restore it ({slug, handle, action, name?, fetch?, dryRun?}). + "x-search-lead", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -579,6 +590,7 @@ export function parseArgs(argv) { let wait = false; let quiet = false; let counts = false; + let leads = false; let tail = 0; const jobs = {}; // The noun-specific flags seen, checked against GET_FLAGS once the noun is @@ -615,6 +627,9 @@ export function parseArgs(argv) { } else if (arg === "--counts") { counts = true; used.add("counts"); + } else if (arg === "--leads") { + leads = true; + used.add("leads"); } else if (arg === "--active" || arg === "--failed") { jobs[arg.slice(2)] = true; used.add(arg.slice(2)); @@ -720,9 +735,12 @@ export function parseArgs(argv) { error: `get ${noun} does not take ${stray.map((f) => `--${f}`).join(", ")}`, }; } + if (noun === "channel" && used.has("limit") && !leads) { + return { error: "get channel: --limit goes with --leads" }; + } return { method: "GET", - path: GETTERS[noun](positional[2], { counts, tail, jobs }), + path: GETTERS[noun](positional[2], { counts, leads, tail, jobs }), wait: false, quiet, waitTimeout, @@ -864,7 +882,7 @@ export function usage() { return [ "Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]", " [--wait-timeout <seconds>] [--quiet]", - " pnpm ops get channel <slug> [--counts]", + " pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]]", " pnpm ops get channels", " pnpm ops get tags [<tagId>]", " pnpm ops get publish", @@ -1174,6 +1192,22 @@ export function usage() { ' derived from the name), "sites"? (absent = on no site). "fetchPlaylist",', ' "fetchPostsNow" and "prioritizeDownload" are the form\'s checkboxes, OFF', ' unless true; a job they start comes back as jobId(s), so --wait follows it.', + ' An X search page URL (x.com/search?q=…), or "platform": "x-search" with', + ' "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?,', + ' "xSearchLang"?), makes an X SEARCH channel: the matching posts from any', + " account, walked by fetch-posts in search windows; never on a site (sites", + " refused).", + "", + 'x-search-lead acts on one lead of an X search channel (the accounts its', + ' posts came from — `get channel <slug> --leads [--limit <n>]` lists them,', + ' most matches first): {"slug", "handle", "action": "archive" | "never" |', + ' "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the', + ' New channel form\'s path and starts its first post fetch ("fetch": false', + ' skips it; "name"? names it; "dryRun" answers the fields and creates', + ' nothing) -> {slug, jobIds}. Refused: not an X search channel, an account', + " an X channel archives already, a slug taken. \"never\" hides the handle", + " (the channel's xSearch.exclude), \"restore\" un-hides it -> {exclude,", + " changed}. No model, no request but the new channel's fetch.", "", 'rename-channel moves a channel to a new slug, as Danger → Rename does:', ' {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit,', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -104,6 +104,19 @@ test("get channel --counts asks for the live on-disk counts", () => { assert.equal(parseArgs(["get", "channel", "x"]).path, "/api/ops/channel/x"); }); +// Release 38 lane S: an X search channel's leads, and the action on one. +test("get channel --leads [--limit] reads an X search channel's leads; x-search-lead posts its body", () => { + assert.equal(parseArgs(["get", "channel", "s", "--leads"]).path, "/api/ops/channel/s?leads=1"); + assert.equal(parseArgs(["get", "channel", "s", "--leads", "--limit", "20"]).path, "/api/ops/channel/s?leads=1&limit=20"); + assert.equal(parseArgs(["get", "channel", "s", "--counts", "--leads"]).path, "/api/ops/channel/s?counts=1&leads=1"); + assert.match(parseArgs(["get", "channel", "s", "--limit", "20"]).error, /--limit goes with --leads/); + assert.match(parseArgs(["get", "jobs", "--leads"]).error, /get jobs does not take --leads/); + const p = parseArgs(["x-search-lead", "--json", '{"slug":"s","handle":"h","action":"never"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/x-search-lead"); + assert.deepEqual(p.body, { slug: "s", handle: "h", action: "never" }); +}); + // --- curated tags ----------------------------------------------------------- test("the tag actions are registered and post to their routes", () => {