Archilyzer · Source

archilyzer

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

commit 3071a6b51f8ef3bf5bc9115930304d214415aee9
parent 1b3a88b504b097692806cdb5a4bee282a362e97d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 10:41:22 -0500

editor, ops: x-trending slice 4 over ops -- organise-trending, publish-trending and the library's accounts, each with its pnpm ops twin

organise-trending {op: rename | move | merge} and publish-trending {dryRun
| confirm, by: "operator"} are the common bodies behind the editor's
actions; the in-flight answers come from the job registry (a merge waits
for a read or a reparse of the library; a publish for a read, a reparse or
a capture). The channel's slug for a first publish is the New channel
form's own slugify of the topic's title. `get trending <slug> --accounts`
(accounts=1) lists the library's accounts; with detail the listing says
where each topic was published. x-search-lead takes "fetch": true from a
library, where the default is to ask X nothing. COMMANDS.md regenerated.

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

Diffstat:
MCOMMANDS.md | 12++++++++++--
Aeditor/app/api/ops/organise-trending/route.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/publish-trending/route.test.ts | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/publish-trending/route.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/trending/route.ts | 39+++++++++++++++++++++++++++++++++++++--
Meditor/app/channels/[slug]/xTrendingActions.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 87++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mscripts/archilyzer-ops.test.mjs | 7+++++++
8 files changed, 530 insertions(+), 9 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -217,11 +217,13 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now): {"url", "slug"?, "dryRun"?}. With archive.org's S3 keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names) it is SPN2 ("mode": "keys"); with none configured it is the public endpoint, anonymously ("mode": "anonymous": archive.org allows 3 a minute and 200 a day). 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. One save at a time in the process, at least 60 s apart anonymous (10 s with keys); a 429/503 rests it (Retry-After, else 2 min doubling to 1 h). Refused, before any job: a key file that is there but readable by others, 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?, mode, spnJobId?, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, rateLimited?, 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` | | `save-page-now-batch` | save-page-now-batch saves a LIST of pages as ONE resumable job: {"urls": \[...\]} \| {"file": &lt;abs path: a JSON list, {urls}, or a URL a line&gt;} \| {"batch": &lt;id&gt;}, "skipArchived"? (true), "sources"? (\["wayback", "archive.today"\]), "evidence"? (abs path), "dailyCap"? (150 anonymous, at most 200; 5000 with keys), "dryRun"? -&gt; {jobId, batch}. Each URL in turn: looked up (the Wayback CDX, archive.today's timemap, each paced) and archived-already when a copy shows it (a Wayback row that recorded a 200, or an archive.today copy); else saved through Save Page Now's pacer (anonymous without keys), saved or failed with the reason; a site Save Page Now refuses as a site (x.com, 5 Nov: "limitations when it comes to archiving this site") is asked once a run, its other URLs looked up only. archive.today and Ghostarchive are looked up, never asked to save. The state is &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.json, written after every URL: the same request again, {batch}, a Retry or a restart continues from the first pending URL. The evidence (JSON + CSV: url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt) is rewritten after every URL; default &lt;transcripts&gt;/.spn-batches/&lt;batch&gt;.evidence.json. Progress (done/total, ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode, counts, run, evidence, statePath, etaSeconds, stopped?}. | `pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'`<br>`pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'`<br>`pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'` | | `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -&gt; {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` | -| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. | `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"}'` | +| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. An X TRENDING LIBRARY's accounts (get trending &lt;slug&gt; --accounts) are leads too: with "slug" a library, "archive" creates &lt;handle&gt;-x for an account that wrote a post the library holds, on no site, naming nothing of the library, and ASKS X NOTHING: there the first fetch is not started unless "fetch": true (it is its own step: fetch-posts). "never" and "restore" are a search channel's only. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'`<br>`pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}'` | | `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/&lt;number&gt;"}, as one job on X's queue (the fresh-jar rule, the X alert and X's job gap apply; ask get x-session first). The page is opened in the connected X profile's browser, every GraphQL answer the page itself fetched is saved raw with a screenshot (channels/&lt;slug&gt;/trending/reads/&lt;readId&gt;/), and the posts are parsed from the saved file and written as the library's posts. A read lists posts; it archives no media and no thread. "topic": a topic's id or name, or a new one's name (absent: the topic this page was read into before, else a new one named for it). "scrolls": 1-20 moves to the bottom of the page (default: the channel's cap, else 8); "posts": stop once 1-200 are seen (else 60); a read also stops after two scrolls with nothing new, and at once on a 429, a 403 or a login wall. A 429 leaves X alone for 15 minutes (no read is queued or started before the time its sentence names); a page that stops answering ends the read within 6 minutes. Nothing retries. "probe": true saves the capture and its summary and writes no post. "headed": true opens a window on the editor's desktop. {"slug", "reparse": "&lt;readId&gt;"} parses a saved read again OFFLINE (X is asked nothing; a read left with no record takes "url" too). No fresh jar needed. --wait prints the log's @@read-x-trending {ok, mode, read, outcome, stop, responses, operations (names and sizes, never a body), posts: {onPage, added}, topic, sentence}; a capture with no post the parser knows ends ok, "read saved, nothing recognised". Refused before a job: not a library, not a trending page URL, a cap out of range, no connected X profile, X's Connect or Refresh in flight, a stale jar. A library is made with create-channel, "platform": "x-trending" (no "url", no "sites": it is private, never on a site, in no index build; "xTrendingMaxScrolls"?, "xTrendingMaxPosts"? set its caps). | `pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait` | | `judge-trending` | judge-trending judges posts of an X trending library: {"slug", "set": \[{"id" \| "thread", "state", "note"?}, ...\], "by"?}. "id" is a post of the library; "thread" a thread's ROOT post id (get trending gives each post's thread), judging every post of it that has no judgement of its own. "state": keep, drop, later, or undecided (the judgement is removed: no entry is undecided). "note": up to 2000 characters. "by": "agent" (the default) or "operator" - the caller's word: an agent says "agent". An agent's judgement is a suggestion: an agent's write over a judgement the operator made is skipped for that id and named in skipped, and the rest is written; a post the operator judged through its thread is the operator's too. Answers {written, skipped: \[{id \| thread, reason}\], kept, archive?} - kept names the posts whose judgement BECAME keep. A keep archives them: ONE capture-posts job on X's queue (a screenshot, the context, a reply's thread shot, the media), its id in archive.jobId; "archive": false marks only. When that job is refused (a stale jar, the X alert, X cooling down) the judgements are written all the same and archive.error says why; capture-posts {slug, ids, "thread": true, "keptMedia": true} archives them later. Drop deletes nothing: the post, its capture and its media stay, and a later keep puts it back. An id the library does not hold is skipped by name, not refused. | `pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}'` | | `watch-trending` | watch-trending watches a topic of an X trending library: {"slug", "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}. While a topic is watched its trending page is read again every intervalMinutes (15-1440; default the library's, else 30) until hours from now (1-168; else 48), each tick the SAME single read-x-trending job on X's queue, started by the editor's own scan (once a minute, at most one read per scan, none while a trending read or capture of ANY library waits its turn: every library's ticks are one stream). A topic of several pages reads one page per tick, in turn. At most 4 topics of a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN, no page opened; "shots": true also screenshots every new post. "on": false stops it. A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes): the editor never refreshes the jar by itself, so a watch pauses when the jar goes stale (X's jar-age alert goes up, /review lists the paused watches) and resumes at the first scan after Refresh cookies on /cookies. It does not cover a night nobody presses Refresh in. That limit is the watch's own, whatever the login source or the setting: a jar whose age cannot be read, a limit set to 0 and an unreadable settings file all pause it. The X alert, a rate-limit cooldown and a missing profile pause it the same way. Three reads in a row that do not end "read" (a rate limit, a 403, a page that will not load) pause it until the operator switches it on again ("by": "operator"; an agent's ask is refused). A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) is recorded gone from the page at that time (get trending: gone) - never "deleted". A page X no longer has is not read again, and ends the watch when it was the topic's last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?, "hours"?, "maxTopics"?}} changes the library's defaults; {"slug", "tick": true} runs one scan now (refused on an idle boot; two asks at once are one scan). get trending shows each topic's watch and what it is doing (watch.sentence). | `pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'`<br>`pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'` | | `purge-trending` | purge-trending removes the captures of DROPPED posts of an X trending library, in two steps. {"slug", "dryRun": true, "topic"?, "ids"?} removes nothing: it counts the dropped posts with a capture (posts, ids, files, bytes) and answers "confirm", a digest of exactly those posts. {"slug", "confirm", "by": "operator", "topic"?, "ids"?} removes them: the screenshot, the record and the media under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. It is the operator's press: an agent's removal is refused (an agent may ask for the dry run), and a confirm that no longer matches (a post dropped or kept, a capture added since) is refused with nothing removed. Only posts whose judgement in force is drop BY THE OPERATOR (their own entry, or their thread's) are taken: an agent's drop is a suggestion and is never purged (agentDropped counts those left alone), nor is a post marked later, kept or undecided; an id named that is not such a post is listed in skipped. gone names the posts to be removed that are gone from the page: their capture is the only copy, and the sentence says removing it cannot be undone. The judgements, the posts and the reads stay, and so does every media file another post still uses (blobsKept). Refused while a capture of the library is queued or running (a dry run then says captureInFlight). A later keep captures the post again. | `pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | +| `organise-trending` | organise-trending organises the topics of an X trending library. "by" is who asks ("agent" unless told) and is recorded. {"slug", "op": "rename", "topic", "title"} renames a topic: its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused. {"slug", "op": "move", "to", "ids": \[..\] \| "thread", "create"?} moves posts (or every post of one thread, by its root post's id) into the topic "to" (an id or a name; "create": true makes a topic of that name, with no trending page, when there is none) -&gt; {to, moved, skipped}; judgements and captures are untouched, a later read never moves a post back, and it is not refused beside a read or a capture. {"slug", "op": "merge", "into", "from": \[..\], "by": "operator"} puts every post, page and read of the "from" topics into "into" and removes them -&gt; {into, merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the operator's (an agent's is refused), and it is refused while a read or a reparse of the library is queued or running. The merged topics' ids keep meaning "into"; judgements are untouched; ONE watch stands (the target's live watch with its own terms, else the first merged topic's moves to it), and "sentence" says which. | `pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}'` | +| `publish-trending` | publish-trending publishes a topic of an X trending library, in two steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it says what would be written (channel, creates, posts, ids, already, files, bytes, textOnly, noLongerKept) and answers "confirm", a digest of exactly that. {"slug", "topic", "confirm", "by": "operator"} publishes: the topic's posts whose judgement in force is keep BY THE OPERATOR (their own entry, or their thread's) go into an ORDINARY posts channel ("channel": a slug of the topic's name unless given, fixed at the first publish) with their captured media and screenshots, COPIED (the library keeps its own; a purge of the library and a delete of the channel do not reach each other). An agent's keep is not published. The channel is on NO site (adding it to one is a separate step: site-config, /sites), names nothing of the library (no judgement, note, read, watch or gone mark) and is never fetched. It is the operator's press: an agent's publish is refused (an agent may ask for the dry run), and a confirm that no longer matches is refused with nothing written. Re-publishing adds newly kept posts and files and removes nothing: a post published before and since dropped is listed in noLongerKept and left; textOnly lists kept posts with no capture yet (published as their words; a later publish adds the files). Refused while a read, a reparse or a capture of the library is queued or running (a dry run then says inFlight), and when a channel of that slug exists that this publish did not make. | `pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | | `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | | `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -&gt; {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` | | `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -&gt; {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` | @@ -265,7 +267,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get x-session [<slug>] pnpm ops get cookies [fresh] pnpm ops get x-run [<run id>] - pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] + pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] [--accounts] pnpm ops get cleanup <slug> pnpm ops get speakers pnpm ops get lookouts [<id>] @@ -394,6 +396,12 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending raw capture, a cookie or a token. The route takes more for a judge view (offset, state, by, gone, media, author, q, since, seen, ids, detail; no slug lists the libraries): `umtool library` asks with them. + --accounts answers the library's ACCOUNTS instead, like an X search + channel's leads: accounts [{handle, key, name?, posts, kept, + keptByOperator, topics, last, archivedAs?}] (most posts first; kept by + the judgement in force; archivedAs the X channels that already archive + the account), total, posts, more; with it --limit is 1-500 accounts. + Archive one with x-search-lead (action "archive"). get x-run [<run id>] is the X run as /review's X run console shows it: the latest run (or the one named) — each channel's status (queued, running, done with its new posts, deferred, failed), "summary" ("N diff --git a/editor/app/api/ops/organise-trending/route.ts b/editor/app/api/ops/organise-trending/route.ts @@ -0,0 +1,60 @@ +import { NextResponse } from "next/server"; +import { organiseXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { oneOf, ops, opsFail, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, op: "rename", topic, title, by? } +// -> { ok: true, slug, op, topic, title, was, changed, sentence } +// POST { slug, op: "move", to, ids: [..] | thread, create?, by? } +// -> { ok: true, slug, op, to: {id, title, created}, moved: [ids], +// skipped: [{id, reason}], sentence } +// POST { slug, op: "merge", into, from: [topic, …], by: "operator" } +// -> { ok: true, slug, op, into: {id, title}, merged: [{id, title, posts, +// pages}], posts, pages, watch: {stands?: {from, sentence}, dropped}, +// sentence } +// +// ORGANISE AN X TRENDING LIBRARY'S TOPICS (lane x-trending-publish). `by` is +// who asks ("agent" unless told; umtool's Posts library page says +// "operator"), and it is recorded. +// +// RENAME changes a topic's name. Its id stays, so its watch, its posts, their +// judgements and a queued read are untouched. Refused: a name another topic +// answers to. +// +// MOVE puts posts — `ids`, or every post of one `thread` (its root post's +// id) — into the topic `to` (an id or a name; `create: true` makes a topic of +// that name, with no trending page, when there is none). Judgements and +// captures are untouched; a later read never moves a post back. Safe beside a +// read or a capture: not refused for one. +// +// MERGE puts every post, page and read of the `from` topics into `into` and +// removes them. THERE IS NO UNMERGE, so it is the OPERATOR's: an agent's ask +// is refused. Refused too while a read or a reparse of the library is queued +// or running. The merged topics' ids keep meaning `into`. Judgements are +// untouched. ONE watch stands: `into`'s live watch with its own terms, else +// the first merged topic's moves to it; `sentence` says which, and that it +// now reads every page in turn. +// +// Refused with a sentence: no such channel, not a library, no such topic. +export async function POST(request: Request) { + return ops(request, ["slug", "op", "by", "topic", "title", "into", "from", "to", "ids", "thread", "create"], async (body) => { + const op = oneOf(body, "op", ["rename", "move", "merge"] as const); + const create = optBool(body, "create"); + const result = await organiseXTrendingAction({ + slug: reqSlug(body, "slug"), + op, + by: body.by === undefined ? "agent" : body.by, + ...(body.topic !== undefined ? { topic: body.topic } : {}), + ...(body.title !== undefined ? { title: body.title } : {}), + ...(body.into !== undefined ? { into: body.into } : {}), + ...(body.from !== undefined ? { from: body.from } : {}), + ...(body.to !== undefined ? { to: body.to } : {}), + ...(body.ids !== undefined ? { ids: body.ids } : {}), + ...(body.thread !== undefined ? { thread: body.thread } : {}), + ...(create !== undefined ? { create } : {}), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/api/ops/publish-trending/route.test.ts b/editor/app/api/ops/publish-trending/route.test.ts @@ -0,0 +1,151 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, readdir, 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/publish-trending/route.test.ts" +// +// publish-trending, organise-trending and the accounts listing over ops (lane +// x-trending-publish), against a temp corpus: the dry run that writes +// nothing, the publish that is the operator's, the channel it makes (on no +// site, with a slug of the topic's name), a merge that is the operator's, and +// the library's accounts with the lead action's dry run. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-publish-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const READ = "tr-01JA0000000000000000000000"; +const A = "1900000000000001001"; +const B = "1900000000000001002"; +const C = "1900000000000001003"; + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} }); +const row = (id: string, author: string) => + JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: `post ${id}`, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] }); +await writeFile(path.join(lib, "trending", "posts", "2026-11.jsonl"), `${row(A, "teapot_news")}\n${row(B, "teapot_news")}\n${row(C, "saucer_fan")}\n`); +await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\ntwitter ${C}\n`); +const seen = [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }]; +const src = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}`, reads: [] }); +await writeFile( + path.join(lib, "trending", "topics.json"), + JSON.stringify({ version: 1, topics: [{ id: "kettles", title: "Kettle Festival 2026", createdAt: "2026-11-17T10:00:00.000Z", sources: [src(1)] }, { id: "cups", title: "Cups", createdAt: "2026-11-17T10:00:00.000Z", sources: [src(2)] }] }), +); +await writeFile(path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen }, [B]: { topic: "kettles", seen }, [C]: { topic: "cups", seen } } })); +await writeFile( + path.join(lib, "trending", "judgements.json"), + JSON.stringify({ version: 1, posts: { [A]: { state: "keep", note: "why", by: "operator", at: "2026-11-17T12:00:00.000Z" }, [B]: { state: "keep", by: "agent", at: "2026-11-17T12:00:00.000Z" } }, threads: {} }), +); +await mkdir(path.join(lib, "trending", "posts-media", A), { recursive: true }); +await writeFile(path.join(lib, "trending", "posts-media", A, "shot.png"), "12345"); +await writeFile(path.join(lib, "trending", "posts-media", A, "capture.json"), JSON.stringify({ version: 1, id: A, url: `https://x.com/i/status/${A}`, capturedAt: "2026-11-18T10:00:00.000Z", state: "captured", shot: { name: "shot.png", bytes: 5, sha256: "0".repeat(64) }, mediaState: "none", media: [] })); + +const PUBLISH = (await import("./route")).POST; +const ORGANISE = (await import("../organise-trending/route")).POST; +const LIST = (await import("../trending/route")).GET; +const LEAD = (await import("../x-search-lead/route")).POST; +test.after(() => rm(ROOT, { recursive: true, force: true })); +const exists = (p: string) => access(p).then(() => true, () => false); + +async function post(handler: (r: Request) => Promise<Response>, name: string, body: Record<string, unknown>, token = "test-token") { + const res = await handler(new Request(`http://localhost/api/ops/${name}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) })); + return { status: res.status, json: (await res.json()) as Record<string, any> }; +} +async function get(query: string) { + const res = await LIST(new Request(`http://localhost/api/ops/trending?${query}`, { headers: { authorization: "Bearer test-token" } })); + return { status: res.status, json: (await res.json()) as Record<string, any> }; +} + +test("publish-trending: the dry run writes nothing; the publish is the operator's with the dry run's digest; the channel is on no site", async () => { + assert.equal((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }, "wrong")).status, 401); + const dry = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }); + assert.equal(dry.status, 200); + assert.deepEqual( + { channel: dry.json.channel, creates: dry.json.creates, kept: dry.json.kept, posts: dry.json.posts, ids: dry.json.ids, files: dry.json.files, bytes: dry.json.bytes, dryRun: dry.json.dryRun }, + { channel: "kettle-festival-2026", creates: true, kept: 1, posts: 1, ids: [A], files: 1, bytes: 5, dryRun: true }, + ); + assert.match(dry.json.sentence, /would make the channel "kettle-festival-2026", on no site, writing 1 post and 1 file \(5 B\)/); + assert.deepEqual(await readdir(path.join(ROOT, "channels")), ["trending"]); + + for (const body of [{ confirm: dry.json.confirm }, { confirm: dry.json.confirm, by: "agent" }]) { + const no = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", ...body }); + assert.equal(no.status, 400); + assert.match(no.json.error, /Publishing a topic is the operator's press/); + } + const stale = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", confirm: "nope", by: "operator" }); + assert.match(stale.json.error, /has changed since it was counted/); + assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", by: "operator" })).json.error, /two steps/); + assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "nope", dryRun: true })).json.error, /has no topic "nope"/); + assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "cups", dryRun: true })).json.error, /The operator has kept no post in "Cups"/); + assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true, extra: 1 })).json.error, /extra/); + assert.deepEqual(await readdir(path.join(ROOT, "channels")), ["trending"]); + + const done = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", confirm: dry.json.confirm, by: "operator" }); + assert.equal(done.status, 200, JSON.stringify(done.json)); + assert.equal(done.json.dryRun, false); + const chan = path.join(ROOT, "channels", "kettle-festival-2026"); + assert.deepEqual(JSON.parse(await readFile(path.join(chan, "config.json"), "utf8")), { name: "Kettle Festival 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + const lines = (await readFile(path.join(chan, "posts", "2026-11.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(lines.map((p) => [p.id, p.slug, p.channelSlug]), [[A, `kettle-festival-2026/${A}`, "kettle-festival-2026"]]); + assert.equal(await readFile(path.join(chan, "posts-media", A, "shot.png"), "utf8"), "12345"); + assert.equal(await exists(path.join(ROOT, "sites")), false, "on no site"); + + // The judge view's listing says where the topic went. + const listed = await get("slug=trending&detail=1"); + assert.deepEqual(listed.json.topics.find((t: any) => t.id === "kettles").published.channel, "kettle-festival-2026"); + assert.equal((await get("slug=trending")).json.topics.find((t: any) => t.id === "kettles").published, undefined, "asked as before it answers as before"); +}); + +test("organise-trending: rename and move are anyone's and recorded; a merge is the operator's", async () => { + const renamed = await post(ORGANISE, "organise-trending", { slug: "trending", op: "rename", topic: "cups", title: "Cups and saucers" }); + assert.equal(renamed.status, 200); + assert.deepEqual([renamed.json.topic, renamed.json.title, renamed.json.changed], ["cups", "Cups and saucers", true]); + const moved = await post(ORGANISE, "organise-trending", { slug: "trending", op: "move", to: "cups", ids: [B] }); + assert.deepEqual([moved.json.moved, moved.json.to.id], [[B], "cups"]); + const topics = JSON.parse(await readFile(path.join(lib, "trending", "topics.json"), "utf8")).topics; + assert.deepEqual(topics.find((t: any) => t.id === "cups").organised.by, "agent", "by is \"agent\" unless told"); + + const agent = await post(ORGANISE, "organise-trending", { slug: "trending", op: "merge", into: "kettles", from: ["cups"] }); + assert.equal(agent.status, 400); + assert.match(agent.json.error, /Merging topics is the operator's press/); + assert.match((await post(ORGANISE, "organise-trending", { slug: "trending", op: "split" })).json.error, /"op"/); + assert.match((await post(ORGANISE, "organise-trending", { slug: "nope", op: "rename", topic: "a", title: "b" })).json.error, /No such channel/); + + const merged = await post(ORGANISE, "organise-trending", { slug: "trending", op: "merge", into: "kettles", from: ["cups"], by: "operator" }); + assert.equal(merged.status, 200, JSON.stringify(merged.json)); + assert.deepEqual([merged.json.into.id, merged.json.posts, merged.json.pages], ["kettles", 2, 2]); + // The merged topic's id still names the target. + const byOld = await get("slug=trending&topic=cups"); + assert.equal(byOld.status, 200); + assert.equal(byOld.json.total, 3); + // A published topic that was renamed keeps its channel. + await post(ORGANISE, "organise-trending", { slug: "trending", op: "rename", topic: "kettles", title: "Teapots", by: "operator" }); + const again = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }); + assert.deepEqual([again.json.channel, again.json.creates, again.json.posts], ["kettle-festival-2026", false, 0]); +}); + +test("the library's accounts, and Archive this account as a dry run: <handle>-x, nothing of the library", async () => { + const view = await get("slug=trending&accounts=1"); + assert.equal(view.status, 200); + assert.deepEqual(view.json.accounts.map((a: any) => [a.handle, a.posts, a.kept, a.keptByOperator, a.topics]), [["teapot_news", 2, 2, 1, ["kettles"]], ["saucer_fan", 1, 0, 0, ["kettles"]]]); + assert.match((await get("slug=trending&accounts=1&detail=1")).json.error, /takes slug, topic and limit only/); + assert.match((await get("slug=kettle-festival-2026&accounts=1")).json.error, /is not an X trending library/); + + const plan = await post(LEAD, "x-search-lead", { slug: "trending", handle: "saucer_fan", action: "archive", dryRun: true }); + assert.equal(plan.status, 200); + assert.deepEqual([plan.json.slug, plan.json.fields.url, plan.json.dryRun], ["saucer_fan-x", "https://x.com/saucer_fan", true]); + assert.doesNotMatch(JSON.stringify(plan.json), /trending/); + assert.match((await post(LEAD, "x-search-lead", { slug: "trending", handle: "nobody_here", action: "archive", dryRun: true })).json.error, /holds no post by @nobody_here/); + assert.match((await post(LEAD, "x-search-lead", { slug: "trending", handle: "saucer_fan", action: "never" })).json.error, /is not an X search channel/); + assert.equal(await exists(path.join(ROOT, "channels", "saucer_fan-x")), false, "a dry run creates nothing"); +}); diff --git a/editor/app/api/ops/publish-trending/route.ts b/editor/app/api/ops/publish-trending/route.ts @@ -0,0 +1,63 @@ +import { NextResponse } from "next/server"; +import { publishXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { ops, opsFail, optBool, optString, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, topic, dryRun: true, channel? } +// -> { ok: true, slug, dryRun: true, library, topic: {id, title}, channel, +// creates, kept, posts, ids, already, files, bytes, textOnly: [ids], +// noLongerKept: [ids], inFlight?, confirm, sentence } +// POST { slug, topic, confirm, by: "operator", channel? } +// -> the same, dryRun: false: published +// +// PUBLISH A TOPIC OF AN X TRENDING LIBRARY (lane x-trending-publish): the +// topic's posts whose judgement IN FORCE is KEEP BY THE OPERATOR (their own +// entry, or their thread's) are written into an ORDINARY posts channel — +// `channel`, a slug of the topic's name unless the ask gives one, fixed at +// the first publish (renaming the topic does not fork it). An agent's keep is +// a suggestion and is not published. +// +// THE CHANNEL IS ON NO SITE: adding it to one is the operator's separate act +// (`pnpm ops site-config`, /sites). It names nothing of the library: no +// judgement, note, read, watch or "gone from the page" mark, and its files +// are COPIES (the library keeps its own; a purge of the library and a delete +// of the channel do not reach each other). Nothing fetches it afterwards. +// +// TWO STEPS, AND THE SECOND IS THE OPERATOR'S. `dryRun: true` writes nothing +// and says exactly what would be written: the slug, whether the channel is +// made, `posts` to add (`ids`), `files` and `bytes` to copy, `textOnly` (kept +// posts with no capture yet: published as their words; a later publish adds +// the files) and `noLongerKept` (published before, since dropped: reported, +// never removed). The publish carries the dry run's `confirm` and `by: +// "operator"`; if anything it would write changed in between, it is refused +// and nothing is written. An agent's publish is refused: it may ask for the +// dry run. +// +// RE-PUBLISHING adds newly kept posts and files and removes nothing. +// +// Refused with a sentence: no such channel, not a library, no such topic, no +// post kept by the operator, a publish with no `confirm` or not by the +// operator, a `confirm` that no longer matches, A READ, A REPARSE OR A +// CAPTURE OF THE LIBRARY QUEUED OR RUNNING (a dry run then says `inFlight: +// true`), a `channel` other than the one the topic was published into, and A +// CHANNEL OF THAT SLUG THIS PUBLISH DID NOT MAKE (one the library has no +// record of, one with a source of its own, or one holding a post this topic +// never published). +export async function POST(request: Request) { + return ops(request, ["slug", "topic", "channel", "dryRun", "confirm", "by"], async (body) => { + const dryRun = optBool(body, "dryRun"); + const channel = optString(body, "channel"); + const confirm = optString(body, "confirm"); + const result = await publishXTrendingAction({ + slug: reqSlug(body, "slug"), + topic: reqString(body, "topic"), + ...(channel !== undefined ? { channel } : {}), + ...(dryRun !== undefined ? { dryRun } : {}), + ...(confirm !== undefined ? { confirm } : {}), + ...(body.by !== undefined ? { by: body.by } : {}), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -11,6 +11,9 @@ import { type XTrendingListFilter, type XTrendingListState, } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { readXTrendingAccounts } from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { X_TRENDING_ACCOUNTS_MAX } from "yt-dlp-transcript-common/lib/xTrending/accounts"; +import { readXTrendingPublished } from "yt-dlp-transcript-common/lib/xTrending/published"; import { opsAuth, opsFail } from "../_lib"; export const dynamic = "force-dynamic"; @@ -51,6 +54,15 @@ export const dynamic = "force-dynamic"; // THE JUDGE VIEW'S ASKS (lane posts-library: umtool's Posts library page and // `umtool library`). With none of them the answer above is unchanged. // +// accounts=1 -> { ok, slug, accounts: [{handle, key, name?, posts, kept, +// keptByOperator, topics: [ids], last, archivedAs?}], +// total, posts, more } — THE LIBRARY'S ACCOUNTS (lane +// x-trending-publish), like an X search channel's leads: +// who wrote its posts, most posts first; `kept` by the +// judgement in force; `archivedAs` the X channels that +// already archive the account. Takes `topic` and `limit` +// (default 100, at most 500) and nothing else. Archive +// one with `pnpm ops x-search-lead` (action "archive"). // (no slug) -> { ok, libraries: [{slug, name, topics, posts, unjudged}] } // every library, by its marker // offset=<n> the posts after the first n (pages with `limit`) @@ -76,7 +88,7 @@ export const dynamic = "force-dynamic"; // threadShot?, media: [{name, kind, bytes}], context?: // {parent?, quoted?}}}. A capture's files are NAMES under // trending/posts-media/<id>/: this route serves no bytes. -const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail"]; +const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail", "accounts"]; const FLAGS = new Set(["1", "true"]); export async function GET(request: Request) { @@ -99,6 +111,20 @@ export async function GET(request: Request) { const slug = sp.get("slug") ?? ""; if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); const topic = sp.get("topic") ?? undefined; + // THE LIBRARY'S ACCOUNTS (lane x-trending-publish): its own answer. + if (sp.get("accounts") !== null) { + if (!FLAGS.has(sp.get("accounts")!)) return opsFail(`"accounts" is 1 when given`); + const extra = [...sp.keys()].filter((k) => !["slug", "topic", "limit", "accounts"].includes(k)); + if (extra.length) return opsFail(`with accounts=1 the listing takes slug, topic and limit only (not "${extra[0]}")`); + let cap: number | undefined; + if (sp.get("limit") !== null) { + cap = Number(sp.get("limit")); + if (!Number.isInteger(cap) || cap < 1 || cap > X_TRENDING_ACCOUNTS_MAX) return opsFail(`"limit" is a whole number, 1–${X_TRENDING_ACCOUNTS_MAX}`); + } + const view = await readXTrendingAccounts(paths, slug, { ...(topic ? { topic } : {}), ...(cap !== undefined ? { limit: cap } : {}) }); + if (!view.ok) return opsFail(view.error, /^No such channel/.test(view.error) ? 404 : 400); + return NextResponse.json(view); + } let limit: number | undefined; if (sp.get("limit") !== null) { limit = Number(sp.get("limit")); @@ -171,8 +197,17 @@ export async function GET(request: Request) { ...(flags.ids ? { ids: true } : {}), ...(seen ? { seen } : {}), }); - if (topic && !listing.topics.some((t) => t.id === topic)) { + if (topic && !listing.topics.some((t) => t.id === topic || t.aliases?.includes(topic))) { return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`); } + // With `detail`: where each topic was published, when it was. + if (flags.detail) { + const published = await readXTrendingPublished(path.join(paths.channelsDir, slug)); + const topics = listing.topics.map((t) => { + const p = published[t.id]; + return p ? { ...t, published: { channel: p.slug, firstAt: p.firstAt, lastAt: p.lastAt, posts: Object.keys(p.posts).length } } : t; + }); + return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing, topics }); + } return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing }); } diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -67,8 +67,19 @@ import { import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot"; import { purgeXTrendingDropped, type XTrendingPurgeResult } from "yt-dlp-transcript-common/lib/xTrending/purge"; import { readXTrendingTopics } from "yt-dlp-transcript-common/lib/xTrending/store"; +import slugify from "@sindresorhus/slugify"; +import { + mergeXTrendingTopics, + moveXTrendingPosts, + renameXTrendingTopic, + type XTrendingMergeResult, + type XTrendingMoveResult, + type XTrendingRenameResult, +} from "yt-dlp-transcript-common/lib/xTrending/organise"; +import { publishXTrendingTopic, type PublishXTrendingResult } from "yt-dlp-transcript-common/controller/publishXTrending"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { capturePostsAction } from "./socialActions"; +import { recompileChannelPriorityAction } from "../actions"; import { xPressInFlight } from "../../lib/cookieRefreshGuard"; export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<StreamActionResult> { @@ -403,3 +414,112 @@ export async function purgeXTrendingAction(ask: PurgeXTrendingAsk): Promise<Purg if (!dryRun) safeRevalidate([`/channels/${ask.slug}`]); return { ok: true, slug: ask.slug, ...(ask.topic !== undefined ? { topic: ask.topic } : {}), ...out.result }; } + +// ── organise: rename, merge, move (lane x-trending-publish) ──────────────── + +// A job of this library, of one of these kinds, queued or running. +function libraryJobInFlight(slug: string, kinds: ReadonlyArray<string>): boolean { + return getRegistry() + .list() + .some((j) => kinds.includes(j.kind) && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); +} + +export type OrganiseXTrendingAsk = { + slug: string; + op: unknown; + by?: unknown; + // rename + topic?: unknown; + title?: unknown; + // merge + into?: unknown; + from?: unknown; + // move + to?: unknown; + ids?: unknown; + thread?: unknown; + create?: unknown; +}; + +export type OrganiseXTrendingActionResult = + | ({ slug: string } & Extract<XTrendingRenameResult | XTrendingMoveResult | XTrendingMergeResult, { ok: true }>) + | { ok: false; error: string }; + +// RENAME A TOPIC, MOVE POSTS BETWEEN TOPICS, MERGE TOPICS: umtool's Posts +// library page, `pnpm ops organise-trending` and `umtool library`, one body +// (lib/xTrending/organise.ts). Rename and move are an agent's or the +// operator's and record who; a merge is the operator's, and waits for a read. +export async function organiseXTrendingAction(ask: OrganiseXTrendingAsk): Promise<OrganiseXTrendingActionResult> { + const lib = await libraryRoot(ask.slug); + if (!lib.ok) return lib; + if (ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; + const by = ask.by; + let out: XTrendingRenameResult | XTrendingMoveResult | XTrendingMergeResult; + if (ask.op === "rename") { + out = await renameXTrendingTopic(lib.channelRoot, { topic: ask.topic as string, title: ask.title as string, by }); + } else if (ask.op === "move") { + out = await moveXTrendingPosts(lib.channelRoot, { + to: ask.to as string, + ...(ask.ids !== undefined ? { ids: ask.ids as string[] } : {}), + ...(ask.thread !== undefined ? { thread: ask.thread as string } : {}), + ...(ask.create === true ? { create: true } : {}), + by, + }); + } else if (ask.op === "merge") { + out = await mergeXTrendingTopics(lib.channelRoot, { + into: ask.into as string, + from: ask.from as string[], + by, + readInFlight: () => libraryJobInFlight(ask.slug, [READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND]), + }); + } else { + return { ok: false, error: `"op" is "rename", "move" or "merge"` }; + } + if (!out.ok) return out; + safeRevalidate([`/channels/${ask.slug}`]); + return { slug: ask.slug, ...out }; +} + +// ── publish a topic (lane x-trending-publish) ────────────────────────────── + +export type PublishXTrendingActionAsk = { + slug: string; + topic: string; + channel?: string; + dryRun?: boolean; + confirm?: string; + by?: unknown; +}; + +export type PublishXTrendingActionResult = ({ ok: true; slug: string } & PublishXTrendingResult) | { ok: false; error: string }; + +// PUBLISH A TOPIC'S KEPT POSTS INTO AN ORDINARY CHANNEL: umtool's Posts +// library page, `pnpm ops publish-trending` and `umtool library publish`, one +// body (controller/publishXTrending.ts). The channel's slug, for a topic +// never published, is the New channel form's own slug of the topic's title +// unless the ask names one. On NO site: adding it to one is another act. +export async function publishXTrendingAction(ask: PublishXTrendingActionAsk): Promise<PublishXTrendingActionResult> { + const dryRun = ask.dryRun === true; + const out = await publishXTrendingTopic(getPaths(), { + slug: ask.slug, + topic: ask.topic, + ...(ask.channel !== undefined ? { channel: ask.channel } : {}), + deriveSlug: (title) => slugify(title), + dryRun, + ...(ask.confirm ? { confirm: ask.confirm } : {}), + ...(ask.by !== undefined ? { by: ask.by } : {}), + busy: () => libraryJobInFlight(ask.slug, [READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND, "capture-posts"]), + }); + if (!out.ok) return out; + if (!dryRun) { + try { + // What creating a channel does everywhere (channels/actions.ts): the + // priority document learns of it. + if (out.result.creates) await recompileChannelPriorityAction(); + } catch { + /* best-effort — the channel was made regardless */ + } + safeRevalidate([`/channels/${ask.slug}`, `/channels/${out.result.channel}`, "/channels"]); + } + return { ok: true, slug: ask.slug, ...out.result }; +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -11,7 +11,7 @@ // pnpm ops <action> [--json '<body>' | --file <path>] [--wait] // [--wait-timeout <seconds>] [--quiet] // pnpm ops get channel <slug> [--counts] [--leads [--limit <n>]] -// pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] +// pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] [--accounts] // pnpm ops get channels // pnpm ops get tags [<tagId>] // pnpm ops get job <id> [--tail [<lines>]] @@ -183,6 +183,13 @@ // pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}' // pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}' // pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}' +// pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}' +// pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}' +// pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}' +// pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}' +// pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}' +// pnpm ops get trending trending --accounts +// pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}' // 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 @@ -348,10 +355,12 @@ const GETTERS = { "x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"), // An X trending library's topics and posts (lane x-trending), from its own // files: --topic narrows the posts to one topic, --limit caps them. - trending: (slug, { jobs }) => { + // --accounts answers its accounts instead (lane x-trending-publish). + trending: (slug, { jobs, accounts }) => { const q = new URLSearchParams({ slug }); if (jobs.topic) q.set("topic", jobs.topic); if (jobs.limit) q.set("limit", String(jobs.limit)); + if (accounts) q.set("accounts", "1"); return `/api/ops/trending?${q.toString()}`; }, // One channel's cleanup row: what each sweep would reclaim, what holds the rest. @@ -433,7 +442,7 @@ const GET_FLAGS = { transcript: ["slug"], "lookout-run": ["run"], channel: ["counts", "leads", "limit"], - trending: ["topic", "limit"], + trending: ["topic", "limit", "accounts"], job: ["tail"], jobs: ["active", "failed", "kind", "slug", "limit"], }; @@ -721,6 +730,16 @@ const ACTIONS = [ // dryRun} counts and answers `confirm`; {slug, confirm, by: "operator"} // removes): the operator's press, in two steps. "purge-trending", + // A library's topics organised (lane x-trending-publish): a topic renamed + // ({slug, op: "rename", topic, title}), posts moved between topics ({slug, + // op: "move", to, ids | thread, create?}), topics merged ({slug, op: + // "merge", into, from, by: "operator"}: the operator's, no unmerge). + "organise-trending", + // A topic's posts KEPT BY THE OPERATOR published into an ordinary posts + // channel on no site ({slug, topic, dryRun, channel?} says what would be + // written and answers `confirm`; {slug, topic, confirm, by: "operator"} + // publishes): the operator's press, in two steps. + "publish-trending", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -865,6 +884,7 @@ export function parseArgs(argv) { let quiet = false; let counts = false; let leads = false; + let accounts = false; let tail = 0; // `job resume-interrupted` only: list what would be re-queued. let dryRun = false; @@ -908,6 +928,9 @@ export function parseArgs(argv) { } else if (arg === "--leads") { leads = true; used.add("leads"); + } else if (arg === "--accounts") { + accounts = true; + used.add("accounts"); } else if (arg === "--active" || arg === "--failed") { jobs[arg.slice(2)] = true; used.add(arg.slice(2)); @@ -1024,7 +1047,7 @@ export function parseArgs(argv) { } return { method: "GET", - path: GETTERS[noun](positional[2], { counts, leads, tail, jobs }), + path: GETTERS[noun](positional[2], { counts, leads, accounts, tail, jobs }), wait: false, quiet, waitTimeout, @@ -1198,7 +1221,7 @@ export function usage() { " pnpm ops get x-session [<slug>]", " pnpm ops get cookies [fresh]", " pnpm ops get x-run [<run id>]", - " pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>]", + " pnpm ops get trending <slug> [--topic <topicId>] [--limit <n>] [--accounts]", " pnpm ops get cleanup <slug>", " pnpm ops get speakers", " pnpm ops get lookouts [<id>]", @@ -1329,6 +1352,12 @@ export function usage() { " raw capture, a cookie or a token. The route takes more for a judge", " view (offset, state, by, gone, media, author, q, since, seen, ids, detail; no", " slug lists the libraries): `umtool library` asks with them.", + " --accounts answers the library's ACCOUNTS instead, like an X search", + " channel's leads: accounts [{handle, key, name?, posts, kept,", + " keptByOperator, topics, last, archivedAs?}] (most posts first; kept by", + " the judgement in force; archivedAs the X channels that already archive", + " the account), total, posts, more; with it --limit is 1-500 accounts.", + " Archive one with x-search-lead (action \"archive\").", "get x-run [<run id>] is the X run as /review's X run console shows it:", " the latest run (or the one named) — each channel's status (queued,", " running, done with its new posts, deferred, failed), \"summary\" (\"N", @@ -1805,6 +1834,12 @@ export function usage() { " 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.", + " An X TRENDING LIBRARY's accounts (get trending <slug> --accounts) are", + " leads too: with \"slug\" a library, \"archive\" creates <handle>-x for an", + " account that wrote a post the library holds, on no site, naming nothing", + " of the library, and ASKS X NOTHING: there the first fetch is not started", + " unless \"fetch\": true (it is its own step: fetch-posts). \"never\" and", + " \"restore\" are a search channel's only.", "", '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,', @@ -1981,6 +2016,48 @@ export function usage() { " running (a dry run then says captureInFlight). A later keep captures", " the post again.", "", + 'organise-trending organises the topics of an X trending library. "by" is', + ' who asks ("agent" unless told) and is recorded. {"slug", "op": "rename",', + ' "topic", "title"} renames a topic: its id stays, so its watch, posts and', + " judgements are untouched; a name another topic answers to is refused.", + ' {"slug", "op": "move", "to", "ids": [..] | "thread", "create"?} moves', + " posts (or every post of one thread, by its root post's id) into the", + ' topic "to" (an id or a name; "create": true makes a topic of that name,', + " with no trending page, when there is none) -> {to, moved, skipped};", + " judgements and captures are untouched, a later read never moves a post", + " back, and it is not refused beside a read or a capture. {\"slug\", \"op\":", + ' "merge", "into", "from": [..], "by": "operator"} puts every post, page', + ' and read of the "from" topics into "into" and removes them -> {into,', + " merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the", + " operator's (an agent's is refused), and it is refused while a read or a", + " reparse of the library is queued or running. The merged topics' ids", + ' keep meaning "into"; judgements are untouched; ONE watch stands (the', + " target's live watch with its own terms, else the first merged topic's", + " moves to it), and \"sentence\" says which.", + "", + 'publish-trending publishes a topic of an X trending library, in two', + ' steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it', + " says what would be written (channel, creates, posts, ids, already,", + " files, bytes, textOnly, noLongerKept) and answers \"confirm\", a digest of", + ' exactly that. {"slug", "topic", "confirm", "by": "operator"} publishes:', + " the topic's posts whose judgement in force is keep BY THE OPERATOR", + " (their own entry, or their thread's) go into an ORDINARY posts channel", + ' ("channel": a slug of the topic\'s name unless given, fixed at the first', + " publish) with their captured media and screenshots, COPIED (the library", + " keeps its own; a purge of the library and a delete of the channel do", + " not reach each other). An agent's keep is not published. The channel is", + " on NO site (adding it to one is a separate step: site-config, /sites),", + " names nothing of the library (no judgement, note, read, watch or gone", + " mark) and is never fetched. It is the operator's press: an agent's", + " publish is refused (an agent may ask for the dry run), and a confirm", + " that no longer matches is refused with nothing written. Re-publishing", + " adds newly kept posts and files and removes nothing: a post published", + " before and since dropped is listed in noLongerKept and left; textOnly", + " lists kept posts with no capture yet (published as their words; a later", + " publish adds the files). Refused while a read, a reparse or a capture", + " of the library is queued or running (a dry run then says inFlight),", + " and when a channel of that slug exists that this publish did not make.", + "", 'watch-trending watches a topic of an X trending library: {"slug",', ' "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}.', " While a topic is watched its trending page is read again every", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1143,6 +1143,13 @@ test("read-x-trending is a POST with a result marker; get trending reads the lib assert.equal(parseArgs(["get", "trending", "lib"]).path, "/api/ops/trending?slug=lib"); assert.equal(parseArgs(["get", "trending", "lib", "--topic", "kettle-festival", "--limit", "50"]).path, "/api/ops/trending?slug=lib&topic=kettle-festival&limit=50"); assert.equal(parseArgs(["get", "trending", "lib", "--topic=a b"]).path, "/api/ops/trending?slug=lib&topic=a+b"); + // Lane x-trending-publish: the library's accounts, and the two new actions. + assert.equal(parseArgs(["get", "trending", "lib", "--accounts", "--limit", "20"]).path, "/api/ops/trending?slug=lib&limit=20&accounts=1"); + assert.match(parseArgs(["get", "channel", "lib", "--accounts"]).error, /does not take --accounts/); + const organise = parseArgs(["organise-trending", "--json", '{"slug":"lib","op":"rename","topic":"kettles","title":"Teapots"}']); + assert.deepEqual([organise.method, organise.path, organise.body], ["POST", "/api/ops/organise-trending", { slug: "lib", op: "rename", topic: "kettles", title: "Teapots" }]); + const publish = parseArgs(["publish-trending", "--json", '{"slug":"lib","topic":"kettles","dryRun":true}']); + assert.deepEqual([publish.method, publish.path, publish.body], ["POST", "/api/ops/publish-trending", { slug: "lib", topic: "kettles", dryRun: true }]); assert.match(parseArgs(["get", "trending"]).error, /trending/); assert.match(parseArgs(["get", "trending", "lib", "--leads"]).error, /get trending does not take --leads/); assert.match(parseArgs(["get", "channel", "s", "--topic", "x"]).error, /get channel does not take --topic/);