Archilyzer · Source

archilyzer

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

commit fb3705fcb5633e140601cb36e8ff81a773f58008
parent 9a4990136abff0fdfe3fa01dfe9c7fb402fe49f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 12:56:47 -0500

Merge lane/x-trending-publish: the trending library is organised and published, slice 4 -- topics are renamed, merged (the operator's) and posts moved between them; `publish-trending`, the operator's alone and in two steps, copies a topic's posts the operator kept, with their captures, into an ordinary posts channel on no site, rebuilt field by field so nothing of the library goes with them, and says which sites the channel is on and which posts were moved in; such a channel has no source and makes no request anywhere; the library lists its accounts, and archiving one makes its channel with sync off and asks X nothing; the library itself stays behind every publishing door

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

Diffstat:
MCOMMANDS.md | 12++++++++++--
MOPERATING.md | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/xTrendingPublishedSite.test.ts | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 4++++
Mcommon/controller/checkPostAvailability.ts | 6++++++
Mcommon/controller/fetchPosts.ts | 7+++++++
Mcommon/controller/fetchWindows.test.ts | 26++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 10++++++++++
Acommon/controller/publishXTrending.test.ts | 633+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/publishXTrending.ts | 760+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/sourcelessPosts.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/undownloadedVideos.ts | 7+++++++
Mcommon/controller/xRun.ts | 6+++++-
Mcommon/controller/xSearchLeads.test.ts | 74+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/xSearchLeads.ts | 27++++++++++++++++++++++++++-
Mcommon/controller/xTrendingGuards.test.ts | 5++++-
Acommon/jobs/xLeadSyncOff.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourcelessPosts.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xSearch/leads.ts | 27+++++++++++++++++++++++++++
Acommon/lib/xTrending/accounts.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/organise.test.ts | 307+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/organise.ts | 420+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/published.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/social/importPost.ts | 3+++
Meditor/CHANGELOG.md | 20++++++++++++++++++++
Aeditor/app/api/ops/organise-trending/route.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/publish-trending/route.test.ts | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/publish-trending/route.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/trending/route.ts | 39+++++++++++++++++++++++++++++++++++++--
Meditor/app/api/ops/wayback-lookup/route.ts | 5+++++
Meditor/app/api/ops/x-search-lead/route.ts | 24++++++++++++++++++++++--
Meditor/app/channels/[slug]/page.tsx | 7+++++--
Meditor/app/channels/[slug]/socialActions.ts | 10++++++++++
Meditor/app/channels/[slug]/xSearchActions.ts | 34+++++++++++++++++++++++++++++-----
Meditor/app/channels/[slug]/xTrendingActions.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/actions.ts | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/e2e/x-trending.spec.ts | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/protocol.test.ts | 1+
Mmcp/src/server.ts | 4+++-
Mmcp/src/xTrending.test.ts | 40++++++++++++++++++++++++++++++++++++++++
Mmcp/src/xTrending.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/xTrendingPrivacy.test.ts | 9++++++++-
Mplans/x-trending.md | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mscripts/archilyzer-ops.mjs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mscripts/archilyzer-ops.test.mjs | 7+++++++
Aumtool/app/api/library/accounts/route.ts | 31+++++++++++++++++++++++++++++++
Aumtool/app/api/library/archive/route.ts | 18++++++++++++++++++
Aumtool/app/api/library/organise/route.ts | 19+++++++++++++++++++
Aumtool/app/api/library/publish/route.ts | 16++++++++++++++++
Mumtool/components/tools/library/LibraryView.tsx | 15+++++++--------
Aumtool/components/tools/library/OrganisePanel.tsx | 345+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 10++++++++++
Mumtool/docs/tools.md | 20+++++++++++++++++++-
Mumtool/e2e/fixtures/editor-stub-trending.mjs | 202++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/e2e/library.spec.ts | 249++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/cli/groups.mjs | 12++++++++++++
Mumtool/lib/cli/verbs.mjs | 6++++++
Mumtool/lib/library/caller.mjs | 2+-
Mumtool/lib/library/cli.mjs | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/library/client.mjs | 39+++++++++++++++++++++++++++++++++++++--
Mumtool/lib/library/load.ts | 3++-
Aumtool/lib/library/organise.test.mjs | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/library/presses.mjs | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/library/seen.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/report/xTrendingLibrary.test.mjs | 16++++++++++++++--
66 files changed, 5767 insertions(+), 87 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, now or later: no first fetch is started and the channel is made with SYNC OFF (its priority tier paused, which the scheduler, Sync all and the lanes honour) -&gt; {slug, jobIds: \[\], syncOff: true, sentence}. The sentence says how to turn sync on (channel-priority, tier normal) and run the first fetch (fetch-posts). "fetch": true asks for the ordinary behaviour instead (the first fetch started, sync on). "never" and "restore" are a search channel's only. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'`<br>`pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}'` | | `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/&lt;number&gt;"}, as one job on X's queue (the fresh-jar rule, the X alert and X's job gap apply; ask get x-session first). The page is opened in the connected X profile's browser, every GraphQL answer the page itself fetched is saved raw with a screenshot (channels/&lt;slug&gt;/trending/reads/&lt;readId&gt;/), and the posts are parsed from the saved file and written as the library's posts. A read lists posts; it archives no media and no thread. "topic": a topic's id or name, or a new one's name (absent: the topic this page was read into before, else a new one named for it). "scrolls": 1-20 moves to the bottom of the page (default: the channel's cap, else 8); "posts": stop once 1-200 are seen (else 60); a read also stops after two scrolls with nothing new, and at once on a 429, a 403 or a login wall. A 429 leaves X alone for 15 minutes (no read is queued or started before the time its sentence names); a page that stops answering ends the read within 6 minutes. Nothing retries. "probe": true saves the capture and its summary and writes no post. "headed": true opens a window on the editor's desktop. {"slug", "reparse": "&lt;readId&gt;"} parses a saved read again OFFLINE (X is asked nothing; a read left with no record takes "url" too). No fresh jar needed. --wait prints the log's @@read-x-trending {ok, mode, read, outcome, stop, responses, operations (names and sizes, never a body), posts: {onPage, added}, topic, sentence}; a capture with no post the parser knows ends ok, "read saved, nothing recognised". Refused before a job: not a library, not a trending page URL, a cap out of range, no connected X profile, X's Connect or Refresh in flight, a stale jar. A library is made with create-channel, "platform": "x-trending" (no "url", no "sites": it is private, never on a site, in no index build; "xTrendingMaxScrolls"?, "xTrendingMaxPosts"? set its caps). | `pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait` | | `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, and so is a rename while a read or a reparse of the library is queued or running (a read may name its topic by its name). {"slug", "op": "move", "to", "ids": \[..\] \| "thread", "create"?} moves posts (or every post of one thread, by its root post's id) into the topic "to" (an id or a name; "create": true makes a topic of that name, with no trending page, when there is none) -&gt; {to, moved, skipped}; judgements and captures are untouched, a later read never moves a post back, and it is not refused beside a read or a capture. {"slug", "op": "merge", "into", "from": \[..\], "by": "operator"} puts every post, page and read of the "from" topics into "into" and removes them -&gt; {into, merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the operator's (an agent's is refused), and it is refused while a read or a reparse of the library is queued or running. The merged topics' ids keep meaning "into"; judgements are untouched; ONE watch stands (the target's live watch with its own terms, else the first merged topic's moves to it), and "sentence" says which. A topic has one published channel too (published: {carried?, left}): the target's stays; with none, the first merged topic's becomes its own; any other is left as it is, never added to again, and named in the sentence. | `pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}'` | +| `publish-trending` | publish-trending publishes a topic of an X trending library, in two steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it says what would be written (channel, creates, posts, ids, already, files, bytes, textOnly, noLongerKept) and what to know before the press: sites (the sites the channel is ALREADY ON: what is added goes public at their next build), movedIn (posts to publish that were moved into the topic, and by whom) and mismatched (files that no longer match the digest their capture recorded: not copied). It answers "confirm", a digest of exactly that, the sites included. Then {"slug", "topic", "confirm", "by": "operator"} publishes: the topic's posts whose judgement in force is keep BY THE OPERATOR (their own entry, or their thread's) go into an ORDINARY posts channel ("channel": a slug of the topic's name unless given, fixed at the first publish) with their captured media and screenshots, COPIED (the library keeps its own; a purge of the library and a delete of the channel do not reach each other). An agent's keep is not published. The channel is on NO site (adding it to one is a separate step: site-config, /sites), names nothing of the library (no judgement, note, read, watch or gone mark) and is never fetched. It is the operator's press: an agent's publish is refused (an agent may ask for the dry run), and a confirm that no longer matches is refused with nothing written. Re-publishing adds newly kept posts and files and removes nothing: a post published before and since dropped is listed in noLongerKept and left; textOnly lists kept posts with no capture yet (published as their words; a later publish adds the files). Refused while a read, a reparse or a capture of the library is queued or running (a dry run then says inFlight), and when a channel of that slug exists that this publish did not make (no record of it, a source of its own, a post this topic never published, or not the very directory this publish made: a channel deleted and made again by hand is refused, even empty). | `pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | | `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/OPERATING.md b/OPERATING.md @@ -795,6 +795,94 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o - **A restart.** A tick left queued when the editor stops is cancelled; the scan starts another at its next pass, jar permitting. `ARCHILYZER_IDLE_BOOT` does not arm the scan at all. +### From a trending page to a published topic + +A library is private until a person publishes one of its topics. The whole path, each step an editor action with its +`pnpm ops` twin; umtool's **Posts library** (`/tools/library`) is the operator's form of the same actions. + +```sh +pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait +pnpm ops get trending trending --topic kettle-festival +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 judge-trending --json '{"slug":"trending","by":"operator","set":[{"id":"1900000000000001001","state":"keep"}]}' +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}' +``` + +- **Organise** (`organise-trending`; `"by"` is `agent` unless told, and is recorded). + - `rename` changes a topic's name. Its id stays, so its watch, its posts and their judgements are untouched. A name + another topic answers to is refused. So is a rename while a read or a reparse of the library is queued or + running: a read may name its topic by its name, and would make a new topic of the old one. + - `move` puts posts (`"ids"`), or every post of one thread (`"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, and a later read never moves a post back. It is safe beside a read or a + capture and is not refused for one. + - `merge` puts every post, page and read of the `"from"` topics into `"into"`, and they are gone. **There is no + unmerge, so a merge is the operator's**: an agent's is refused. It is refused too while a read or a reparse of + the library is queued or running (a queued watch tick names its topic). The merged topics' ids keep meaning the + topic that stays. Judgements are untouched. **One watch stands**: the target's live watch with its own terms; + when the target has none, the first merged topic's moves to it. The answer's sentence says which. **A topic + has one published channel**: the target's stays its own; when it has none, the first merged topic's channel + becomes its own (the next publish adds to it); any other merged topic's channel is left as it is, is never + added to again, and is named in the sentence. +- **Publish** (`publish-trending`), in two steps, the second the operator's. + - `"dryRun": true` writes nothing and says exactly what would be written: `channel` (the slug) and whether it is + made (`creates`), the `posts` to add (`ids`), the `files` and `bytes` to copy, `textOnly` (kept posts with no + capture yet) and `noLongerKept`. It answers `confirm`. An agent may ask for it. + - **Read the dry run before the press.** `sites` names the sites the channel is ALREADY on: what a publish adds to + such a channel goes public at each site's next build, and the sentence says so in capitals. `movedIn` lists + the posts to publish that were moved into this topic and by whom (an agent may move posts, and a move changes + what a publish takes). `mismatched` lists files whose bytes are no longer what their capture recorded: they + are not copied. The `confirm` covers the sites: a channel put on a site after the dry run refuses the publish. + - The publish carries that `confirm` and `"by": "operator"`. If anything it would write changed in between (a + post kept or dropped, a capture finished, a post moved) it is refused and nothing is written. Refused while a + read, a reparse or a capture of the library is queued or running. + - **What is published**: the topic's posts whose judgement in force is keep **by the operator**, their own or + their thread's. An agent's keep is a suggestion and is not published; nor is a post marked later, dropped or + undecided. + - **Where**: an ordinary posts channel. Its slug is a slug of the topic's name unless the first publish names one + (`"channel"`); it is fixed after that, so renaming the topic does not fork it. The channel is **on no site**: + adding it to one is a separate step: its Configure → Sites, or `pnpm ops channel-config --json '{"slug":"<channel>", + "sites":[{"siteId":"<site>"}]}'`. Configure sets such a channel's name and its sites and nothing else: it cannot + be given a URL, a handle or a fetcher. `social.x.visibility` applies to it as to any X channel. + - **What the channel holds**: the posts, their captured screenshots and media, and what X said of them + (deleted). Nothing of the library: no judgement, note, read, watch or "gone from the page" mark, and no mention + of the library. The files are **copies**: the library keeps its own, a purge of the library does not reach the + channel, and deleting the channel does not reach the library. + - **Nothing fetches the channel.** It has no account: `fetch-posts`, `capture-posts`, `import-post`, the + availability check and an X run refuse it with one sentence, and Sync all and an X run's list leave it out. + No address is ever built for one of its posts: a clip window, transcribe-one and a Wayback lookup of one are + refused. Its page offers no Scraping method, and a fetcher key written onto it changes none of this. + - **Publishing again** adds newly kept posts, and the files of a post whose capture came later. It removes + nothing: a post published before and since dropped is listed in `noLongerKept` and stays in the channel. To + take a post out, remove it from the channel yourself. + - **A channel of that slug that this publish did not make is never added to.** The library records what it + published (`trending/published.json`); a channel is this publish's when that record names it, it still has no + source of its own, it holds no post the record does not name, and it is the very directory the publish made + (the record keeps the directory's inode and birth time; nothing is written into the channel). Otherwise the + publish is refused: name another slug at a first publish, or remove that channel. A published channel that + was deleted is made again by the next publish, but one made again BY HAND under that slug, even empty, is + refused; so is a bare directory of the slug. One that was renamed is left alone, and the next publish makes a + new channel under the recorded slug. +- **Accounts** (`get trending <slug> --accounts`, the MCP's `x_trending_accounts`): who wrote the library's posts, + with posts, kept, topics and the X channels that already archive each. `x-search-lead` with `"action": + "archive"` makes `<handle>-x` for an account that wrote a post the library holds: an X channel on no site that + names nothing of the library. **From a library it asks X nothing, now or later.** No first fetch is started, and + the channel is made with **sync off**: its priority tier is `paused`, which the sync scheduler, Sync all and the + lanes all honour. (A never-synced channel with a URL is the most overdue one the scheduler knows: without this, + its next tick would fetch it.) The answer's sentence says how to go on: turn sync on by setting its priority to + normal on /channels (`pnpm ops channel-priority --json '{"slugs":["<handle>-x"],"tier":"normal"}'`), and run its + first fetch with **Fetch posts** on its page (`pnpm ops fetch-posts`). `"fetch": true` asks for the ordinary + behaviour instead: the first fetch started, sync on. An X search channel's lead is archived as before. +- **In umtool**: a topic's panel has **Rename**, **Merge…** (behind a confirm that says it cannot be undone) and + **Publish kept posts…** (the dry run, then **Publish**); the bar has **Move to**; **Accounts** lists the accounts + with **Archive this account…**. `umtool library rename | move | merge | publish | accounts | archive` are the same + from a shell; `merge` and `publish` want `--by operator`. + ## Transcribe ```sh diff --git a/common/bin/xTrendingPublishedSite.test.ts b/common/bin/xTrendingPublishedSite.test.ts @@ -0,0 +1,197 @@ +// THE LIBRARY STAYS BEHIND EVERY DOOR; THE PUBLISHED CHANNEL IS AN ORDINARY +// CHANNEL (lane x-trending-publish). bin/xTrendingPrivacy.test.ts pins the +// first half. This pins the second, over a temp corpus, through the real +// publish, the real site writer, the real index build and the real compose: +// +// - a topic is published, and the channel it makes is put on a site by the +// site writer (which refuses the library itself); +// - the build and the composed site carry the post the OPERATOR kept; +// - and NOTHING ELSE of the library: not a post an agent kept, a dropped, +// later or undecided one, a post of another topic, a judgement's note, +// the raw capture of a read, nor the library's slug or a file of its +// name; +// - `social.x.visibility` still covers the published channel (it is an X +// posts channel), and no build or publisher module imports the publish or +// the organise bodies. +// +// Run with: node_modules/.bin/tsx --test common/bin/xTrendingPublishedSite.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "x-trending-published-site-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}); +delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("../controller/buildIndex"); +const { publishXTrendingTopic } = await import("../controller/publishXTrending"); +const { readChannelConfig } = await import("../controller/channels"); +const { main: composeSite } = await import("./compose-site"); +const { writeSite } = await import("../lib/site"); +const { postsVisibleTo } = await import("../lib/postsVisibility"); +const { judgeXTrending } = await import("../lib/xTrending/judgements"); +const { recordXTrendingRead, writeXTrendingPosts, trendingReadDir } = await import("../lib/xTrending/store"); +const { X_TRENDING_NOT_ON_A_SITE } = await import("../lib/xTrending/config"); + +const paths = getPaths(); +const LIB = "zzprivatelibraryq7"; +const CHANNEL = "kettle-festival"; +const READ = "tr-01JA0000000000000000000000"; +const KEPT = "publishedkeptwordsmarkx3d"; +const PRIVATE = { + agentKept: "agentkeptwordsmarkb6t", + dropped: "droppedwordsmarkc2m", + later: "laterwordsmarkd9p", + undecided: "undecidedwordsmarkf5r", + otherTopic: "othertopicwordsmarkg1s", + note: "judgenotemarkq4z", + raw: "rawcapturemarkj9m", +}; +const quiet = () => {}; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const post = (id: string, text: string) => ({ + id, slug: `${LIB}/${id}`, channelSlug: LIB, author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", + text, url: `https://x.com/teapot_news/status/${id}`, platform: "twitter" as const, isReply: false, isRepost: false, links: [], +}); + +writeJson(paths.settingsFile, {}); +const libRoot = path.join(paths.channelsDir, LIB); +writeJson(path.join(libRoot, "config.json"), { handling: "transcribe", sourceKind: "social", platform: "twitter", name: "A library", xTrending: {} }); +await writeXTrendingPosts(libRoot, [ + post("801", `the opening ${KEPT}`), + post("802", PRIVATE.agentKept), + post("803", PRIVATE.dropped), + post("804", PRIVATE.later), + post("805", PRIVATE.undecided), + post("806", PRIVATE.otherTopic), +]); +const ref = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); +await recordXTrendingRead(libRoot, { readId: READ, at: "2026-11-17T10:00:00.000Z", ref: ref(1), topic: "Kettle Festival", postIds: ["801", "802", "803", "804", "805"], added: 5 }); +await recordXTrendingRead(libRoot, { readId: "tr-01JB0000000000000000000000", at: "2026-11-17T11:00:00.000Z", ref: ref(2), topic: "Cups", postIds: ["806"], added: 1 }); +mkdirSync(trendingReadDir(libRoot, READ), { recursive: true }); +writeFileSync(path.join(trendingReadDir(libRoot, READ), "responses.jsonl"), `${JSON.stringify({ n: 1, op: "Op", status: 200, body: { t: PRIVATE.raw } })}\n`); +await judgeXTrending(libRoot, { by: "agent", set: [{ id: "802", state: "keep" }] }); +await judgeXTrending(libRoot, { by: "operator", set: [{ id: "801", state: "keep", note: `why ${PRIVATE.note}` }, { id: "803", state: "drop" }, { id: "804", state: "later" }, { id: "806", state: "keep" }] }); + +const site = (channels: string[]) => ({ + siteId: "pub", siteTitle: "pub", siteDescription: "fixture", headerTitle: "pub", homeTagline: "", + socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", channels: channels.map((slug) => ({ slug, groupId: "default" })), + siteUrl: "https://pub.example.test", archives: false, +}); + +function filesUnder(dir: string): { rel: string; text: string }[] { + const out: { rel: string; text: string }[] = []; + const walk = (d: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const p = path.join(d, e.name); + if (e.isDirectory()) walk(p); + else if (e.isFile() || (e.isSymbolicLink() && statSync(p).isFile())) out.push({ rel: path.relative(dir, p), text: readFileSync(p).toString("latin1") }); + } + }; + if (existsSync(dir)) walk(dir); + return out; +} + +test("a published topic's channel goes on a site by the site writer, and builds the operator's kept post and nothing else of the library", async () => { + const ask = { slug: LIB, topic: "kettle-festival", deriveSlug: () => CHANNEL, busy: () => false }; + const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.ids, ["801"]); + const done = await publishXTrendingTopic(paths, { ...ask, dryRun: false, confirm: dry.result.confirm, by: "operator" }); + assert.ok(done.ok); + + // The site writer: the library refused as ever, the published channel taken like any channel. + await assert.rejects(writeSite(site([LIB]) as never, paths), { message: X_TRENDING_NOT_ON_A_SITE(LIB) }); + await writeSite(site([CHANNEL]) as never, paths); + + const log: string[] = []; + await buildIndex({ paths, onLog: (l: string) => log.push(l) }); + assert.ok(log.some((l) => l.includes(`Skipping channel ${LIB}: an X trending library`)), "the build still skips the library"); + const out = console.log; + const warn = console.warn; + console.log = quiet; + console.warn = quiet; + try { + await composeSite({ siteId: "pub", paths }); + } finally { + console.log = out; + console.warn = warn; + } + + for (const [where, dir] of [["the index", paths.exportIndexDir], ["the composed site", paths.exportPublicDir]] as const) { + const files = filesUnder(dir); + assert.ok(files.length > 0, `${where} was written`); + // THE PUBLISHED POST IS THERE: the operator published it. + assert.ok(files.some((f) => f.text.includes(KEPT)), `${where} carries the post the operator kept and published`); + for (const f of files) { + for (const [what, mark] of Object.entries(PRIVATE)) assert.ok(!f.text.includes(mark), `${where}: ${f.rel} carries the library's ${what}`); + assert.ok(!f.text.includes(LIB), `${where}: ${f.rel} names the library`); + assert.ok(!f.rel.split(path.sep).includes(LIB), `${where}: a file under ${f.rel}`); + for (const name of ["judgements.json", "membership.json", "topics.json", "watch.json", "published.json", "media-index.json", "media-store", "reads"]) { + assert.ok(!f.rel.split(path.sep).includes(name), `${where} wrote ${f.rel}`); + } + } + } + const composed = filesUnder(paths.exportPublicDir); + for (const name of ["corpus.json", "site.json"]) { + const f = composed.find((x) => x.rel === name); + assert.ok(f, `${name} was composed`); + assert.ok(f!.text.includes(CHANNEL), `${name} names the published channel`); + } +}); + +test("social.x.visibility covers the published channel: it is an X posts channel", async () => { + const config = await readChannelConfig(paths, CHANNEL); + assert.ok(config); + const isPrivate = { social: { x: { visibility: "private" } } }; + assert.equal(postsVisibleTo({ audience: "public" } as never, config, isPrivate), false, "X private: no public site carries it"); + assert.equal(postsVisibleTo({ audience: "private" } as never, config, isPrivate), true); + assert.equal(postsVisibleTo({ audience: "public" } as never, config, {}), true); + // The library itself: on no site, whatever the setting. + assert.equal(postsVisibleTo({ audience: "private" } as never, await readChannelConfig(paths, LIB), {}), false); +}); + +test("no build, publisher, export, homepage or MCP module reaches the publish or the organise bodies", () => { + const repo = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", ".."); + const sources: { rel: string; text: string }[] = []; + const walk = (d: string) => { + if (!existsSync(d)) return; + for (const e of readdirSync(d, { withFileTypes: true })) { + if (e.name === "node_modules" || e.name.startsWith(".")) continue; + const p = path.join(d, e.name); + if (e.isDirectory()) walk(p); + else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\.|\.unit\./.test(e.name)) sources.push({ rel: path.relative(repo, p), text: readFileSync(p, "utf8") }); + } + }; + for (const d of ["common/bin", "common/publish", "common/views", "export/app", "export/lib", "homepage/app", "homepage/lib", "mcp/src"]) walk(path.join(repo, d)); + assert.ok(sources.length > 50, "the sweep read the publishing sources"); + const WORDS = ["publishXTrending", "xTrending/published", "xTrending/organise", "mergeXTrendingTopics", "moveXTrendingPosts", "renameXTrendingTopic", "readXTrendingPublished", "publish-trending", "organise-trending"]; + for (const f of sources) for (const word of WORDS) assert.ok(!f.text.includes(word), `${f.rel} names ${word}`); + // The sweep catches what it guards against. + assert.ok(WORDS.some((w) => 'import { publishXTrendingTopic } from "../controller/publishXTrending";'.includes(w))); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -35,6 +35,7 @@ import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import { readXTrendingMembership, TRENDING_RESPONSES_FILENAME, @@ -259,6 +260,9 @@ export async function capturePosts( const config = await readChannelConfig(paths, slug); if (!config) return fail(`No such channel: ${slug}`); if (!isSocialChannel(config)) return fail(`${slug} is not a social channel.`); + // Posts published from a private library (lane x-trending-publish): their + // captures came with them, and nothing is asked of X for this channel. + if (isSourcelessPostsChannel(config)) return fail(SOURCELESS_POSTS_CHANNEL(slug)); // A Wayback pages channel (release 37 S4): no fetcher — each record is // rendered from its capture's replay, its images from the archive. diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -40,6 +40,7 @@ import "../social/xNitterFetcher"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import type { CheckOriginalOptions } from "../lib/waybackPages/liveness-server"; import { checkPageAvailability } from "./checkPageAvailability"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; export type CheckPostAvailabilityMode = "stale" | "unchecked" | "all"; @@ -125,6 +126,11 @@ export async function checkPostAvailability( if (!isSocialChannel(config)) { return { ok: false, ...empty, error: `${slug} is not a social channel.` }; } + // Posts published from a private library (lane x-trending-publish): what X + // said of them came with them; nothing is asked of X for this channel. + if (isSourcelessPostsChannel(config)) { + return { ok: false, ...empty, error: SOURCELESS_POSTS_CHANNEL(slug) }; + } // A Wayback pages channel (release 37 S5): each record's ORIGINAL URL, // asked at its own site — no fetcher, never the Wayback Machine. if (isWaybackPagesChannel(config)) { diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -17,6 +17,7 @@ import { isSocialChannel } from "../lib/channelConfig"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "../lib/xTrending/config"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import { fetchXSearchPosts, X_SEARCH_OLDER_REFUSAL } from "./fetchXSearch"; import { alwaysCookies, @@ -285,6 +286,12 @@ export async function fetchPosts( return { ok: false, written: 0, skipped: 0, complete: false, error: X_TRENDING_NOT_FETCHED(slug) }; } + // Posts published from a private library (lane x-trending-publish): no + // account, no search, no page — nothing is asked of X for it. + if (isSourcelessPostsChannel(config)) { + return { ok: false, written: 0, skipped: 0, complete: false, error: SOURCELESS_POSTS_CHANNEL(slug) }; + } + const accountUrl = config.url ?? ""; const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl); if (!fetcher) { diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -885,3 +885,29 @@ test("a local media library channel and a local recording fail local-media, and for (const f of r.failed) assert.match(f.message ?? "", /no online source, so no clip can be fetched/); assert.equal(r.fetched.length, 1); }); + +// Lane x-trending-publish, review 1 S1: posts published from a private library +// have no page of their own. The item is failed before any URL is looked up, +// even one that carries an address of its own; the run goes on. +test("a source-less posts channel's window is refused with its sentence, whatever URL the item carries", async () => { + const PUBLISHED = { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" } as never; + let looked = 0; + const h = harness({ + readChannelConfig: async (_p, slug) => (slug === "kettle-festival" ? PUBLISHED : CONFIG), + findVideoSourceUrl: async () => { + looked++; + return null; + }, + }); + const r = await go( + await corpus(), + [{ ...item("1900000000000001001", "/x"), slug: "kettle-festival", webpageUrl: "https://x.com/i/status/1900000000000001001" }, { slug: "kettle-festival", id: "1900000000000001002", from: 1, to: 2 }, item("v2", "/ok")], + h, + ); + assert.deepEqual(r.failed.map((f) => [f.class, f.message]), [ + ["no-url", "kettle-festival holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it."], + ["no-url", "kettle-festival holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it."], + ]); + assert.equal(looked, 0, "no source URL was looked up for it"); + assert.equal(r.fetched.length, 1, "the run goes on"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -1,5 +1,6 @@ import path from "node:path"; import { localMediaFetchRefusal } from "../lib/localMedia"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; @@ -854,6 +855,15 @@ export async function fetchWindows({ progress(); continue; } + // Posts published from a private library (lib/sourcelessPosts.ts; review 1 + // S1): no page of its own, so no window is fetched for it — whatever + // address the item itself carries. + if (isSourcelessPostsChannel(config)) { + fail(item, "no-url", SOURCELESS_POSTS_CHANNEL(item.slug)); + done += 1; + progress(); + continue; + } const unreadable = await textProblem(item.slug); if (unreadable) { fail(item, "unreachable", unreadable); diff --git a/common/controller/publishXTrending.test.ts b/common/controller/publishXTrending.test.ts @@ -0,0 +1,633 @@ +// Publishing a topic of an X trending library (lane x-trending-publish): the +// operator's kept posts and nothing else become an ordinary channel that +// names nothing of the library; files are copies with inodes of their own; +// "made by this publish" is the library's record and the channel's content. +// A temp corpus; no network, no editor. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/publishXTrending.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtemp } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Post } from "../lib/posts"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-publish-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const { getPaths } = await import("../lib/paths"); +const { readAllPosts, readPostAvailability, writePostAvailability, writePosts } = await import("../lib/posts-server"); +const { isSourcelessPostsChannel } = await import("../lib/sourcelessPosts"); +const { judgeXTrending } = await import("../lib/xTrending/judgements"); +const { adoptXTrendingMedia } = await import("../lib/xTrending/mediaStore"); +const { renameXTrendingTopic, moveXTrendingPosts } = await import("../lib/xTrending/organise"); +const { readXTrendingPublished } = await import("../lib/xTrending/published"); +const { purgeXTrendingDropped } = await import("../lib/xTrending/purge"); +const { recordXTrendingRead, trendingDir, writeXTrendingPosts } = await import("../lib/xTrending/store"); +const { createChannel, deleteChannel, readChannelConfig } = await import("./channels"); +const { writeSite } = await import("../lib/site"); +const { mutateXTrendingPublished } = await import("../lib/xTrending/published"); +const { + NOT_THIS_PUBLISHS_CHANNEL, + PUBLISH_IS_THE_OPERATORS, + PUBLISH_SET_CHANGED, + PUBLISH_WAITS, + PUBLISHED_POST_FIELDS, + captureFileNames, + publishedCaptureOf, + publishedPostOf, + publishXTrendingTopic, +} = await import("./publishXTrending"); +const paths = getPaths(); + +const IDLE = () => false; +const derive = (title: string) => title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); +const READ_A = "tr-01JA0000000000000000000000"; +const READ_B = "tr-01JB0000000000000000000000"; +const READ_C = "tr-01JC0000000000000000000000"; +const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }; +const REF_2 = { trendId: "1900000000000000002", url: "https://x.com/i/trending/1900000000000000002" }; +const MARK = { note: "judgenotemarkq4z", stray: "straybytesmarkw8k", owed: "owedtextmarkv3n", agentPost: "agentkeptwordsmarkb6t", dropped: "droppedwordsmarkc2m", later: "laterwordsmarkd9p", undecided: "undecidedwordsmarkf5r", otherTopic: "othertopicwordsmarkg1s" }; + +function post(lib: string, id: string, text: string, extra: Partial<Post> = {}): Post { + return { id, slug: `${lib}/${id}`, channelSlug: lib, author: "teapot_news", authorName: "Teapot News", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/teapot_news/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra }; +} + +const sha = (text: string) => createHash("sha256").update(text).digest("hex"); + +function capture(libRoot: string, id: string, files: Record<string, string>, record: Record<string, unknown> = {}) { + const dir = path.join(libRoot, "trending", "posts-media", id); + mkdirSync(dir, { recursive: true }); + for (const [name, bytes] of Object.entries(files)) writeFileSync(path.join(dir, name), bytes); + const media = Object.keys(files).filter((n) => /_\d+\.(jpg|mp4)$/.test(n)); + writeFileSync( + path.join(dir, "capture.json"), + JSON.stringify({ + version: 1, + id, + url: `https://x.com/i/status/${id}`, + capturedAt: "2026-11-18T10:05:00.000Z", + state: "captured", + // As a capture job leaves it: each file's own size and digest. + ...(files["shot.png"] ? { shot: { name: "shot.png", bytes: files["shot.png"].length, sha256: sha(files["shot.png"]) } } : {}), + mediaState: "ok", + media: media.map((name) => ({ name, bytes: files[name].length, sha256: sha(files[name]), url: `https://pbs.twimg.com/media/${name}` })), + ...record, + }), + ); + return media; +} + +// A library "<lib>" with the topic "Kettle Festival": +// 801 kept by the operator (a note), captured (a shot, a picture, a stray +// file its record does not name), X said deleted, gone from the page +// 802 kept by an AGENT 803 dropped by the operator, captured +// 804 later 805 undecided +// 806 a THREAD kept by the operator, captured, the same picture as 801 +// 807 its reply: kept through the thread, no capture yet +// and the topic "Cups": 808 kept by the operator. +async function library(lib: string): Promise<string> { + const libRoot = path.join(paths.channelsDir, lib); + await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); + await writeXTrendingPosts(libRoot, [ + post(lib, "801", "first words", { engagement: { likes: 3 }, links: ["https://example.org/a"] }), + post(lib, "802", MARK.agentPost), + post(lib, "803", MARK.dropped), + post(lib, "804", MARK.later), + post(lib, "805", MARK.undecided), + post(lib, "806", "thread root words"), + post(lib, "807", "thread reply words", { isReply: true, threadId: "806", replyTo: { platform: "twitter", id: "806" } }), + post(lib, "808", MARK.otherTopic), + ]); + await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettle Festival", postIds: ["801", "802", "803", "804", "805", "806", "807"], added: 7, threads: { "807": "806" } }); + await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["808"], added: 1 }); + // A complete read that no longer shows 801: gone from the page. + await recordXTrendingRead(libRoot, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF, postIds: ["802", "803", "804", "805", "806", "807"], added: 0, complete: true }); + for (const name of capture(libRoot, "801", { "shot.png": "SHOT-801", "801_1.jpg": "PICTURE-SHARED", "stray.bin": MARK.stray }, { + mediaOwed: "kept", + error: `media ${MARK.owed}: owed until the post is kept`, + threadError: `thread ${MARK.owed}`, + context: { readAt: "2026-11-18T10:05:00.000Z", quoted: { text: "a quoted post", media: [] } }, + })) await adoptXTrendingMedia(libRoot, { postId: "801", name }); + for (const name of capture(libRoot, "803", { "803_1.jpg": "PICTURE-DROPPED" })) await adoptXTrendingMedia(libRoot, { postId: "803", name }); + for (const name of capture(libRoot, "806", { "806_1.jpg": "PICTURE-SHARED" })) await adoptXTrendingMedia(libRoot, { postId: "806", name }); + await judgeXTrending(libRoot, { by: "agent", set: [{ id: "802", state: "keep" }] }); + await judgeXTrending(libRoot, { + by: "operator", + set: [{ id: "801", state: "keep", note: `why ${MARK.note}` }, { id: "803", state: "drop" }, { id: "804", state: "later" }, { thread: "806", state: "keep" }, { id: "808", state: "keep" }], + }); + await writePostAvailability(trendingDir(libRoot), { + "801": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" }, + "803": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" }, + }); + return libRoot; +} + +function walk(dir: string): string[] { + const out: string[] = []; + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) out.push(...walk(p)); + else out.push(p); + } + return out.sort(); +} +const snapshot = (dir: string) => walk(dir).map((f) => `${path.relative(dir, f)}:${readFileSync(f).toString("latin1")}`); + +async function publish(lib: string, o: { topic?: string; channel?: string; busy?: () => boolean } = {}) { + const ask = { slug: lib, topic: o.topic ?? "kettle-festival", deriveSlug: derive, busy: o.busy ?? IDLE, now: Date.parse("2026-11-18T12:00:00.000Z"), ...(o.channel ? { channel: o.channel } : {}) }; + const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + if (!dry.ok) return { dry, done: dry }; + const done = await publishXTrendingTopic(paths, { ...ask, dryRun: false, confirm: dry.result.confirm, by: "operator" }); + return { dry, done }; +} + +test("the allowlists: a post's unknown field, its library slug and its index-time fields are not copied; a capture's owed and error text neither", () => { + const stored = { ...post("zzlib", "801", "words", { lang: "en", quoted: { platform: "twitter", id: "5", author: "saucer_fan" } }), secretField: "x", forum: { host: "h", threadId: "t" }, isDeleted: true, availability: "deleted" } as unknown as Post; + const out = publishedPostOf(stored, "kettles")!; + assert.deepEqual(Object.keys(out).sort(), ["author", "authorName", "channelSlug", "createdAt", "id", "isReply", "isRepost", "lang", "links", "platform", "quoted", "slug", "text", "uploadDate", "url"]); + assert.deepEqual([out.slug, out.channelSlug], ["kettles/801", "kettles"]); + assert.doesNotMatch(JSON.stringify(out), /zzlib|secretField/); + assert.ok(!PUBLISHED_POST_FIELDS.includes("slug") && !PUBLISHED_POST_FIELDS.includes("channelSlug")); + + const record = { + version: 1, id: "801", url: "u", capturedAt: "t", state: "captured", mediaState: "error", mediaOwed: "kept", error: "e", threadError: "te", unknown: "u", + shot: { name: "shot.png", bytes: 1, sha256: "a" }, + media: [{ name: "801_1.jpg", bytes: 1, sha256: "b", url: "https://pbs.twimg.com/media/x.jpg" }, { name: "../evil", bytes: 1, sha256: "c" }, { name: "801_2.jpg", bytes: 1, sha256: "d" }], + article: { articleId: "9", url: "au", capturedAt: "t", state: "error", blocks: 0, extraction: "by-magic", files: [{ name: "article.json", bytes: 1, sha256: "e" }], error: "ae" }, + } as never; + assert.deepEqual(captureFileNames(record), ["shot.png", "801_1.jpg", "801_2.jpg", "article.json"]); + const there: Record<string, { name: string; bytes: number; sha256: string }> = { "shot.png": { name: "shot.png", bytes: 7, sha256: "S" }, "801_1.jpg": { name: "801_1.jpg", bytes: 9, sha256: "M" } }; + const built = publishedCaptureOf(record, (name) => there[name]); + assert.deepEqual(built, { + version: 1, id: "801", url: "u", capturedAt: "t", state: "captured", + shot: { name: "shot.png", bytes: 7, sha256: "S" }, + mediaState: "error", + media: [{ name: "801_1.jpg", bytes: 9, sha256: "M", url: "https://pbs.twimg.com/media/x.jpg" }], + article: { articleId: "9", url: "au", capturedAt: "t", state: "error", blocks: 0, files: [] }, + }); + + // FIELD BY FIELD (review 1): the context's two posts, a thread shot's redaction and an article's + // extraction are rebuilt from named fields; a key nobody named is not copied. + const rich = { + version: 1, id: "802", url: "u", capturedAt: "t", state: "captured", mediaState: "none", media: [], + thread: { + name: "shot-thread.png", bytes: 1, sha256: "t", parentId: "700", parentHandle: "saucer_fan", parentVerified: true, parentBadge: "gold", parentFrom: "above", libraryNote: "x", + redaction: { applied: true, reason: "private", boxes: [{ what: "avatar", box: { x: 1, y: 2, width: 3, height: 4, z: 9 }, why: "x" }, { what: "everything", box: {} }], secret: "x" }, + }, + article: { articleId: "9", url: "au", capturedAt: "t", state: "captured", blocks: 2, extraction: "structured", files: [], libraryNote: "x" }, + context: { + readAt: "r", topic: "kettles", + quoted: { id: "5", url: "qu", handle: "h", author: "A", verified: true, badge: "blue", date: "d", text: "quoted", media: [{ kind: "image", url: "mu", note: "x" }, { kind: "audio", url: "no" }], judgement: "keep" }, + parent: { text: "parent", media: [], from: "above", note: "x" }, + }, + } as never; + const richBuilt = publishedCaptureOf(rich, (name) => (name === "shot-thread.png" ? { name, bytes: 5, sha256: "T" } : undefined)); + assert.deepEqual(richBuilt, { + version: 1, id: "802", url: "u", capturedAt: "t", state: "captured", mediaState: "none", media: [], + article: { articleId: "9", url: "au", capturedAt: "t", state: "captured", blocks: 2, extraction: "structured", files: [] }, + thread: { + name: "shot-thread.png", bytes: 5, sha256: "T", parentId: "700", parentHandle: "saucer_fan", parentVerified: true, parentBadge: "gold", parentFrom: "above", + redaction: { applied: true, reason: "private", boxes: [{ what: "avatar", box: { x: 1, y: 2, width: 3, height: 4 } }] }, + }, + context: { + readAt: "r", + quoted: { id: "5", url: "qu", handle: "h", author: "A", verified: true, badge: "blue", date: "d", text: "quoted", media: [{ kind: "image", url: "mu" }] }, + parent: { text: "parent", media: [], from: "above" }, + }, + } as never); + assert.doesNotMatch(JSON.stringify(richBuilt), /libraryNote|secret|judgement|kettles|"note"|"why"|"z"/); + // A redaction nobody can read (no known reason) publishes no thread shot's record at all. + const noReason = publishedCaptureOf({ ...(rich as object), thread: { name: "shot-thread.png", bytes: 1, sha256: "t", parentId: "7", parentVerified: false, parentFrom: "reply-to", redaction: { applied: true, reason: "because" } } } as never, (name) => ({ name, bytes: 1, sha256: "T" })); + assert.equal(noReason.thread, undefined); +}); + +test("a dry run writes nothing and says exactly what would be written; the publish is the operator's, in two steps, and waits for a read or a capture", async () => { + const lib = "zzlibrarymarkq7"; + const libRoot = await library(lib); + const before = snapshot(libRoot); + const ask = { slug: lib, topic: "Kettle Festival", deriveSlug: derive, busy: IDLE }; + const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(dry.ok); + const r = dry.result; + assert.deepEqual( + { channel: r.channel, creates: r.creates, kept: r.kept, posts: r.posts, ids: r.ids, already: r.already, files: r.files, bytes: r.bytes, textOnly: r.textOnly, noLongerKept: r.noLongerKept }, + { channel: "kettle-festival", creates: true, kept: 3, posts: 3, ids: ["801", "806", "807"], already: 0, files: 3, bytes: "SHOT-801".length + 2 * "PICTURE-SHARED".length, textOnly: ["807"], noLongerKept: [] }, + ); + assert.match(r.sentence, /^Publishing "Kettle Festival" would make the channel "kettle-festival", on no site, writing 3 posts and 3 files \(36 B\); 0 of the 3 kept posts are there already\. 1 post has no capture yet and is published as its words alone: a later publish adds the files\. The files are copies: the library keeps its own\.$/); + assert.deepEqual(readdirSync(paths.channelsDir), [lib], "no channel was made"); + assert.deepEqual(snapshot(libRoot), before, "a dry run writes nothing in the library either"); + + const busyDry = await publishXTrendingTopic(paths, { ...ask, dryRun: true, busy: () => true }); + assert.ok(busyDry.ok && busyDry.result.inFlight === true && /the publish waits for it/.test(busyDry.result.sentence)); + + for (const by of ["agent", undefined]) { + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, confirm: r.confirm, ...(by ? { by } : {}) }), { ok: false, error: PUBLISH_IS_THE_OPERATORS }); + } + const noConfirm = await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator" }); + assert.ok(!noConfirm.ok && /two steps/.test(noConfirm.error)); + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: "0".repeat(24) }), { ok: false, error: PUBLISH_SET_CHANGED }); + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm, busy: () => true }), { ok: false, error: PUBLISH_WAITS }); + // Queued between the first look and the lock. + let asked = 0; + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm, busy: () => ++asked > 1 }), { ok: false, error: PUBLISH_WAITS }); + // The set changed after the count: a post moved out of the topic. + await moveXTrendingPosts(libRoot, { to: "cups", ids: ["807"], by: "agent" }); + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm }), { ok: false, error: PUBLISH_SET_CHANGED }); + assert.deepEqual(readdirSync(paths.channelsDir), [lib], "every refusal wrote nothing"); + + const none = await publishXTrendingTopic(paths, { ...ask, topic: "spoons", dryRun: true }); + assert.ok(!none.ok && /has no topic "spoons"/.test(none.error)); + const notLib = await publishXTrendingTopic(paths, { ...ask, slug: "nope", dryRun: true }); + assert.ok(!notLib.ok && /No such channel/.test(notLib.error)); + const itself = await publishXTrendingTopic(paths, { ...ask, channel: lib, dryRun: true }); + assert.ok(!itself.ok && /the library itself/.test(itself.error)); + const badSlug = await publishXTrendingTopic(paths, { ...ask, channel: "../x", dryRun: true }); + assert.ok(!badSlug.ok && /not a valid channel slug/.test(badSlug.error)); + await deleteChannel(paths, lib); +}); + +test("THE PIN: the published channel holds the operator's keeps and nothing that names the library, a judgement, a note, a read, a watch or a gone mark; its files are copies", async () => { + const lib = "zzlibrarymarkq7"; + const libRoot = await library(lib); + const libBefore = snapshot(libRoot).filter((l) => !l.startsWith("trending/published.json")); + const { done } = await publish(lib); + assert.ok(done.ok, JSON.stringify(done)); + assert.match(done.result.sentence, /^Publishing "Kettle Festival" made the channel "kettle-festival", on no site, and wrote 3 posts and 3 files/); + assert.match(done.result.sentence, /Adding the channel to a site is a separate step\.$/); + const chan = path.join(paths.channelsDir, "kettle-festival"); + + // An ordinary channel: its config is four plain keys. + assert.deepEqual(JSON.parse(readFileSync(path.join(chan, "config.json"), "utf8")), { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + assert.equal(isSourcelessPostsChannel(await readChannelConfig(paths, "kettle-festival")), true); + // On no site: nothing but the two channels exists in the corpus. + assert.deepEqual(readdirSync(ROOT).sort(), ["channels"]); + + // EXACTLY the operator's keeps: not the agent's keep, the drop, the later, + // the undecided, nor a keep of another topic. + const posts = await readAllPosts(chan); + assert.deepEqual(posts.map((p) => p.id).sort(), ["801", "806", "807"]); + for (const p of posts) assert.deepEqual([p.slug, p.channelSlug], [`kettle-festival/${p.id}`, "kettle-festival"]); + assert.deepEqual(posts.find((p) => p.id === "801")?.engagement, { likes: 3 }); + + // The files: what the capture records name, and not the stray one. + const files = walk(chan).map((f) => path.relative(chan, f)); + assert.deepEqual(files, [ + "config.json", + "posts-archive", + "posts-availability.json", + "posts-media/801/801_1.jpg", + "posts-media/801/capture.json", + "posts-media/801/shot.png", + "posts-media/806/806_1.jpg", + "posts-media/806/capture.json", + "posts/2026-11.jsonl", + ]); + + // NOTHING OF THE LIBRARY, in any file's bytes or name. + const forbidden = [lib, "trending", "xTrending", ...Object.values(MARK), READ_A, READ_B, READ_C, REF.trendId, "judg", "agent", "operator", "gone", "mediaOwed", "owed", "threadError", '"error"', "watch", "membership", "published.json", "media-store", "media-index", "kept", "keep", "topic"]; + for (const f of walk(chan)) { + const hay = `${path.relative(chan, f)}\n${readFileSync(f).toString("latin1")}`; + for (const word of forbidden) assert.ok(!hay.includes(word), `${path.relative(chan, f)} carries "${word}"`); + } + // Every string of every published post record, too (ruling 10). + for (const line of readFileSync(path.join(chan, "posts", "2026-11.jsonl"), "utf8").trim().split("\n")) assert.doesNotMatch(line, new RegExp(lib)); + + // The capture record: an ordinary one, describing the copies. + const cap = JSON.parse(readFileSync(path.join(chan, "posts-media", "801", "capture.json"), "utf8")); + assert.deepEqual(Object.keys(cap).sort(), ["capturedAt", "context", "id", "media", "mediaState", "shot", "state", "url", "version"]); + assert.equal(cap.media[0].bytes, "PICTURE-SHARED".length); + assert.match(cap.media[0].sha256, /^[0-9a-f]{64}$/); + assert.notEqual(cap.media[0].sha256, "0".repeat(64)); + + // What X said of the published posts, and of no other. + assert.deepEqual(await readPostAvailability(chan), { "801": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" } }); + + // COPIES: no published file shares an inode with a library file, and each + // has one name only. + const libInodes = new Set(walk(libRoot).map((f) => lstatSync(f).ino)); + for (const f of walk(chan)) { + const st = lstatSync(f); + assert.equal(st.nlink, 1, `${f} has one name`); + assert.ok(!libInodes.has(st.ino), `${f} is not a library file's inode`); + assert.ok(st.isFile() && !st.isSymbolicLink()); + } + assert.equal(readFileSync(path.join(chan, "posts-media", "806", "806_1.jpg"), "utf8"), "PICTURE-SHARED"); + + // The library: untouched but for its own record of the publish. + assert.deepEqual(snapshot(libRoot).filter((l) => !l.startsWith("trending/published.json")), libBefore); + const made = lstatSync(chan); + assert.deepEqual(await readXTrendingPublished(libRoot), { + "kettle-festival": { + slug: "kettle-festival", firstAt: "2026-11-18T12:00:00.000Z", lastAt: "2026-11-18T12:00:00.000Z", + posts: { "801": "2026-11-18T12:00:00.000Z", "806": "2026-11-18T12:00:00.000Z", "807": "2026-11-18T12:00:00.000Z" }, + // Which directory it made: kept HERE, in the library. Nothing is written into the channel for it. + identity: { ino: made.ino, birthtimeMs: made.birthtimeMs }, + }, + }); +}); + +test("re-publishing adds the newly kept and removes nothing: a post since dropped is reported and stays; a capture that came later is topped up; a renamed topic keeps its channel", async () => { + const lib = "zzlibrarymarkq7"; + const libRoot = path.join(paths.channelsDir, lib); + const chan = path.join(paths.channelsDir, "kettle-festival"); + const again = await publishXTrendingTopic(paths, { slug: lib, topic: "kettle-festival", deriveSlug: derive, busy: IDLE, dryRun: true }); + assert.ok(again.ok); + assert.deepEqual([again.result.creates, again.result.posts, again.result.files, again.result.already], [false, 0, 0, 3]); + assert.equal(again.result.sentence, `Nothing to add: the channel "kettle-festival" already holds the 3 posts the operator kept in "Kettle Festival". 1 post has no capture yet and is published as its words alone: a later publish adds the files.`); + + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "805", state: "keep" }, { id: "801", state: "drop" }] }); + for (const name of capture(libRoot, "807", { "shot.png": "SHOT-807", "807_1.jpg": "PICTURE-807" })) await adoptXTrendingMedia(libRoot, { postId: "807", name }); + const renamed = await renameXTrendingTopic(libRoot, { readInFlight: IDLE, topic: "kettle-festival", title: "Teapots", by: "operator" }); + assert.ok(renamed.ok); + const other = await publishXTrendingTopic(paths, { slug: lib, topic: "kettle-festival", channel: "teapots", deriveSlug: derive, busy: IDLE, dryRun: true }); + assert.ok(!other.ok && /a topic has one channel, fixed at its first publish/.test(other.error)); + + const before801 = snapshot(path.join(chan, "posts-media", "801")); + const { dry, done } = await publish(lib); + assert.ok(dry.ok && done.ok, JSON.stringify(done)); + assert.deepEqual( + [done.result.channel, done.result.creates, done.result.ids, done.result.already, done.result.files, done.result.textOnly, done.result.noLongerKept], + ["kettle-festival", false, ["805"], 2, 2, ["805"], ["801"]], + ); + assert.match(done.result.sentence, /1 post published before is no longer kept: it stays in the channel \(a publish removes nothing\)\./); + assert.deepEqual((await readAllPosts(chan)).map((p) => p.id).sort(), ["801", "805", "806", "807"]); + assert.deepEqual(snapshot(path.join(chan, "posts-media", "801")), before801, "the dropped post's files stay as they were"); + assert.equal(readFileSync(path.join(chan, "posts-media", "807", "807_1.jpg"), "utf8"), "PICTURE-807"); + assert.equal(JSON.parse(readFileSync(path.join(chan, "config.json"), "utf8")).name, "Kettle Festival", "the channel's own name is its own"); +}); + +test("a purge of the library after a publish frees exactly what it would have freed, and the channel's copies still read; deleting either leaves the other whole", async () => { + const lib = "zzlibrarymarkq7"; + const libRoot = path.join(paths.channelsDir, lib); + const chan = path.join(paths.channelsDir, "kettle-festival"); + // The same library, never published. + const twinRoot = await library("zztwinlibrary"); + await judgeXTrending(twinRoot, { by: "operator", set: [{ id: "805", state: "keep" }, { id: "801", state: "drop" }] }); + for (const name of capture(twinRoot, "807", { "shot.png": "SHOT-807", "807_1.jpg": "PICTURE-807" })) await adoptXTrendingMedia(twinRoot, { postId: "807", name }); + await renameXTrendingTopic(twinRoot, { readInFlight: IDLE, topic: "kettle-festival", title: "Teapots", by: "operator" }); + + const purge = async (root: string, slug: string) => { + const dry = await purgeXTrendingDropped(root, { slug, dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + const done = await purgeXTrendingDropped(root, { slug, dryRun: false, confirm: dry.result.confirm, captureInFlight: IDLE }); + assert.ok(done.ok); + const { posts, files, bytes, blobsFreed, blobsKept } = done.result; + return { posts, files, bytes, blobsFreed, blobsKept }; + }; + const chanBefore = snapshot(chan); + const published = await purge(libRoot, lib); + const never = await purge(twinRoot, "zztwinlibrary"); + assert.deepEqual(published, never, "the published copies hold no link to the library's blobs"); + assert.equal(published.posts, 2); + assert.deepEqual(snapshot(chan), chanBefore, "a purge of the library reaches nothing of the channel"); + assert.equal(readFileSync(path.join(chan, "posts-media", "801", "801_1.jpg"), "utf8"), "PICTURE-SHARED"); + + // Deleting the channel leaves the library whole… + const libBefore = snapshot(libRoot); + await deleteChannel(paths, "kettle-festival"); + assert.deepEqual(snapshot(libRoot), libBefore); + // …and its slug, free again, is simply made again with every kept post. + const { done } = await publish(lib); + assert.ok(done.ok && done.result.creates); + assert.deepEqual(done.result.ids, ["805", "806", "807"]); + // Deleting the LIBRARY leaves the published channel whole. + const chanAfter = snapshot(chan); + await deleteChannel(paths, lib); + await deleteChannel(paths, "zztwinlibrary"); + assert.deepEqual(snapshot(chan), chanAfter); + await deleteChannel(paths, "kettle-festival"); +}); + +test("the three-part proof: a slug a stranger holds is refused — never recorded, a source of its own, or posts this topic never published; a renamed channel is left alone", async () => { + const lib = "zzlibrarymarkq7"; + const libRoot = await library(lib); + const ask = { slug: lib, topic: "kettle-festival", deriveSlug: derive, busy: IDLE, dryRun: true }; + + // 1. A channel of that slug that this library never published into. + await createChannel(paths, "kettle-festival", { name: "Somebody's", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/somebody", socialHandle: "somebody" }); + const stranger = await publishXTrendingTopic(paths, ask); + assert.deepEqual(stranger, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("kettle-festival", "this library has no record of publishing into it") }); + // The ask may name another slug. + const elsewhere = await publish(lib, { channel: "Kettles-2026" }); + assert.ok(elsewhere.done.ok && elsewhere.done.result.channel === "Kettles-2026" && elsewhere.done.result.creates); + await deleteChannel(paths, "kettle-festival"); + + // 2. Deleted, then made again BY HAND with an account: a stranger. + await deleteChannel(paths, "Kettles-2026"); + await createChannel(paths, "Kettles-2026", { name: "By hand", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/somebody", socialHandle: "somebody" }); + const byHand = await publishXTrendingTopic(paths, ask); + assert.deepEqual(byHand, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("Kettles-2026", "it is a channel with a source of its own") }); + + // 3. Of the right shape, holding a post this topic never published. + await deleteChannel(paths, "Kettles-2026"); + await createChannel(paths, "Kettles-2026", { name: "Look-alike", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + await writePosts(path.join(paths.channelsDir, "Kettles-2026"), [post("Kettles-2026", "999", "a stranger's post")]); + const lookAlike = await publishXTrendingTopic(paths, ask); + assert.deepEqual(lookAlike, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("Kettles-2026", "it holds 1 post this topic never published") }); + assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "Kettles-2026"))).map((p) => p.id), ["999"], "nothing was appended to it"); + await deleteChannel(paths, "Kettles-2026"); + + // A RENAMED published channel: its directory moved. The record's slug is + // free, so a publish makes that channel again; the renamed one is not + // written to. + const made = await publish(lib); + assert.ok(made.done.ok && made.done.result.creates); + renameSync(path.join(paths.channelsDir, "Kettles-2026"), path.join(paths.channelsDir, "renamed-by-the-operator")); + const renamedBefore = snapshot(path.join(paths.channelsDir, "renamed-by-the-operator")); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "805", state: "keep" }] }); + const after = await publish(lib); + assert.ok(after.done.ok && after.done.result.creates && after.done.result.channel === "Kettles-2026"); + assert.deepEqual(after.done.result.ids, ["801", "805", "806", "807"]); + assert.deepEqual(snapshot(path.join(paths.channelsDir, "renamed-by-the-operator")), renamedBefore); + + // Nothing kept by the operator: nothing to publish (an agent's keep is not one). + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "808", state: "undecided" }] }); + await judgeXTrending(libRoot, { by: "agent", set: [{ id: "808", state: "keep" }] }); + const empty = await publishXTrendingTopic(paths, { ...ask, topic: "cups" }); + assert.ok(!empty.ok && /The operator has kept no post in "Cups"/.test(empty.error)); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +// A small library for one question each: topic "Kettle Festival", posts by id. +async function small(lib: string, ids: string[], threads: Record<string, string> = {}): Promise<string> { + const libRoot = path.join(paths.channelsDir, lib); + await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); + await writeXTrendingPosts(libRoot, ids.map((id) => post(lib, id, `words ${id}`, threads[id] ? { isReply: true, threadId: threads[id], replyTo: { platform: "twitter", id: threads[id] } } : {}))); + await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettle Festival", postIds: ids, added: ids.length, threads }); + return libRoot; +} +const ask = (lib: string, channel: string) => ({ slug: lib, topic: "kettle-festival", deriveSlug: () => channel, busy: IDLE, now: Date.parse("2026-11-18T12:00:00.000Z") }); +async function go(lib: string, channel: string) { + const dry = await publishXTrendingTopic(paths, { ...ask(lib, channel), dryRun: true }); + if (!dry.ok) return dry; + return publishXTrendingTopic(paths, { ...ask(lib, channel), dryRun: false, confirm: dry.result.confirm, by: "operator" }); +} + +test("S10: which judgement is in force decides what is published: the operator's entry, own or thread's, outranks an agent's; the operator's own outranks the operator's thread", async () => { + // Thread 911: the OPERATOR dropped the thread; an AGENT kept its reply 912 itself. + // Thread 921: the OPERATOR kept the thread; the OPERATOR dropped its reply 922 itself; 923 has no entry of its own. + const libRoot = await small("zzlibs10", ["911", "912", "921", "922", "923"], { "912": "911", "922": "921", "923": "921" }); + await judgeXTrending(libRoot, { by: "agent", set: [{ id: "912", state: "keep" }] }); + await judgeXTrending(libRoot, { by: "operator", set: [{ thread: "911", state: "drop" }, { thread: "921", state: "keep" }, { id: "922", state: "drop" }] }); + const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs10", "s10-channel"), dryRun: true }); + assert.ok(dry.ok); + // 921 and 923: the operator's thread keep, with no entry of their own. Not 912 (an agent's own keep under + // the operator's thread drop), not 922 (the operator's own drop under the operator's thread keep), not 911. + assert.deepEqual(dry.result.ids, ["921", "923"]); + const done = await go("zzlibs10", "s10-channel"); + assert.ok(done.ok); + assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "s10-channel"))).map((p) => p.id).sort(), ["921", "923"]); + await deleteChannel(paths, "zzlibs10"); + await deleteChannel(paths, "s10-channel"); +}); + +test("S2, S3: the channel must be the very directory this publish made: one made again by hand, even empty and of the same shape, is refused; so is a bare directory of the slug", async () => { + const libRoot = await small("zzlibs2", ["931", "932"]); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "931", state: "keep" }] }); + const chan = path.join(paths.channelsDir, "s2-channel"); + + // S3: a directory of that name with no channel in it: a publish makes a channel only where there is nothing. + mkdirSync(chan, { recursive: true }); + const bare = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); + assert.deepEqual(bare, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "a directory of that name is there, with no channel in it") }); + rmSync(chan, { recursive: true }); + + const first = await go("zzlibs2", "s2-channel"); + assert.ok(first.ok && first.result.creates); + const made = lstatSync(chan); + const record = (await readXTrendingPublished(libRoot))["kettle-festival"]; + assert.deepEqual(record.identity, { ino: made.ino, birthtimeMs: made.birthtimeMs }); + assert.equal(record.pending, undefined); + // The channel's own config rewritten (as any edit of it does): still this publish's channel. + writeFileSync(path.join(chan, "config.json.tmp"), readFileSync(path.join(chan, "config.json"))); + renameSync(path.join(chan, "config.json.tmp"), path.join(chan, "config.json")); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "932", state: "keep" }] }); + const second = await go("zzlibs2", "s2-channel"); + assert.ok(second.ok && !second.result.creates, JSON.stringify(second)); + + // DELETED, THEN MADE AGAIN BY HAND: the same slug, the same shape, EMPTY. Not this publish's. + await deleteChannel(paths, "s2-channel"); + await createChannel(paths, "s2-channel", { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + const again = lstatSync(chan); + assert.ok(again.ino !== made.ino || again.birthtimeMs !== made.birthtimeMs, "the test's file system tells the two directories apart"); + const refused = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); + assert.deepEqual(refused, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "it is not the channel this publish made: that one was removed, and this one was made since") }); + assert.deepEqual(readdirSync(chan), ["config.json"], "nothing was added to it"); + + // A record that says neither which directory nor that a publish was cut: refused. + await mutateXTrendingPublished(libRoot, (all) => { delete all["kettle-festival"].identity; return { write: true, result: undefined }; }); + const unsaid = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); + assert.deepEqual(unsaid, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "the library's record does not say which channel it made") }); + + // A PUBLISH CUT after it made the channel and before it recorded which: `pending`, and the channel holds + // nothing. The next publish takes it up and records the directory. + await mutateXTrendingPublished(libRoot, (all) => { all["kettle-festival"].pending = true; return { write: true, result: undefined }; }); + const resumed = await go("zzlibs2", "s2-channel"); + assert.ok(resumed.ok && !resumed.result.creates, JSON.stringify(resumed)); + assert.deepEqual((await readAllPosts(chan)).map((p) => p.id).sort(), ["931", "932"]); + const after = (await readXTrendingPublished(libRoot))["kettle-festival"]; + assert.deepEqual([after.identity, after.pending], [{ ino: again.ino, birthtimeMs: again.birthtimeMs }, undefined]); + await deleteChannel(paths, "zzlibs2"); + await deleteChannel(paths, "s2-channel"); +}); + +test("S4: the dry run names the sites the channel is on, and the confirm covers it: put on a site after the count, the publish is refused", async () => { + const libRoot = await small("zzlibs4", ["941", "942"]); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "941", state: "keep" }] }); + const first = await go("zzlibs4", "s4-channel"); + assert.ok(first.ok); + assert.deepEqual(first.result.sites, []); + assert.match(first.result.sentence, /made the channel "s4-channel", on no site,/); + + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "942", state: "keep" }] }); + const offSite = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: true }); + assert.ok(offSite.ok); + assert.deepEqual(offSite.result.sites, []); + // The operator's separate act, made between the count and the press. + const site = (siteId: string, channels: string[]) => ({ + siteId, siteTitle: siteId, siteDescription: "fixture", headerTitle: siteId, homeTagline: "", socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], defaultGroupId: "default", + channels: channels.map((slug) => ({ slug, groupId: "default" })), siteUrl: `https://${siteId}.example.test`, archives: false, + }); + await writeSite(site("kettle-site", ["s4-channel"]) as never, paths); + assert.deepEqual(await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: false, confirm: offSite.result.confirm, by: "operator" }), { ok: false, error: PUBLISH_SET_CHANGED }); + assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "s4-channel"))).map((p) => p.id), ["941"], "nothing was written"); + + const onSite = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: true }); + assert.ok(onSite.ok); + assert.deepEqual(onSite.result.sites, ["kettle-site"]); + assert.notEqual(onSite.result.confirm, offSite.result.confirm); + assert.equal( + onSite.result.sentence, + 'Publishing "Kettle Festival" would add to the channel "s4-channel" writing 1 post and 0 files (0 B); 1 of the 2 kept posts is there already. ' + + "THIS CHANNEL IS ON THE SITE kettle-site: this post goes public at its next build. " + + "2 posts have no capture yet and are published as their words alone: a later publish adds the files.", + ); + const done = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: false, confirm: onSite.result.confirm, by: "operator" }); + assert.ok(done.ok); + await deleteChannel(paths, "zzlibs4"); + await deleteChannel(paths, "s4-channel"); + rmSync(paths.sitesDir, { recursive: true, force: true }); +}); + +test("S5: the dry run says how many of the posts to publish were moved into the topic, and by whom", async () => { + const libRoot = await small("zzlibs5", ["951", "952", "953", "954"]); + await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["955"], added: 0 }); + await moveXTrendingPosts(libRoot, { to: "cups", ids: ["952", "953", "954"], by: "operator" }); + // Back into the topic: two by an agent, one by the operator. 951 never moved. + await moveXTrendingPosts(libRoot, { to: "kettle-festival", ids: ["952", "953"], by: "agent" }); + await moveXTrendingPosts(libRoot, { to: "kettle-festival", ids: ["954"], by: "operator" }); + await judgeXTrending(libRoot, { by: "operator", set: ["951", "952", "953", "954"].map((id) => ({ id, state: "keep" as const })) }); + const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs5", "s5-channel"), dryRun: true }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.movedIn, [{ id: "952", by: "agent", from: "cups" }, { id: "953", by: "agent", from: "cups" }, { id: "954", by: "operator", from: "cups" }]); + assert.match(dry.result.sentence, / 3 posts to publish were moved into this topic: 2 by an agent, 1 by the operator\./); + // Once published they are not "to publish" any more. + const done = await go("zzlibs5", "s5-channel"); + assert.ok(done.ok); + const again = await publishXTrendingTopic(paths, { ...ask("zzlibs5", "s5-channel"), dryRun: true }); + assert.ok(again.ok); + assert.deepEqual(again.result.movedIn, []); + await deleteChannel(paths, "zzlibs5"); + await deleteChannel(paths, "s5-channel"); +}); + +test("S8: a file whose bytes are no longer what its capture recorded is not published, is reported, and gets no new digest; an interrupted copy's temp files are swept", async () => { + const libRoot = await small("zzlibs8", ["961"]); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "961", state: "keep" }] }); + capture(libRoot, "961", { "shot.png": "SHOT-961", "961_1.jpg": "PICTURE-961", "961_2.jpg": "PICTURE-TWO" }); + // After the capture, one picture's bytes changed under the library. + writeFileSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"), "NOT WHAT WAS CAPTURED"); + const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs8", "s8-channel"), dryRun: true }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.mismatched, [{ id: "961", name: "961_2.jpg" }]); + assert.equal(dry.result.files, 2); + assert.equal(dry.result.bytes, "SHOT-961".length + "PICTURE-961".length); + assert.match(dry.result.sentence, / 1 file no longer matches the digest its capture recorded and is not copied \(961\/961_2\.jpg\)\./); + const done = await go("zzlibs8", "s8-channel"); + assert.ok(done.ok); + const dir = path.join(paths.channelsDir, "s8-channel", "posts-media", "961"); + assert.deepEqual(readdirSync(dir).sort(), ["961_1.jpg", "capture.json", "shot.png"]); + const cap = JSON.parse(readFileSync(path.join(dir, "capture.json"), "utf8")); + assert.deepEqual(cap.media.map((m: { name: string; sha256: string }) => [m.name, m.sha256]), [["961_1.jpg", sha("PICTURE-961")]], "no record, and no digest, of the file that was not copied"); + assert.doesNotMatch(JSON.stringify(cap), /961_2|NOT WHAT/); + + // The bytes put right: the next publish copies it. Temp names an interrupted copy left are swept; nothing else is. + writeFileSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"), "PICTURE-TWO"); + writeFileSync(path.join(dir, ".publish-0123456789ab.part"), "half a copy"); + writeFileSync(path.join(dir, ".publish-notours.part"), "somebody else's"); + const fixed = await go("zzlibs8", "s8-channel"); + assert.ok(fixed.ok); + assert.deepEqual(fixed.result.mismatched, []); + assert.deepEqual(readdirSync(dir).sort(), [".publish-notours.part", "961_1.jpg", "961_2.jpg", "capture.json", "shot.png"]); + assert.equal(readFileSync(path.join(dir, "961_2.jpg"), "utf8"), "PICTURE-TWO"); + assert.ok(existsSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"))); + await deleteChannel(paths, "zzlibs8"); + await deleteChannel(paths, "s8-channel"); +}); diff --git a/common/controller/publishXTrending.ts b/common/controller/publishXTrending.ts @@ -0,0 +1,760 @@ +// PUBLISHING A TOPIC OF AN X TRENDING LIBRARY (lane x-trending-publish, +// slice 4): the topic's posts whose judgement IN FORCE is KEEP BY THE +// OPERATOR — their own entry, or their thread's — are materialised into an +// ORDINARY posts channel. An agent's keep is a suggestion and is not +// published; nor is a post marked later, dropped or undecided. +// +// THE LIBRARY STAYS BEHIND EVERY DOOR; THE CHANNEL IS AN ORDINARY CHANNEL, on +// NO site until the operator adds it to one (a separate, existing act). The +// channel carries NO mark of where it came from: +// +// posts each record REBUILT from an explicit allowlist of fields +// (PUBLISHED_POST_FIELDS), with `slug` and `channelSlug` the +// channel's — a stored library post carries the library's slug +// in both. A field not on the list is not copied. +// captures `posts-media/<id>/`: the files the capture record NAMES (the +// shot, the thread shot, the media, an article's files) — never +// a directory listing — and a record rebuilt from an allowlist +// too, without what is the library's alone (`mediaOwed`, and +// the error text of a half that is owed). +// sidecar the published posts' availability (X said "deleted") only. +// +// Never the judgements, a note, the reads, the raw capture, the watch, a +// "gone from the page" mark, or who decided. +// +// FILES ARE COPIED, NEVER LINKED. A library's media is hardlinked to its +// store, and the purge frees a blob only when nothing else links to it +// (lib/xTrending/mediaStore.ts): a hardlink into the channel would keep +// every blob for ever and make the purge's count untrue, and library and +// channel would share one inode. A copy (`COPYFILE_FICLONE`: shared extents +// where the file system can, a NEW inode always) means a purge of the library +// and a delete of the channel can neither reach the other's bytes. +// +// "MADE BY THIS PUBLISH" is the library's record (lib/xTrending/published.ts) +// and the channel itself — a PROOF IN FOUR PARTS, asked before a byte is +// appended to a channel that exists: +// 1. the record names this slug for this topic; +// 2. the channel still has the shape this publish gives one (an X posts +// channel with no account, search or page: lib/sourcelessPosts.ts); +// 3. every post the channel holds is one the record says was published; +// 4. it is the very DIRECTORY this publish made (its inode and birth time, +// kept in the record): a channel deleted and made again by hand, even of +// the same shape and empty, is another one. +// A channel that fails it is refused; a slug that is free is simply made +// (again), and only where no directory of that name is left. +// +// TWO STEPS, AND THE SECOND IS THE OPERATOR'S. A dry run writes nothing and +// answers exactly what would be written (the slug, posts, files, bytes) with +// `confirm`, a digest of the library, the topic, the slug, the exact posts +// and the exact files. The publish carries it and `by: "operator"`; if the +// set changed in between it is refused and nothing is written — read again +// inside the media index's lock, immediately before the first write. +// +// REFUSED WHILE A READ, A REPARSE OR A CAPTURE OF THE LIBRARY IS QUEUED OR +// RUNNING (the caller answers that from its job registry): a read can change +// the membership the digest was computed over, and a capture writes the +// directories this copies from, outside the lock. +// +// RE-PUBLISHING ADDS AND REMOVES NOTHING: newly kept posts are added; a post +// published before and no longer kept is REPORTED (`noLongerKept`) and left; +// a file already in the channel is never overwritten; a post published as +// text before its capture existed gets its files at the next publish. +// +// SERVER-ONLY (node:fs). + +import { createHash, randomBytes } from "node:crypto"; +import { constants as FS } from "node:fs"; +import { copyFile, lstat, mkdir, readdir, realpath, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { withJsonFileLock } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { parsePost, postSlug, type Post, type PostAvailabilityMap } from "../lib/posts"; +import { readPostAvailability, readSeenPostIds, writePostAvailability, writePosts } from "../lib/posts-server"; +import { isSourcelessPostsChannel } from "../lib/sourcelessPosts"; +import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "../lib/xTrending/config"; +import { xTrendingMediaIndexPath } from "../lib/xTrending/mediaStore"; +import { mutateXTrendingPublished, readXTrendingPublished, type XTrendingPublishedIdentity, type XTrendingPublishedTopic } from "../lib/xTrending/published"; +import { removeMediaFile } from "../lib/mediaTier-server"; +import { listSites } from "../lib/site"; +import { siteCitableChannelSlugs } from "../lib/siteSchema"; +import { + listXTrending, + readXTrendingMembership, + readXTrendingPosts, + readXTrendingTopics, + resolveXTrendingTopic, + xTrendingPostsMediaDir, + xTrendingPostsRoot, +} from "../lib/xTrending/store"; +import { + fileDigest, + postCaptureDir, + postsMediaDir, + readPostCapture, + writePostCapture, + type ArticleCaptureRecord, + type CapturedFile, + type PostCaptureRecord, + type PostContextPost, + type ThreadCaptureRecord, +} from "../social/postCapture"; +import { channelExists, createChannel, isValidChannelSlug, readChannelConfig } from "./channels"; + +// ── the allowlists ───────────────────────────────────────────────────────── + +// EVERY FIELD OF A POST, DECIDED: true = copied into the published record. +// `satisfies Record<keyof Post, boolean>` makes a NEW field of Post a compile +// error here until somebody decides it — and it is not copied until then. +const POST_FIELDS = { + id: true, + // Rewritten, never copied: the library's slug is in both. + slug: false, + channelSlug: false, + author: true, + authorName: true, + createdAt: true, + uploadDate: true, + text: true, + url: true, + platform: true, + lang: true, + threadId: true, + replyTo: true, + quoted: true, + repostOf: true, + isReply: true, + isRepost: true, + links: true, + mediaCount: true, + media: true, + engagement: true, + // Not an X post's. + forum: false, + page: false, + // Derived at index time from the availability sidecar, never stored. + isDeleted: false, + availability: false, + availabilityCheckedAt: false, +} as const satisfies Record<keyof Post, boolean>; + +export const PUBLISHED_POST_FIELDS: readonly string[] = Object.entries(POST_FIELDS) + .filter(([, copied]) => copied) + .map(([key]) => key); + +// A library post as the channel's own record, or null when it is not a post. +export function publishedPostOf(stored: Post, channel: string): Post | null { + const raw: Record<string, unknown> = {}; + for (const key of PUBLISHED_POST_FIELDS) { + const value = (stored as unknown as Record<string, unknown>)[key]; + if (value !== undefined) raw[key] = value; + } + raw.channelSlug = channel; + raw.slug = postSlug(channel, stored.id); + // parsePost is the posts store's own allowlist, one level down (a ref's + // and an engagement's keys). + return parsePost(raw); +} + +const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/; + +function capturedFile(f: CapturedFile | undefined): CapturedFile | undefined { + if (!f || typeof f !== "object" || typeof f.name !== "string" || !SAFE_NAME.test(f.name)) return undefined; + return { + name: f.name, + bytes: Number(f.bytes) || 0, + sha256: typeof f.sha256 === "string" ? f.sha256 : "", + ...(typeof f.url === "string" && f.url ? { url: f.url } : {}), + }; +} + +// The files a capture record names, in a fixed order: what a publish copies. +export function captureFileNames(record: PostCaptureRecord): string[] { + const names = [ + record.shot?.name, + record.thread?.name, + ...(Array.isArray(record.media) ? record.media.map((m) => m?.name) : []), + ...(Array.isArray(record.article?.files) ? record.article!.files.map((f) => f?.name) : []), + ]; + return [...new Set(names.filter((n): n is string => typeof n === "string" && SAFE_NAME.test(n) && n !== "capture.json"))]; +} + +// A library capture's record as an ordinary channel's: an allowlist, and of +// the files only those `has` says are in the channel. NOT COPIED: `mediaOwed` +// ("owed until the post is kept" is the library's word), `error` and +// `threadError` (a half the library still owes), and an article's `error`. +export function publishedCaptureOf(record: PostCaptureRecord, has: (name: string) => CapturedFile | undefined): PostCaptureRecord { + const file = (f: CapturedFile | undefined) => { + const clean = capturedFile(f); + const there = clean ? has(clean.name) : undefined; + return clean && there ? { ...clean, bytes: there.bytes, sha256: there.sha256 } : undefined; + }; + const shot = file(record.shot); + const media = (Array.isArray(record.media) ? record.media : []).map(file).filter((f): f is CapturedFile => !!f); + const threadFile = file(record.thread); + const a = record.article; + const article: ArticleCaptureRecord | undefined = + a && typeof a === "object" && typeof a.articleId === "string" && typeof a.url === "string" + ? { + articleId: a.articleId, + url: a.url, + capturedAt: a.capturedAt, + state: a.state, + ...(typeof a.title === "string" ? { title: a.title } : {}), + blocks: Number(a.blocks) || 0, + ...(a.extraction === "structured" || a.extraction === "fallback" ? { extraction: a.extraction } : {}), + files: (Array.isArray(a.files) ? a.files : []).map(file).filter((f): f is CapturedFile => !!f), + ...(a.trimmed ? { trimmed: true } : {}), + } + : undefined; + const ctx = record.context; + const quoted = contextPostOf(ctx?.quoted); + const parent = contextPostOf(ctx?.parent); + const parentFrom = (ctx?.parent as { from?: unknown } | undefined)?.from; + const redaction = threadFile && record.thread ? redactionOf(record.thread.redaction) : undefined; + return { + version: 1, + id: record.id, + url: record.url, + capturedAt: record.capturedAt, + state: record.state, + ...(record.sensitive ? { sensitive: true } : {}), + ...(shot ? { shot } : {}), + ...(shot && (record.shotScope === "item" || record.shotScope === "page") ? { shotScope: record.shotScope } : {}), + ...(shot && record.trimmed ? { trimmed: true } : {}), + mediaState: record.mediaState, + media, + ...(article ? { article } : {}), + ...(threadFile && record.thread && redaction + ? { + thread: { + ...threadFile, + parentId: String(record.thread.parentId), + ...(typeof record.thread.parentHandle === "string" ? { parentHandle: record.thread.parentHandle } : {}), + ...(typeof record.thread.parentAuthor === "string" ? { parentAuthor: record.thread.parentAuthor } : {}), + parentVerified: record.thread.parentVerified === true, + ...(BADGES.includes(record.thread.parentBadge as never) ? { parentBadge: record.thread.parentBadge } : {}), + parentFrom: record.thread.parentFrom === "above" ? "above" : "reply-to", + redaction, + }, + } + : {}), + ...(typeof record.threadNone === "string" ? { threadNone: record.threadNone } : {}), + ...(ctx && typeof ctx === "object" && typeof ctx.readAt === "string" + ? { + context: { + readAt: ctx.readAt, + ...(quoted ? { quoted } : {}), + ...(parent ? { parent: { ...parent, from: parentFrom === "above" ? ("above" as const) : ("reply-to" as const) } } : {}), + }, + } + : {}), + }; +} + +const BADGES = ["blue", "gold", "grey", "other"] as const; +const REDACTION_REASONS = ["private", "blue-check", "verified", "self", "off", "forced"] as const; +const REDACTED_WHAT = ["avatar", "name", "user-name", "mention"] as const; + +// A CONTEXT POST, FIELD BY FIELD (review 1): the quoted post or the parent as +// the capture read it off the page. A key this does not name is not copied. +function contextPostOf(raw: unknown): PostContextPost | undefined { + if (!raw || typeof raw !== "object") return undefined; + const r = raw as Record<string, unknown>; + if (typeof r.text !== "string") return undefined; + const media = (Array.isArray(r.media) ? r.media : []) + .filter((m): m is { kind: "image" | "video"; url: string } => !!m && typeof m === "object" && (m.kind === "image" || m.kind === "video") && typeof m.url === "string") + .map((m) => ({ kind: m.kind, url: m.url })); + return { + ...(typeof r.id === "string" ? { id: r.id } : {}), + ...(typeof r.url === "string" ? { url: r.url } : {}), + ...(typeof r.handle === "string" ? { handle: r.handle } : {}), + ...(typeof r.author === "string" ? { author: r.author } : {}), + ...(typeof r.verified === "boolean" ? { verified: r.verified } : {}), + ...(BADGES.includes(r.badge as never) ? { badge: r.badge as PostContextPost["badge"] } : {}), + ...(typeof r.date === "string" ? { date: r.date } : {}), + text: r.text, + media, + }; +} + +// A thread shot's redaction, field by field: whether, why, and the boxes. +function redactionOf(raw: unknown): ThreadCaptureRecord["redaction"] | undefined { + if (!raw || typeof raw !== "object") return undefined; + const r = raw as Record<string, unknown>; + if (!REDACTION_REASONS.includes(r.reason as never)) return undefined; + const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); + const boxes = (Array.isArray(r.boxes) ? r.boxes : []) + .filter((b): b is { what: (typeof REDACTED_WHAT)[number]; box: Record<string, unknown> } => !!b && typeof b === "object" && REDACTED_WHAT.includes(b.what as never) && !!b.box && typeof b.box === "object") + .map((b) => ({ what: b.what, box: { x: num(b.box.x), y: num(b.box.y), width: num(b.box.width), height: num(b.box.height) } })); + return { applied: r.applied === true, reason: r.reason as ThreadCaptureRecord["redaction"]["reason"], boxes }; +} + +// ── the ask and the answer ───────────────────────────────────────────────── + +export type PublishXTrendingAsk = { + // The library, and its topic (id, a merged id, or its name). + slug: string; + topic: string; + // The channel's slug, for a topic never published (a published topic's is + // fixed). Absent: `deriveSlug` of the topic's title. + channel?: string; + deriveSlug: (title: string) => string; + dryRun: boolean; + confirm?: string; + by?: unknown; + // A read, a reparse or a capture of this library queued or running + // (required, so no door can forget it). + busy: () => boolean | Promise<boolean>; + now?: number; +}; + +export type PublishXTrendingResult = { + dryRun: boolean; + library: string; + topic: { id: string; title: string }; + // The channel the posts go into, and whether this publish makes it. + channel: string; + creates: boolean; + // THE SITES THE CHANNEL IS ALREADY ON (review 1 S4): what is added to it + // goes public at each one's next build. Empty for a channel on no site. + sites: string[]; + // The topic's posts kept by the operator; of them, the ones to add (`ids`) + // and the ones the channel already holds. + kept: number; + posts: number; + ids: string[]; + already: number; + // Of the posts to add, those somebody MOVED into this topic (review 1 S5): + // an agent may move posts, and a move changes what a publish takes. + movedIn: Array<{ id: string; by: "agent" | "operator"; from: string }>; + // Files to copy and their size (media, shots, an article's files). + files: number; + bytes: number; + // Files whose bytes no longer match the digest their capture recorded + // (review 1 S8): not copied, and no new digest is written for them. + mismatched: Array<{ id: string; name: string }>; + // Kept posts with no capture yet: published as their words alone; a later + // publish adds their files. + textOnly: string[]; + // Published before and no longer kept by the operator: reported, left. + noLongerKept: string[]; + inFlight?: true; + confirm: string; + sentence: string; +}; + +export const PUBLISH_IS_THE_OPERATORS = + `Publishing a topic is the operator's press: an agent may ask for the dry run ("dryRun": true), which says what would be written and writes nothing. ` + + `The operator publishes on umtool's Posts library page, or with "by": "operator".`; + +export const PUBLISH_WAITS = "A read or a capture of this library is queued or running: publish once it has finished (its job is on /jobs)."; + +export const PUBLISH_SET_CHANGED = + "What would be published has changed since it was counted (a post kept or dropped, a capture finished, a post moved, the channel put on a site): nothing was written. Ask for the dry run again."; + +export const NOT_THIS_PUBLISHS_CHANNEL = (channel: string, why: string) => + `A channel "${channel}" already exists and was not made by publishing this topic (${why}): nothing is added to it. Publish under another slug ("channel"), or remove that channel first.`; + +const n = (k: number, what: string) => `${k} ${what}${k === 1 ? "" : "s"}`; + +export function formatPublishBytes(b: number): string { + if (b < 1024) return `${b} B`; + if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`; + if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`; + return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`; +} + +// The digest a publish must carry: everything it would write, and where it +// would become public. +export function xTrendingPublishConfirm(o: { + library: string; + topic: string; + channel: string; + ids: ReadonlyArray<string>; + files: ReadonlyArray<string>; + sites?: ReadonlyArray<string>; +}): string { + return createHash("sha256") + .update(JSON.stringify([o.library, o.topic, o.channel, [...o.ids].sort(), [...o.files].sort(), [...(o.sites ?? [])].sort()])) + .digest("hex") + .slice(0, 24); +} + +export function publishSentence(r: Omit<PublishXTrendingResult, "sentence">): string { + const would = r.dryRun; + const where = r.creates + ? `${would ? "would make" : "made"} the channel "${r.channel}"${r.sites.length ? "" : ", on no site,"}` + : `${would ? "would add to" : "added to"} the channel "${r.channel}"`; + const what = `${n(r.posts, "post")} and ${n(r.files, "file")} (${formatPublishBytes(r.bytes)})`; + const head = + r.posts === 0 && r.files === 0 && !r.creates + ? `Nothing to add: the channel "${r.channel}" already holds the ${n(r.kept, "post")} the operator kept in "${r.topic.title}".` + : `Publishing "${r.topic.title}" ${where} ${would ? "writing" : "and wrote"} ${what}; ${r.already} of the ${n(r.kept, "kept post")} ${r.already === 1 ? "is" : "are"} there already.`; + // WHERE IT GOES PUBLIC: said first after the count, in so many words. + const sites = + r.sites.length && (r.posts > 0 || r.files > 0) + ? ` THIS CHANNEL IS ON ${r.sites.length === 1 ? "THE SITE" : "THE SITES"} ${r.sites.join(", ")}: ${r.posts === 1 && r.files === 0 ? "this post goes" : "these posts go"} public at ${r.sites.length === 1 ? "its" : "their"} next build.` + : ""; + const agents = r.movedIn.filter((m) => m.by === "agent").length; + const moved = r.movedIn.length + ? ` ${n(r.movedIn.length, "post")} to publish ${r.movedIn.length === 1 ? "was" : "were"} moved into this topic: ${agents} by an agent, ${r.movedIn.length - agents} by the operator.` + : ""; + const text = r.textOnly.length + ? ` ${n(r.textOnly.length, "post")} ${r.textOnly.length === 1 ? "has" : "have"} no capture yet and ${r.textOnly.length === 1 ? "is" : "are"} published as ${r.textOnly.length === 1 ? "its" : "their"} words alone: a later publish adds the files.` + : ""; + const bad = r.mismatched.length + ? ` ${n(r.mismatched.length, "file")} no longer ${r.mismatched.length === 1 ? "matches" : "match"} the digest ${r.mismatched.length === 1 ? "its" : "their"} capture recorded and ${r.mismatched.length === 1 ? "is" : "are"} not copied (${r.mismatched.slice(0, 3).map((m) => `${m.id}/${m.name}`).join(", ")}${r.mismatched.length > 3 ? ", …" : ""}).` + : ""; + const gone = r.noLongerKept.length + ? ` ${n(r.noLongerKept.length, "post")} published before ${r.noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${r.noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).` + : ""; + const copies = r.files > 0 ? " The files are copies: the library keeps its own." : ""; + const site = r.creates && !would && r.sites.length === 0 ? " Adding the channel to a site is a separate step." : ""; + const waits = r.inFlight ? " A read or a capture of this library is queued or running: the publish waits for it." : ""; + return `${head}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; +} + +// ── the plan ─────────────────────────────────────────────────────────────── + +type PlannedFile = { id: string; name: string; from: string; to: string; bytes: number; sha256: string }; +type Plan = { + channelRoot: string; + creates: boolean; + // An interrupted publish's channel, holding nothing yet: its directory is + // recorded by this one. + adopts: boolean; + sites: string[]; + kept: string[]; + fresh: Post[]; + movedIn: PublishXTrendingResult["movedIn"]; + already: number; + files: PlannedFile[]; + mismatched: Array<{ id: string; name: string }>; + // Kept posts with a readable capture record. + captured: Map<string, PostCaptureRecord>; + textOnly: string[]; + noLongerKept: string[]; +}; + +type Fail = { ok: false; error: string }; + +async function isRegularFileInside(file: string, root: string): Promise<{ size: number; mtimeMs: number; ino: number } | null> { + const st = await lstat(file).catch(() => null); + if (!st?.isFile()) return null; + const [real, realRoot] = await Promise.all([realpath(file), realpath(root)]); + return real.startsWith(realRoot + path.sep) ? { size: st.size, mtimeMs: st.mtimeMs, ino: st.ino } : null; +} + +// Which directory a channel is, or null when there is none. +async function identityOf(dir: string): Promise<XTrendingPublishedIdentity | null> { + const st = await lstat(dir).catch(() => null); + return st?.isDirectory() ? { ino: st.ino, birthtimeMs: st.birthtimeMs } : null; +} + +// The same directory: the inode, and the birth time where the file system +// keeps one (an inode number is reused once its directory is gone; a birth +// time is not. A file system that keeps none answers 0, and is not asked). +function sameIdentity(a: XTrendingPublishedIdentity, b: XTrendingPublishedIdentity): boolean { + if (a.ino !== b.ino) return false; + return a.birthtimeMs > 0 && b.birthtimeMs > 0 ? a.birthtimeMs === b.birthtimeMs : true; +} + +// The digest each file's capture record states, by name (64 hex only). +function recordedDigests(record: PostCaptureRecord): Map<string, string> { + const out = new Map<string, string>(); + const take = (f: CapturedFile | undefined) => { + if (f && typeof f.name === "string" && typeof f.sha256 === "string" && /^[0-9a-f]{64}$/.test(f.sha256)) out.set(f.name, f.sha256); + }; + take(record.shot); + take(record.thread); + for (const f of Array.isArray(record.media) ? record.media : []) take(f); + for (const f of Array.isArray(record.article?.files) ? record.article!.files : []) take(f); + return out; +} + +// The sites whose build would carry this channel: as a member, or as a cited +// channel (its cited posts). +function sitesCarrying(paths: Paths, channel: string): string[] { + return listSites(paths) + .filter((site) => siteCitableChannelSlugs(site).has(channel)) + .map((site) => site.siteId) + .sort(); +} + +// EVERYTHING A PUBLISH WOULD WRITE, READ FROM DISK AS IT STANDS: the channel +// and whether it is this publish's, the sites it is on, the judgements in +// force, the membership (and who moved what), the captures and their bytes. +// Asked for the dry run, again before the write, and AGAIN INSIDE THE MEDIA +// INDEX'S LOCK immediately before the first write, each time from disk: the +// digest's inputs are all read here, so a judgement, a move or a site written +// in between changes it. +async function plan( + paths: Paths, + o: { library: string; libRoot: string; topicId: string; channel: string; record: XTrendingPublishedTopic | undefined; digests: Map<string, string> }, +): Promise<{ ok: true; plan: Plan } | Fail> { + const channelRoot = path.join(paths.channelsDir, o.channel); + const recorded = o.record?.posts; + const here = await identityOf(channelRoot); + const exists = await channelExists(paths, o.channel); + let have = new Set<string>(); + let adopts = false; + // S3: a publish MAKES a channel only where no directory of that name is. + if (!exists && (await lstat(channelRoot).catch(() => null)) !== null) { + return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "a directory of that name is there, with no channel in it") }; + } + if (exists) { + // THE PROOF, in four parts. + if (!o.record || !recorded) return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "this library has no record of publishing into it") }; + const config = await readChannelConfig(paths, o.channel); + if (!isSourcelessPostsChannel(config)) { + return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "it is a channel with a source of its own") }; + } + have = await readSeenPostIds(channelRoot); + const strangers = [...have].filter((id) => !recorded[id]); + if (strangers.length > 0) { + return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, `it holds ${n(strangers.length, "post")} this topic never published`) }; + } + // S2: the very directory this publish made. A channel deleted and made + // again, of the same shape and even empty, is another directory. + if (o.record.identity) { + if (!here || !sameIdentity(o.record.identity, here)) { + return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "it is not the channel this publish made: that one was removed, and this one was made since") }; + } + } else if (o.record.pending && have.size === 0) { + // A publish that was cut after making the channel and before saying + // which directory it was: it holds nothing yet, and is taken up. + adopts = true; + } else { + return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "the library's record does not say which channel it made") }; + } + } + const [listing, stored, membership] = await Promise.all([ + listXTrending(o.libRoot, { topic: o.topicId, ids: true, filter: { state: "keep", by: "operator" } }), + readXTrendingPosts(o.libRoot), + readXTrendingMembership(o.libRoot), + ]); + const byId = new Map(stored.map((p) => [p.id, p])); + // An id becomes a path below: digits, or it is not a post of X's. + const kept = [...(listing.ids ?? [])].filter((id) => /^\d{1,32}$/.test(id)).sort(); + const keptSet = new Set(kept); + const fresh: Post[] = []; + const movedIn: Plan["movedIn"] = []; + const files: PlannedFile[] = []; + const mismatched: Plan["mismatched"] = []; + const captured = new Map<string, PostCaptureRecord>(); + const textOnly: string[] = []; + let already = 0; + const libMedia = xTrendingPostsMediaDir(o.libRoot); + for (const id of kept) { + const post = byId.get(id); + const built = post ? publishedPostOf(post, o.channel) : null; + if (!built) continue; + if (have.has(id)) already++; + else { + fresh.push(built); + const moved = membership[id]?.moved; + if (moved) movedIn.push({ id, by: moved.by, from: moved.from }); + } + const from = postCaptureDir(libMedia, id); + const record = await readPostCapture(from); + if (!record || record.id !== id) { + textOnly.push(id); + continue; + } + captured.set(id, record); + const stated = recordedDigests(record); + const to = postCaptureDir(postsMediaDir(channelRoot), id); + for (const name of captureFileNames(record)) { + if ((await lstat(path.join(to, name)).catch(() => null)) !== null) continue; + const src = path.join(from, name); + const st = await isRegularFileInside(src, o.libRoot); + if (st === null) continue; + // The source's own digest, once per file per publish (three looks). + const key = `${src}\0${st.ino}\0${st.size}\0${st.mtimeMs}`; + let sha256 = o.digests.get(key); + if (!sha256) { + sha256 = (await fileDigest(src)).sha256; + o.digests.set(key, sha256); + } + // S8: what the capture recorded of this file, when it recorded a + // digest. Bytes that are no longer those are not published. + const want = stated.get(name); + if (want && want !== sha256) { + mismatched.push({ id, name }); + continue; + } + files.push({ id, name, from: src, to: path.join(to, name), bytes: st.size, sha256 }); + } + } + const noLongerKept = Object.keys(recorded ?? {}).filter((id) => have.has(id) && !keptSet.has(id)).sort(); + return { + ok: true, + plan: { channelRoot, creates: !exists, adopts, sites: sitesCarrying(paths, o.channel), kept, fresh, movedIn, already, files, mismatched, captured, textOnly, noLongerKept }, + }; +} + +const PART = /^\.publish-[0-9a-f]{12}\.part$/; + +// One file, copied: to a temp name beside its place, checked against the +// digest its source had when it was planned, then renamed. Never a link. +async function copyChecked(f: PlannedFile): Promise<void> { + await mkdir(path.dirname(f.to), { recursive: true }); + const tmp = path.join(path.dirname(f.to), `.publish-${randomBytes(6).toString("hex")}.part`); + try { + await copyFile(f.from, tmp, FS.COPYFILE_FICLONE); + const copy = await fileDigest(tmp); + if (copy.sha256 !== f.sha256 || copy.bytes !== f.bytes) throw new Error(`the copy of ${f.name} (post ${f.id}) does not match its source`); + await rename(tmp, f.to); + } catch (err) { + await rm(tmp, { force: true }); + throw err; + } +} + +// What an interrupted copy left in a capture directory of the channel: its +// own temp names, and nothing else. Under the lock, before a file is copied. +async function sweepParts(dir: string): Promise<void> { + for (const name of await readdir(dir).catch(() => [] as string[])) { + if (PART.test(name)) await removeMediaFile(dir, name); + } +} + +// ── the door ─────────────────────────────────────────────────────────────── + +export async function publishXTrendingTopic( + paths: Paths, + ask: PublishXTrendingAsk, +): Promise<{ ok: true; result: PublishXTrendingResult } | Fail> { + if (ask.by !== undefined && ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; + if (!ask.dryRun && ask.by !== "operator") return { ok: false, error: PUBLISH_IS_THE_OPERATORS }; + if (!ask.dryRun && (typeof ask.confirm !== "string" || !ask.confirm)) { + return { ok: false, error: `Publishing takes two steps: ask with "dryRun": true first, then send its "confirm" back.` }; + } + if (!isValidChannelSlug(ask.slug)) return { ok: false, error: `"${ask.slug}" is not a valid channel slug` }; + const config = await readChannelConfig(paths, ask.slug); + if (!config) return { ok: false, error: `No such channel: ${ask.slug}` }; + if (!isXTrendingChannel(config)) return { ok: false, error: NOT_AN_X_TRENDING_LIBRARY(ask.slug) }; + const libRoot = path.join(paths.channelsDir, ask.slug); + const topics = await readXTrendingTopics(libRoot); + const topic = resolveXTrendingTopic(topics, ask.topic); + if (!topic) return { ok: false, error: `${ask.slug} has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"})` }; + + const first0 = (await readXTrendingPublished(libRoot))[topic.id]; + if (first0 && ask.channel !== undefined && ask.channel !== first0.slug) { + return { ok: false, error: `"${topic.title}" is published into the channel "${first0.slug}": a topic has one channel, fixed at its first publish.` }; + } + const channel = first0?.slug ?? ask.channel ?? ask.deriveSlug(topic.title); + if (!isValidChannelSlug(channel)) { + return { ok: false, error: `"${channel}" is not a valid channel slug: name the channel ("channel": letters, digits, ".", "_" and "-").` }; + } + if (channel === ask.slug) return { ok: false, error: `"${channel}" is the library itself: a topic is published into a channel of its own.` }; + + const digests = new Map<string, string>(); + // The record is read with each look: never the copy read above. + const look = async () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, record: (await readXTrendingPublished(libRoot))[topic.id], digests }); + const digest = (p: Plan) => + xTrendingPublishConfirm({ library: ask.slug, topic: topic.id, channel, ids: p.fresh.map((x) => x.id), files: p.files.map((f) => `${f.id}/${f.name}`), sites: p.sites }); + const answer = (p: Plan, dryRun: boolean, inFlight: boolean): PublishXTrendingResult => { + const r: Omit<PublishXTrendingResult, "sentence"> = { + dryRun, + library: ask.slug, + topic: { id: topic.id, title: topic.title }, + channel, + creates: p.creates, + sites: p.sites, + kept: p.kept.length, + posts: p.fresh.length, + ids: p.fresh.map((x) => x.id), + already: p.already, + movedIn: p.movedIn, + files: p.files.length, + bytes: p.files.reduce((a, f) => a + f.bytes, 0), + mismatched: p.mismatched, + textOnly: p.textOnly, + noLongerKept: p.noLongerKept, + ...(inFlight ? { inFlight: true as const } : {}), + confirm: digest(p), + }; + return { ...r, sentence: publishSentence(r) }; + }; + + const first = await look(); + if (!first.ok) return first; + if (first.plan.kept.length === 0) { + return { ok: false, error: `The operator has kept no post in "${topic.title}": there is nothing to publish. (An agent's keep is a suggestion and is not published.)` }; + } + if (ask.dryRun) return { ok: true, result: answer(first.plan, true, await ask.busy()) }; + if (digest(first.plan) !== ask.confirm) return { ok: false, error: PUBLISH_SET_CHANGED }; + if (await ask.busy()) return { ok: false, error: PUBLISH_WAITS }; + + const at = new Date(ask.now ?? Date.now()).toISOString(); + // Inside the media index's lock: no purge and no media adoption of this + // library runs beside the copy. + return withJsonFileLock(xTrendingMediaIndexPath(libRoot), async () => { + // THE JUDGEMENTS, THE MEMBERSHIP, THE CAPTURES, THE RECORD AND THE SITES, + // READ AGAIN HERE: what is written is what this look finds, and it must + // be what the operator was shown. + const again = await look(); + if (!again.ok) return again; + const p = again.plan; + if (digest(p) !== ask.confirm) return { ok: false, error: PUBLISH_SET_CHANGED }; + if (await ask.busy()) return { ok: false, error: PUBLISH_WAITS }; + + // 1. The record FIRST: the slug, and every post about to be written. A + // channel about to be made has no directory to name yet: `pending`. + await mutateXTrendingPublished(libRoot, (all) => { + const have: XTrendingPublishedTopic = all[topic.id] ?? { slug: channel, firstAt: at, lastAt: at, posts: {} }; + for (const post of p.fresh) have.posts[post.id] ??= at; + have.lastAt = at; + if (p.creates) { + delete have.identity; + have.pending = true; + } + all[topic.id] = have; + return { write: true, result: undefined }; + }); + // 2. The channel, through its own writer: on no site. Then WHICH + // DIRECTORY it is, into the record. + if (p.creates) await createChannel(paths, channel, { name: topic.title, handling: "transcribe", sourceKind: "social", platform: "twitter" }); + if (p.creates || p.adopts) { + const made = await identityOf(p.channelRoot); + if (!made) return { ok: false, error: `The channel "${channel}" could not be made.` }; + await mutateXTrendingPublished(libRoot, (all) => { + const have = all[topic.id]; + if (!have) return { write: false, result: undefined }; + have.identity = made; + delete have.pending; + return { write: true, result: undefined }; + }); + } + // 3. The posts, through the posts store's writer. + await writePosts(p.channelRoot, p.fresh); + // 4. The files (an interrupted copy's temp names swept first), then each + // capture's record. + for (const id of p.captured.keys()) await sweepParts(postCaptureDir(postsMediaDir(p.channelRoot), id)); + for (const f of p.files) await copyChecked(f); + for (const [id, source] of p.captured) { + const dir = postCaptureDir(postsMediaDir(p.channelRoot), id); + const there = new Map<string, CapturedFile>(); + for (const name of captureFileNames(source)) { + const st = await stat(path.join(dir, name)).catch(() => null); + if (st?.isFile()) there.set(name, { name, ...(await fileDigest(path.join(dir, name))) }); + } + const existing = await readPostCapture(dir); + const next = publishedCaptureOf(source, (name) => there.get(name)); + if (!existing || JSON.stringify(existing) !== JSON.stringify(next)) await writePostCapture(dir, next); + } + // 5. What X said of them ("deleted"), and nothing else of the sidecar. + const [libAvail, chanAvail] = await Promise.all([readPostAvailability(xTrendingPostsRoot(libRoot)), readPostAvailability(p.channelRoot)]); + const merged: PostAvailabilityMap = { ...chanAvail }; + let changed = false; + for (const id of p.kept) { + const rec = libAvail[id]; + if (!rec || (merged[id] && merged[id].checkedAt >= rec.checkedAt)) continue; + merged[id] = { availability: rec.availability, checkedAt: rec.checkedAt, ...(rec.history ? { history: rec.history.map((h) => ({ availability: h.availability, at: h.at })) } : {}) }; + changed = true; + } + if (changed) await writePostAvailability(p.channelRoot, merged); + return { ok: true as const, result: answer(p, false, false) }; + }); +} diff --git a/common/controller/sourcelessPosts.test.ts b/common/controller/sourcelessPosts.test.ts @@ -0,0 +1,152 @@ +// A POSTS CHANNEL WITH NO SOURCE — posts published from a private library +// (lane x-trending-publish) — MAKES NO REQUEST ANYWHERE: every path that +// would fetch, capture or check it refuses it by name with one sentence, and +// every list of channels to run leaves it out. No fetcher is resolved, no +// binary spawned, no browser opened (the suite also runs with the network +// refused: lib/noNetwork.mjs). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/sourcelessPosts.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { chmod, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "sourceless-posts-")); +const TOUCHED = path.join(ROOT, "a-binary-ran"); +const BIN = path.join(ROOT, "fake-bin.mjs"); +await writeFile(BIN, `#!/usr/bin/env node\nimport { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(TOUCHED)}, "ran");\n`); +await chmod(BIN, 0o755); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.GALLERY_DL_BIN = BIN; +process.env.YT_DLP_BIN = BIN; + +const { getPaths } = await import("../lib/paths"); +const { writePosts } = await import("../lib/posts-server"); +const { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL, syncSkipForShape } = await import("../lib/sourcelessPosts"); +const { registerSocialFetcher } = await import("../social/fetchers"); +const { createChannel } = await import("./channels"); +const { capturePosts } = await import("./capturePosts"); +const { checkPostAvailability } = await import("./checkPostAvailability"); +const { fetchPosts } = await import("./fetchPosts"); +const { isXPostsChannel, listXRunCandidates, planXRun } = await import("./xRun"); +const { findVideoSourceUrl } = await import("./undownloadedVideos"); +const { recordWebpageUrl } = await import("../publish/findCopy"); +const { planImportPost } = await import("../social/importPost"); +const { defaultWebpageUrl } = await import("../lib/platform"); +const { readChannelConfig } = await import("./channels"); +const paths = getPaths(); +const settings = {} as never; + +// Every fetcher the registry could hand out, replaced by one that counts any +// call made on it. +let fetcherCalls = 0; +const spy = (id: string) => + new Proxy({ id, label: id, platform: "twitter", fields: {} } as Record<string, unknown>, { + get(target, prop) { + if (prop in target || typeof prop === "symbol") return target[prop as string]; + return () => { + fetcherCalls++; + throw new Error(`fetcher ${id}.${String(prop)} was called`); + }; + }, + has: () => true, + }); +for (const id of ["x-gallery-dl", "x-playwright", "bluesky", "x"]) registerSocialFetcher(spy(id) as never); + +const PUBLISHED = { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" } as const; +await createChannel(paths, "kettle-festival", { ...PUBLISHED }); +await createChannel(paths, "teapot-x", { name: "Teapot (X)", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/teapot_news", socialHandle: "teapot_news", postFetcher: "x-gallery-dl" }); +await writePosts(path.join(paths.channelsDir, "kettle-festival"), [ + { id: "801", slug: "kettle-festival/801", channelSlug: "kettle-festival", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "words", url: "https://x.com/teapot_news/status/801", platform: "twitter", isReply: false, isRepost: false, links: [] }, +]); +// The same channel after some hand gave it a fetcher key. +await createChannel(paths, "kettle-keyed", { ...PUBLISHED, postFetcher: "x-gallery-dl" }); +await writePosts(path.join(paths.channelsDir, "kettle-keyed"), [ + { id: "801", slug: "kettle-keyed/801", channelSlug: "kettle-keyed", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "words", url: "https://x.com/teapot_news/status/801", platform: "twitter", isReply: false, isRepost: false, links: [] }, +]); +const SENTENCE = SOURCELESS_POSTS_CHANNEL("kettle-festival"); + +test("the shape: an X posts channel with no account, search, page or marker — and no other", () => { + assert.equal(isSourcelessPostsChannel(PUBLISHED), true); + for (const other of [ + { ...PUBLISHED, url: "https://x.com/teapot_news" }, + { ...PUBLISHED, socialHandle: "teapot_news" }, + { ...PUBLISHED, xSearch: { query: "kettles" } }, + { ...PUBLISHED, xTrending: {} }, + { ...PUBLISHED, platform: "bluesky" }, + { ...PUBLISHED, sourceKind: "video" }, + { ...PUBLISHED, remoteOnly: true }, + { ...PUBLISHED, platform: "webpage", wayback: { targets: [{ url: "https://example.org", match: "exact" }] } }, + null, + ]) { + assert.equal(isSourcelessPostsChannel(other as never), false, JSON.stringify(other)); + } + // A FETCHER KEY IS NOT A SOURCE (review 1 M2): writing one cannot switch the guards off. + assert.equal(isSourcelessPostsChannel({ ...PUBLISHED, postFetcher: "x-gallery-dl" } as never), true); + assert.match(SENTENCE, /^kettle-festival holds posts published from a private library: it has no account to fetch from/); +}); + +test("a direct ask is refused with the sentence: fetch-posts, capture-posts, the availability check, an X run", async () => { + const fetched = await fetchPosts({ paths, slug: "kettle-festival", settings } as never); + assert.deepEqual([fetched.ok, fetched.error, fetched.written], [false, SENTENCE, 0]); + for (const extra of [{}, { full: true }, { limit: 5 }]) { + const r = await fetchPosts({ paths, slug: "kettle-festival", settings, ...extra } as never); + assert.equal(r.error, SENTENCE); + } + for (const extra of [{}, { avatarsOnly: true }, { contextOnly: true }, { force: true, thread: true }]) { + const captured = await capturePosts({ paths, slug: "kettle-festival", settings, ids: ["801"], ...extra } as never); + assert.deepEqual([captured.ok, captured.error, captured.outcomes], [false, SENTENCE, []], JSON.stringify(extra)); + } + for (const mode of ["stale", "all"]) { + const checked = await checkPostAvailability({ paths, slug: "kettle-festival", mode } as never); + assert.deepEqual([checked.ok, checked.error, checked.checked], [false, SENTENCE, 0]); + } + const run = await planXRun(paths, { channels: ["teapot-x", "kettle-festival"] }); + assert.deepEqual(run, { ok: false, error: SENTENCE }); + assert.equal(fetcherCalls, 0, "no fetcher was called"); + assert.equal(existsSync(TOUCHED), false, "no binary was run"); +}); + +test("where channels are listed it is left out, with its reason: an X run's candidates, Sync all", async () => { + assert.equal(isXPostsChannel(PUBLISHED), false); + assert.deepEqual((await listXRunCandidates(paths)).map((c) => c.slug), ["teapot-x"]); + assert.equal(syncSkipForShape(PUBLISHED), "published posts: no account to fetch from"); + assert.equal(syncSkipForShape({ handling: "transcribe" } as never), "no url"); + assert.equal(syncSkipForShape({ url: "https://example.org/c", remoteOnly: true } as never), "remote-only"); + assert.equal(syncSkipForShape({ url: "https://x.com/teapot_news", sourceKind: "social", platform: "twitter" }), null); + assert.equal(fetcherCalls, 0); + assert.equal(existsSync(TOUCHED), false); +}); + +// Review 1 M2. +test("a fetcher key written onto it changes nothing: every door still refuses, and no fetcher is called", async () => { + const says = SOURCELESS_POSTS_CHANNEL("kettle-keyed"); + assert.equal((await fetchPosts({ paths, slug: "kettle-keyed", settings } as never)).error, says); + assert.equal((await capturePosts({ paths, slug: "kettle-keyed", settings, ids: ["801"] } as never)).error, says); + assert.equal((await checkPostAvailability({ paths, slug: "kettle-keyed" } as never)).error, says); + assert.deepEqual(await planXRun(paths, { channels: ["kettle-keyed"] }), { ok: false, error: says }); + assert.deepEqual((await listXRunCandidates(paths)).map((c) => c.slug), ["teapot-x"]); + assert.equal(syncSkipForShape({ ...PUBLISHED, postFetcher: "x-gallery-dl" } as never), "published posts: no account to fetch from"); + assert.equal(fetcherCalls, 0); + assert.equal(existsSync(TOUCHED), false); +}); + +// Review 1 S1. +test("no source URL is ever built for one of its posts, and import-post is refused; an account channel answers as before", async () => { + for (const slug of ["kettle-festival", "kettle-keyed"]) { + assert.equal(await findVideoSourceUrl(paths, slug, "801"), null, `${slug}, config read`); + assert.equal(await findVideoSourceUrl(paths, slug, "801", (await readChannelConfig(paths, slug))!), null, `${slug}, config handed in`); + assert.equal(await recordWebpageUrl(paths, slug, "801"), null, `${slug}: nothing for a Wayback lookup`); + const imported = await planImportPost(paths, slug, "https://x.com/teapot_news/status/1900000000000001001"); + assert.deepEqual(imported, { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) }); + } + // CONTROL: an X account channel still gets the address built from its platform and the id. + const built = defaultWebpageUrl("twitter", "801"); + assert.ok(built, "the platform builds an address from an id"); + assert.equal(await findVideoSourceUrl(paths, "teapot-x", "801", (await readChannelConfig(paths, "teapot-x"))!), built); + assert.equal(fetcherCalls, 0); +}); diff --git a/common/controller/undownloadedVideos.ts b/common/controller/undownloadedVideos.ts @@ -1,4 +1,5 @@ import path from "node:path"; +import { isSourcelessPostsChannel } from "../lib/sourcelessPosts"; import { readChannelConfig } from "./channels"; import { localMediaFetchRefusal } from "../lib/localMedia"; import { readFile } from "node:fs/promises"; @@ -33,6 +34,12 @@ export async function findVideoSourceUrl( if (localMediaFetchRefusal(slug, config ?? (await readChannelConfig(paths, slug).catch(() => null)), videoId)) { return null; } + // POSTS PUBLISHED FROM A PRIVATE LIBRARY (lib/sourcelessPosts.ts; review 1 + // S1): no account, no page. Null, so no door — transcribe-one, a clip + // window, a persist, a redownload, a Wayback lookup — is handed + // `defaultWebpageUrl("twitter", id)` built from the channel's platform and + // a post's id. Any other posts channel answers as before. + if (isSourcelessPostsChannel(config ?? (await readChannelConfig(paths, slug).catch(() => null)))) return null; const metaPath = path.join(channelRoot, "data", videoId, "metadata.info.json"); try { const raw = await readFile(metaPath, "utf8"); diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -61,6 +61,7 @@ import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/ne import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; export const X_RUN_JOB_KIND = "x-run"; // X's platform queue: the run serialises with every other X job (a channel's @@ -321,7 +322,9 @@ export function isXPostsChannel(config: ConfigLike | null | undefined): boolean config.platform === "twitter" && !isWaybackPagesChannel(config as Parameters<typeof isWaybackPagesChannel>[0]) && // A trending library has nothing an X run can fetch. - !isXTrendingChannel(config as Parameters<typeof isXTrendingChannel>[0]) + !isXTrendingChannel(config as Parameters<typeof isXTrendingChannel>[0]) && + // Nor have posts published from one: no account, no search. + !isSourcelessPostsChannel(config as Parameters<typeof isSourcelessPostsChannel>[0]) ); } @@ -442,6 +445,7 @@ export async function planXRun(paths: Paths, req: XRunRequest, now = Date.now()) if (slugs.includes(s)) return { ok: false, error: `"${s}" is named twice.` }; const config = await readChannelConfig(paths, s); if (!config) return { ok: false, error: `No such channel: ${s}` }; + if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(s) }; if (!isXPostsChannel(config)) return { ok: false, error: `${s} is not an X posts channel.` }; slugs.push(s); } diff --git a/common/controller/xSearchLeads.test.ts b/common/controller/xSearchLeads.test.ts @@ -17,7 +17,9 @@ 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 { readXSearchLeads, setXSearchLeadHidden, planArchiveXLead, readXTrendingAccounts } = await import("./xSearchLeads"); +const { judgeXTrending } = await import("../lib/xTrending/judgements"); +const { recordXTrendingRead, writeXTrendingPosts } = await import("../lib/xTrending/store"); const { writeSite, X_SEARCH_NOT_ON_A_SITE } = await import("../lib/site"); const paths = getPaths(); @@ -152,3 +154,73 @@ test("no site may carry an X search channel, as a member or a cited channel", as { message: "demo-search is an X search channel: it is never put on a site." }, ); }); + +test("an X trending library's accounts: handle, posts, kept, topics, who archives it; Archive this account plans <handle>-x for an account in the library only", async () => { + const libRoot = await channel("demo-library", { sourceKind: "social", platform: "twitter", xTrending: {} }); + const lp = (id: string, author: string, name: string, at: string) => ({ + id, slug: `demo-library/${id}`, channelSlug: "demo-library", author, authorName: name, createdAt: at, uploadDate: at.slice(0, 10).replace(/-/g, ""), + text: `kettle ${id}`, url: `https://x.com/${author}/status/${id}`, platform: "twitter" as const, isReply: false, isRepost: false, links: [], + }); + await writeXTrendingPosts(libRoot, [ + lp("901", "Dora", "Dora D", "2026-11-16T10:00:00.000Z"), + lp("902", "dora", "Dora Now", "2026-11-16T12:00:00.000Z"), + lp("903", "bob", "Bob", "2026-11-16T11:00:00.000Z"), + lp("904", "Dora", "Dora D", "2026-11-16T09:00:00.000Z"), + lp("905", "erin", "Erin", "2026-11-16T09:00:00.000Z"), + ]); + const ref = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); + await recordXTrendingRead(libRoot, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: ref(1), topic: "Kettles", postIds: ["901", "902", "903"], added: 3 }); + await recordXTrendingRead(libRoot, { readId: "tr-01JB0000000000000000000000", at: "2026-11-17T11:00:00.000Z", ref: ref(2), topic: "Cups", postIds: ["904", "905"], added: 2 }); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "901", state: "keep" }, { id: "903", state: "drop" }] }); + await judgeXTrending(libRoot, { by: "agent", set: [{ id: "904", state: "keep" }] }); + + const view = await readXTrendingAccounts(paths, "demo-library"); + assert.ok(view.ok); + assert.deepEqual([view.total, view.posts, view.more], [3, 5, 0]); + assert.deepEqual(view.accounts, [ + { handle: "dora", key: "dora", name: "Dora Now", posts: 3, kept: 2, keptByOperator: 1, topics: ["kettles", "cups"], last: "2026-11-16T12:00:00.000Z" }, + { handle: "bob", key: "bob", name: "Bob", posts: 1, kept: 0, keptByOperator: 0, topics: ["kettles"], last: "2026-11-16T11:00:00.000Z", archivedAs: ["bob-x"] }, + { handle: "erin", key: "erin", name: "Erin", posts: 1, kept: 0, keptByOperator: 0, topics: ["cups"], last: "2026-11-16T09:00:00.000Z" }, + ]); + const cups = await readXTrendingAccounts(paths, "demo-library", { topic: "cups", limit: 1 }); + assert.ok(cups.ok); + assert.deepEqual([cups.accounts.map((a) => [a.key, a.posts]), cups.total, cups.more], [[["dora", 1]], 2, 1]); + assert.deepEqual(await readXTrendingAccounts(paths, "demo-search"), { ok: false, error: 'demo-search is not an X trending library (create one with platform "x-trending").' }); + + // The plan: the leads' own, and it names nothing of the library. + const plan = await planArchiveXLead(paths, "demo-library", "@Dora", "Dora Now"); + assert.deepEqual(plan, { + ok: true, + slug: "dora-x", + fields: { name: "Dora Now (X)", handling: "transcribe", url: "https://x.com/Dora", platform: "twitter", sourceKind: "social", postFetcher: "x-gallery-dl", socialHandle: "Dora" }, + }); + assert.doesNotMatch(JSON.stringify(plan), /demo-library|trending/i); + assert.deepEqual(await planArchiveXLead(paths, "demo-library", "bob"), { ok: false, error: "@bob is already archived: bob-x." }); + assert.deepEqual(await planArchiveXLead(paths, "demo-library", "alice"), { + ok: false, + error: 'demo-library holds no post by @alice: "Archive this account" is for an account in the library.', + }); + // "Never archive" stays a search channel's. + assert.equal((await setXSearchLeadHidden(paths, "demo-library", "dora", true)).ok, false); +}); + +// Review 1, nit: the listing stops at 500 accounts; the plan must not. +test("Archive this account finds an account of a library that holds more than 500", async () => { + const libRoot = await channel("big-library", { sourceKind: "social", platform: "twitter", xTrending: {} }); + const posts = Array.from({ length: 520 }, (_, i) => { + const id = String(1899100000000000000n + BigInt(i)); + // The LAST account has the fewest and oldest posts: it sorts past the 500th. + const author = `acct_${String(i).padStart(3, "0")}`; + return { id, slug: `big-library/${id}`, channelSlug: "big-library", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "kettle", url: `https://x.com/${author}/status/${id}`, platform: "twitter" as const, isReply: false, isRepost: false, links: [] }; + }); + await writeXTrendingPosts(libRoot, posts); + await recordXTrendingRead(libRoot, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: { trendId: "1900000000000000009", url: "https://x.com/i/trending/1900000000000000009" }, topic: "Kettles", postIds: posts.map((p) => p.id), added: posts.length }); + const view = await readXTrendingAccounts(paths, "big-library", { limit: 500 }); + assert.ok(view.ok); + assert.deepEqual([view.total, view.accounts.length, view.more], [520, 500, 20]); + const beyond = "acct_519"; + assert.ok(!view.accounts.some((a) => a.key === beyond), "the account is past the listing's cap"); + const plan = await planArchiveXLead(paths, "big-library", beyond); + assert.ok(plan.ok, JSON.stringify(plan)); + assert.equal(plan.slug, "acct_519-x"); +}); diff --git a/common/controller/xSearchLeads.ts b/common/controller/xSearchLeads.ts @@ -22,6 +22,8 @@ import { type XSearchLeads, } from "../lib/xSearch/leads"; import { handleFromAccountUrl } from "../social/fetchers"; +import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "../lib/xTrending/config"; +import { listXTrendingAccounts, xTrendingHoldsAccount, type XTrendingAccounts } from "../lib/xTrending/accounts"; import { channelExists, listChannelConfigs, patchChannelConfig, readChannelConfig } from "./channels"; export const NOT_AN_X_SEARCH_CHANNEL = (slug: string) => @@ -121,7 +123,15 @@ export async function planArchiveXLead( 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) }; + // AN X TRENDING LIBRARY'S ACCOUNTS ARE LEADS TOO (lane x-trending-publish): + // the same plan, for an account that wrote a post the library holds. The + // channel made names nothing of the library. + if (isXTrendingChannel(config)) { + // Asked of the library's posts, not of the listing (which stops at 500 accounts). + if (!(await xTrendingHoldsAccount(path.join(paths.channelsDir, slug), key))) { + return { ok: false, error: `${slug} holds no post by @${handle.replace(/^@/, "")}: "Archive this account" is for an account in the library.` }; + } + } else 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); @@ -130,3 +140,18 @@ export async function planArchiveXLead( } return { ok: true, slug: newSlug, fields: xLeadChannelFields({ handle: handle.replace(/^@/, ""), ...(name ? { name } : {}) }) }; } + +// A LIBRARY'S ACCOUNTS, with the X channels that already archive each (lane +// x-trending-publish): what `get trending --accounts`, the MCP's +// x_trending_accounts and the Posts library page list. +export async function readXTrendingAccounts( + paths: Paths, + slug: string, + opts: { topic?: string; limit?: number } = {}, +): Promise<({ ok: true; slug: string } & XTrendingAccounts) | { ok: false; error: string }> { + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXTrendingChannel(config)) return { ok: false, error: NOT_AN_X_TRENDING_LIBRARY(slug) }; + const archived = await archivedXAccounts(paths); + return { ok: true, slug, ...(await listXTrendingAccounts(path.join(paths.channelsDir, slug), { ...opts, archived })) }; +} diff --git a/common/controller/xTrendingGuards.test.ts b/common/controller/xTrendingGuards.test.ts @@ -38,7 +38,10 @@ test("fetch-posts refuses a library with a sentence, before any fetcher is asked test("the X run never lists a library among the X posts channels", () => { assert.equal(isXPostsChannel(LIBRARY as never), false); - assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), true); + assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/teapot_news", socialHandle: "teapot_news" } as never), true); + // With no account at all it is posts published from a library (lane + // x-trending-publish): nothing an X run can fetch either. + assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), false); }); test("read-x-trending: a network kind on X's queue that nothing replays or resumes; reparse asks nothing", () => { diff --git a/common/jobs/xLeadSyncOff.test.ts b/common/jobs/xLeadSyncOff.test.ts @@ -0,0 +1,69 @@ +// "ARCHIVE THIS ACCOUNT" FROM A LIBRARY ASKS X NOTHING, NOW OR LATER (lane +// x-trending-publish, review 1 M1). The channel it makes has a URL and has +// never synced: the most overdue channel the scheduler knows. So it is made +// with its priority tier `paused`, and this pins that every automatic door +// honours that one switch: the sync scheduler (selectDueChannels and the +// schedule view), Sync all's skip, and the four lanes. And that an X SEARCH +// channel's lead is archived exactly as before. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xLeadSyncOff.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { channelsForOperation, isChannelPaused, PRIORITY_OPERATIONS, sanitizeChannelPriority } from "../lib/channelPriority"; +import { defaultSyncScheduler } from "../lib/settings"; +import { xLeadArchiveMode, xLeadChannelFields, xLeadChannelSlug, xLeadSyncOffSentence } from "../lib/xSearch/leads"; +import { buildScheduleView, selectDueChannels } from "./syncScheduler"; +import { emptySchedulerState } from "./syncSchedulerState"; + +const NOW = Date.parse("2026-11-18T12:00:00.000Z"); +const scheduler = { ...defaultSyncScheduler(), enabled: true, defaultIntervalMinutes: 60, quietHoursStart: null, quietHoursEnd: null }; + +// The channel as "Archive this account" makes it: the lead's own fields, never synced. +const slug = xLeadChannelSlug("saucer_fan"); +const fields = xLeadChannelFields({ handle: "saucer_fan" }); +const config = { handling: "transcribe", name: fields.name, url: fields.url, platform: "twitter", sourceKind: "social", postFetcher: fields.postFetcher, socialHandle: fields.socialHandle } as ChannelConfig; +const channels = [{ slug, config }]; +const due = (priority: ReturnType<typeof sanitizeChannelPriority>) => + selectDueChannels({ channels, scheduler, state: emptySchedulerState(), activeSlugs: new Set<string>(), now: NOW, priority }).due; + +test("the mode: from a library nothing is fetched and sync is off unless fetch is asked; from a search channel nothing changed", () => { + assert.deepEqual(xLeadArchiveMode({ library: true }), { fetchNow: false, syncOff: true }); + assert.deepEqual(xLeadArchiveMode({ library: true, fetch: false }), { fetchNow: false, syncOff: true }); + assert.deepEqual(xLeadArchiveMode({ library: true, fetch: true }), { fetchNow: true, syncOff: false }); + // AN X SEARCH CHANNEL'S LEAD, AS IT ALWAYS WAS: the first fetch starts unless `fetch: false`; sync is never touched. + assert.deepEqual(xLeadArchiveMode({ library: false }), { fetchNow: true, syncOff: false }); + assert.deepEqual(xLeadArchiveMode({ library: false, fetch: true }), { fetchNow: true, syncOff: false }); + assert.deepEqual(xLeadArchiveMode({ library: false, fetch: false }), { fetchNow: false, syncOff: false }); +}); + +test("WITHOUT the switch the new channel is fetched at the scheduler's next tick: a never-synced channel with a URL is due at once", () => { + assert.deepEqual(due(sanitizeChannelPriority({ channels: {} })), [slug]); +}); + +test("with its tier paused it is not due, not eligible, skipped by Sync all's question, and in no lane", () => { + const priority = sanitizeChannelPriority({ channels: { [slug]: { tier: "paused" } } }); + // The sync scheduler. + assert.deepEqual(due(priority), []); + const view = buildScheduleView({ channels, scheduler, state: emptySchedulerState(), now: NOW, priority }); + assert.equal(view[0].autoSyncEligible, false); + // Sync all asks exactly this (editor channels/actions.ts syncAllChannelsAction: "paused for sync"). + assert.equal(isChannelPaused(priority, slug, "sync"), true); + // The four lanes, and sync: every operation there is. + for (const op of PRIORITY_OPERATIONS) { + assert.equal(isChannelPaused(priority, slug, op), true, op); + assert.deepEqual(channelsForOperation(priority, [slug], op), [], op); + } + // Turned on again (tier normal): due, as any channel. + assert.deepEqual(due(sanitizeChannelPriority({ channels: { [slug]: { tier: "normal" } } })), [slug]); +}); + +test("the sentence says the three things: sync off, nothing asked of X, and how to turn sync on and run the first fetch", () => { + assert.equal( + xLeadSyncOffSentence("saucer_fan-x", "@saucer_fan"), + `Made the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. ` + + `To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["saucer_fan-x"],"tier":"normal"}'). ` + + `Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"saucer_fan-x"}').`, + ); +}); diff --git a/common/lib/sourcelessPosts.ts b/common/lib/sourcelessPosts.ts @@ -0,0 +1,41 @@ +// A POSTS CHANNEL WITH NO SOURCE (lane x-trending-publish): an X posts +// channel that names no account, no search and no page — nothing to fetch. +// A `postFetcher` key does not make a source (review 1 M2): a fetcher is HOW +// a source is read, and with no url, handle, search, library marker or page +// scope there is nothing for it to read. So that key is not asked, and +// writing it cannot switch this predicate, and every guard that asks it, off. +// Its posts were PUT there: a topic of a private library, published by the +// operator (controller/publishXTrending.ts). The channel carries no mark of +// that; it is told by its shape alone, and by this one predicate. +// +// SUCH A CHANNEL MAKES NO REQUEST ANYWHERE: fetch-posts, an X run, Sync all, +// capture-posts and the availability check skip it where they list channels +// and refuse it, with the sentence below, when asked for it by name. It is an +// ordinary channel otherwise: indexed, built, and put on a site by the +// operator's own act. A LEAF: types only. + +import { isRemoteOnlyChannel, isSocialChannel, type ChannelConfig } from "./channelConfig"; + +type Shape = Pick<ChannelConfig, "sourceKind" | "platform"> & + Partial<Pick<ChannelConfig, "url" | "socialHandle" | "xSearch" | "xTrending" | "wayback" | "remoteOnly">>; + +export function isSourcelessPostsChannel(config: Shape | null | undefined): boolean { + if (!config || !isSocialChannel(config) || config.platform !== "twitter") return false; + if (config.url || config.socialHandle) return false; + if (config.xSearch || config.xTrending || config.wayback) return false; + return !isRemoteOnlyChannel(config); +} + +// What it is, wherever a fetch, a capture or Configure is asked of it. +export const SOURCELESS_POSTS_CHANNEL = (slug: string) => + `${slug} holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it.`; + +// WHY SYNC ALL SKIPS A CHANNEL FOR WHAT IT IS (its shape, before its state): +// the reason the bulk bar shows, or null. Published posts are named as such, +// not as a channel somebody forgot to give a URL. +export function syncSkipForShape(config: (Shape & Pick<ChannelConfig, "remoteOnly">) | null | undefined): string | null { + if (isSourcelessPostsChannel(config)) return "published posts: no account to fetch from"; + if (!config?.url) return "no url"; + if (isRemoteOnlyChannel(config)) return "remote-only"; + return null; +} diff --git a/common/lib/xSearch/leads.ts b/common/lib/xSearch/leads.ts @@ -151,3 +151,30 @@ export function xLeadChannelFields(lead: { handle: string; name?: string }): Rec socialHandle: handle, }; } + +// WHAT "ARCHIVE THIS ACCOUNT" DOES BESIDE MAKING THE CHANNEL, by where the +// lead came from (lane x-trending-publish, review 1 M1). +// +// From an X SEARCH channel's leads, as always: the first fetch starts unless +// `fetch: false`, and the channel syncs like any other. +// +// From an X TRENDING LIBRARY's accounts: NOTHING IS ASKED OF X unless `fetch: +// true`. Not starting the first fetch is not enough: a channel with a URL +// that has never synced is the most overdue one the scheduler knows, and the +// next tick would fetch it. So the channel is made with SYNC OFF: its +// priority tier `paused` (lib/channelPriority.ts), the one switch the sync +// scheduler, Sync all and the four lanes all ask (`isChannelPaused`). +export function xLeadArchiveMode(o: { library: boolean; fetch?: boolean }): { fetchNow: boolean; syncOff: boolean } { + if (o.library) return o.fetch === true ? { fetchNow: true, syncOff: false } : { fetchNow: false, syncOff: true }; + return { fetchNow: o.fetch !== false, syncOff: false }; +} + +// What is said of a channel made with sync off: the page, the ops answer and +// the CLI print this, whole. +export function xLeadSyncOffSentence(slug: string, handle: string): string { + return ( + `Made the channel "${slug}" for @${handle.replace(/^@/, "")}, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. ` + + `To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["${slug}"],"tier":"normal"}'). ` + + `Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"${slug}"}').` + ); +} diff --git a/common/lib/xTrending/accounts.ts b/common/lib/xTrending/accounts.ts @@ -0,0 +1,91 @@ +// A LIBRARY'S ACCOUNTS (lane x-trending-publish, slice 4): who wrote the +// posts a library holds — like an X search channel's leads +// (lib/xSearch/leads.ts): the handle, how many posts, how many of them are +// kept (the judgement in force, either hand's), and the topics they are in. +// Read from the library's own files; no index, no request. A library file's +// reader like the listing: behind every door. SERVER-ONLY (node:fs). + +import { xLeadHandle } from "../xSearch/config"; +import { + readXTrendingJudgementsFile, + readXTrendingMembership, + readXTrendingPosts, + readXTrendingTopics, + xTrendingEffectiveJudgement, + xTrendingThreadOf, +} from "./store"; + +export type XTrendingAccount = { + // The handle as the newest post writes it; `key` is its lower case. + handle: string; + key: string; + name?: string; + posts: number; + kept: number; + // Of the kept, the operator's (what a publish would take). + keptByOperator: number; + topics: string[]; + last: string; // ISO, its newest post in the library + // X channels already archiving this account (filled by the controller). + archivedAs?: string[]; +}; + +export type XTrendingAccounts = { accounts: XTrendingAccount[]; total: number; posts: number; more: number }; + +export const X_TRENDING_ACCOUNTS_DEFAULT = 100; +export const X_TRENDING_ACCOUNTS_MAX = 500; + +// Most posts first, then most kept, then by handle. `topic` narrows to one. +export async function listXTrendingAccounts( + channelRoot: string, + opts: { topic?: string; limit?: number; archived?: ReadonlyMap<string, string[]> } = {}, +): Promise<XTrendingAccounts> { + const [topics, membership, posts, judgements] = await Promise.all([ + readXTrendingTopics(channelRoot), + readXTrendingMembership(channelRoot), + readXTrendingPosts(channelRoot), + readXTrendingJudgementsFile(channelRoot), + ]); + const want = opts.topic ? (topics.find((t) => t.id === opts.topic) ?? topics.find((t) => t.aliases?.includes(opts.topic!)))?.id ?? opts.topic : undefined; + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + const rows = new Map<string, XTrendingAccount & { topicSet: Set<string> }>(); + let counted = 0; + for (const post of byId.values()) { + const m = membership[post.id]; + if (want && m.topic !== want) continue; + const key = xLeadHandle(post.author); + if (!key) continue; + counted++; + const row = rows.get(key) ?? { handle: post.author.replace(/^@/, ""), key, posts: 0, kept: 0, keptByOperator: 0, topics: [], last: "", topicSet: new Set<string>() }; + row.posts++; + const j = xTrendingEffectiveJudgement(judgements.posts[post.id], judgements.threads[xTrendingThreadOf(post, membership, byId)]); + if (j?.state === "keep") { + row.kept++; + if (j.by === "operator") row.keptByOperator++; + } + row.topicSet.add(m.topic); + if (post.createdAt > row.last) { + row.last = post.createdAt; + row.handle = post.author.replace(/^@/, ""); + if (post.authorName) row.name = post.authorName; + } + rows.set(key, row); + } + const order = new Map(topics.map((t, i) => [t.id, i])); + const all = [...rows.values()] + .map(({ topicSet, ...row }) => ({ + ...row, + topics: [...topicSet].sort((a, b) => (order.get(a) ?? 1e9) - (order.get(b) ?? 1e9)), + ...(opts.archived?.get(row.key)?.length ? { archivedAs: opts.archived.get(row.key) } : {}), + })) + .sort((a, b) => b.posts - a.posts || b.kept - a.kept || (a.key < b.key ? -1 : 1)); + const limit = Math.min(Math.max(1, opts.limit ?? X_TRENDING_ACCOUNTS_DEFAULT), X_TRENDING_ACCOUNTS_MAX); + return { accounts: all.slice(0, limit), total: all.length, posts: counted, more: Math.max(0, all.length - limit) }; +} + +// Whether the library holds a post by this account (its handle's lower case), +// however many accounts it holds: asked of the posts, not of a capped listing. +export async function xTrendingHoldsAccount(channelRoot: string, key: string): Promise<boolean> { + const [membership, posts] = await Promise.all([readXTrendingMembership(channelRoot), readXTrendingPosts(channelRoot)]); + return posts.some((p) => membership[p.id] && xLeadHandle(p.author) === key); +} diff --git a/common/lib/xTrending/organise.test.ts b/common/lib/xTrending/organise.test.ts @@ -0,0 +1,307 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { judgeXTrending } from "./judgements"; +import { MERGE_IS_THE_OPERATORS, MERGE_WAITS_FOR_READS, RENAME_WAITS_FOR_READS, mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } from "./organise"; +import { mutateXTrendingPublished, readXTrendingPublished } from "./published"; +import { listXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, writeXTrendingPosts } from "./store"; +import { readXTrendingWatches, setXTrendingWatch } from "./watch"; +import type { Post } from "../posts"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-organise-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const READ = (c: string) => `tr-01J${c}0000000000000000000000`; +const REF = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); +const NOW = Date.parse("2026-11-18T10:00:00.000Z"); +const IDLE = () => false; + +function post(id: string, author: string, text: string, replyTo?: string): Post { + return { + id, + slug: `lib/${id}`, + channelSlug: "lib", + author, + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter", + ...(replyTo ? { threadId: replyTo, replyTo: { id: replyTo, platform: "twitter" as const } } : {}), + isReply: Boolean(replyTo), + isRepost: false, + links: [], + }; +} + +// Two topics: "Kettles" (page 1: posts 101, 102 and 103, a reply to 101) and +// "Saucers" (page 2: posts 201, 202; page 1 again as its second source). +async function library(name: string): Promise<string> { + const dir = path.join(TMP, name); + mkdirSync(dir, { recursive: true }); + await writeXTrendingPosts(dir, [ + post("101", "teapot_news", "one"), + post("102", "saucer_fan", "two"), + post("103", "teapot_news", "three", "101"), + post("201", "spoon_daily", "four"), + post("202", "saucer_fan", "five"), + ]); + await recordXTrendingRead(dir, { readId: READ("A"), at: "2026-11-17T10:00:00.000Z", ref: REF(1), topic: "Kettles", postIds: ["101", "102", "103"], added: 3, threads: { "101": "101", "103": "101", "102": "102" } }); + await recordXTrendingRead(dir, { readId: READ("B"), at: "2026-11-17T11:00:00.000Z", ref: REF(2), topic: "Saucers", postIds: ["201", "202"], added: 2 }); + await recordXTrendingRead(dir, { readId: READ("C"), at: "2026-11-17T12:00:00.000Z", ref: REF(1), topic: "Saucers", postIds: ["101"], added: 0 }); + return dir; +} + +const watchOn = async (dir: string, topic: string, by: "agent" | "operator", intervalMinutes: number) => { + const r = await setXTrendingWatch(dir, { topics: await readXTrendingTopics(dir), topic, on: true, intervalMinutes, hours: 48, by, maxTopics: 4, now: NOW }); + assert.equal(r.ok, true); +}; + +test("rename: the title changes, the id stays, and who renamed is recorded; a name another topic answers to is refused", async () => { + const dir = await library("rename"); + await watchOn(dir, "kettles", "operator", 30); + const r = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: " Teapots of the week ", by: "agent", now: NOW }); + assert.ok(r.ok); + assert.deepEqual([r.topic, r.title, r.was, r.changed], ["kettles", "Teapots of the week", "Kettles", true]); + assert.match(r.sentence, /Its id stays kettles/); + const topics = await readXTrendingTopics(dir); + assert.deepEqual(topics.map((t) => [t.id, t.title]), [["kettles", "Teapots of the week"], ["saucers", "Saucers"]]); + assert.deepEqual(topics[0].organised, { what: "rename", by: "agent", at: "2026-11-18T10:00:00.000Z" }); + assert.ok((await readXTrendingWatches(dir)).kettles, "its watch is still its own"); + assert.equal((await readXTrendingMembership(dir))["102"].topic, "kettles"); + + const same = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "Teapots of the week", by: "agent" }); + assert.ok(same.ok && !same.changed); + for (const taken of ["saucers", "SAUCERS", "Saucers"]) { + const no = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: taken, by: "operator" }); + assert.ok(!no.ok && /already answers to/.test(no.error), taken); + } + const missing = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "spoons", title: "x", by: "operator" }); + assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); + const long = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "x".repeat(121), by: "operator" }); + assert.ok(!long.ok && /at most 120/.test(long.error)); + const who = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "x", by: "somebody" as never }); + assert.ok(!who.ok && /"by" is/.test(who.error)); +}); + +test("move: posts by id or a whole thread change topic; judgements stay; a later read does not move them back", async () => { + const dir = await library("move"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "102", state: "keep", note: "a note" }, { thread: "101", state: "drop" }] }); + const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); + + const r = await moveXTrendingPosts(dir, { to: "saucers", ids: ["102", "999", "201"], by: "agent", now: NOW }); + assert.ok(r.ok); + assert.deepEqual(r.moved, ["102"]); + assert.deepEqual(r.skipped, [{ id: "999", reason: "not in this library" }, { id: "201", reason: 'already in "Saucers"' }]); + let members = await readXTrendingMembership(dir); + assert.equal(members["102"].topic, "saucers"); + assert.deepEqual(members["102"].moved, { from: "kettles", by: "agent", at: "2026-11-18T10:00:00.000Z" }); + + const t = await moveXTrendingPosts(dir, { to: "Saucers", thread: "101", by: "operator", now: NOW }); + assert.ok(t.ok); + assert.deepEqual([...t.moved].sort(), ["101", "103"]); + assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore, "judgements are keyed by post and thread: untouched"); + const listing = await listXTrending(dir, { topic: "saucers", filter: { state: "drop" }, ids: true }); + assert.deepEqual([...(listing.ids ?? [])].sort(), ["101", "103"], "the thread's judgement travels with its posts"); + + // The page is read again into its first topic: a placed post keeps its place. + await recordXTrendingRead(dir, { readId: READ("D"), at: "2026-11-18T11:00:00.000Z", ref: REF(1), topic: "kettles", postIds: ["101", "102", "103"], added: 0 }); + members = await readXTrendingMembership(dir); + assert.deepEqual(["101", "102", "103"].map((id) => members[id].topic), ["saucers", "saucers", "saucers"]); + + for (const [ask, re] of [ + [{ to: "saucers", by: "agent" }, /one of them/], + [{ to: "saucers", ids: ["101"], thread: "101", by: "agent" }, /one of them/], + [{ to: "saucers", ids: ["x"], by: "agent" }, /list of post ids/], + [{ to: "saucers", thread: "777", by: "agent" }, /no thread "777"/], + [{ to: "spoons", ids: ["101"], by: "agent" }, /no topic "spoons".*"create": true/], + [{ to: "", ids: ["101"], by: "agent" }, /"to" is/], + ] as const) { + const no = await moveXTrendingPosts(dir, ask as never); + assert.ok(!no.ok && re.test(no.error), JSON.stringify(ask)); + } +}); + +test("move with create: a new topic with no page, made only when a post went into it", async () => { + const dir = await library("move-create"); + const none = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["999"], create: true, by: "operator" }); + assert.ok(none.ok && none.moved.length === 0 && !none.to.created); + assert.equal((await readXTrendingTopics(dir)).length, 2); + const r = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator" }); + assert.ok(r.ok && r.to.created); + assert.deepEqual(r.to, { id: "spoons", title: "Spoons", created: true }); + const topics = await readXTrendingTopics(dir); + assert.deepEqual(topics.map((t) => [t.id, t.sources.length]), [["kettles", 1], ["saucers", 2], ["spoons", 0]]); +}); + +test("merge is the operator's, and waits for a read", async () => { + const dir = await library("merge-refused"); + const before = readFileSync(path.join(dir, "trending", "topics.json"), "utf8"); + const agent = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "agent", readInFlight: () => false }); + assert.deepEqual(agent, { ok: false, error: MERGE_IS_THE_OPERATORS }); + const busy = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => true }); + assert.deepEqual(busy, { ok: false, error: MERGE_WAITS_FOR_READS }); + // A read queued between the first look and the lock refuses it too. + let asked = 0; + const late = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => ++asked > 1 }); + assert.deepEqual(late, { ok: false, error: MERGE_WAITS_FOR_READS }); + const self = await mergeXTrendingTopics(dir, { into: "kettles", from: ["Kettles"], by: "operator", readInFlight: () => false }); + assert.ok(!self.ok && /not merged into itself/.test(self.error)); + const missing = await mergeXTrendingTopics(dir, { into: "kettles", from: ["spoons"], by: "operator", readInFlight: () => false }); + assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); + assert.equal(readFileSync(path.join(dir, "trending", "topics.json"), "utf8"), before); +}); + +test("merge: posts, pages and reads carried; the same page in both becomes one; judgements untouched; the old id means the target", async () => { + const dir = await library("merge"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "201", state: "keep" }, { thread: "101", state: "later" }] }); + const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + assert.deepEqual(r.into, { id: "kettles", title: "Kettles" }); + assert.deepEqual(r.merged, [{ id: "saucers", title: "Saucers", posts: 2, pages: 2 }]); + assert.equal(r.posts, 2); + assert.equal(r.pages, 2); + assert.match(r.sentence, /"Saucers" is now part of "Kettles": 2 posts moved, 2 trending pages in the topic\. The judgements are untouched\. This cannot be undone\./); + + const topics = await readXTrendingTopics(dir); + assert.equal(topics.length, 1); + assert.deepEqual(topics[0].aliases, ["saucers"]); + assert.deepEqual(topics[0].organised, { what: "merge", by: "operator", at: "2026-11-18T10:00:00.000Z" }); + assert.deepEqual( + topics[0].sources.map((s) => [s.trendId, s.reads.map((x) => x.id)]), + [[REF(1).trendId, [READ("A"), READ("C")]], [REF(2).trendId, [READ("B")]]], + ); + const members = await readXTrendingMembership(dir); + assert.ok(Object.values(members).every((m) => m.topic === "kettles")); + assert.deepEqual(members["201"].moved, { from: "saucers", by: "operator", at: "2026-11-18T10:00:00.000Z" }); + assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore); + + // An ask that still names the merged topic: the listing and a read. + const listing = await listXTrending(dir, { topic: "saucers", ids: true }); + assert.equal(listing.ids?.length, 5); + assert.deepEqual(listing.topics.map((t) => [t.id, t.posts, t.aliases]), [["kettles", 5, ["saucers"]]]); + await writeXTrendingPosts(dir, [post("301", "spoon_daily", "six")]); + const read = await recordXTrendingRead(dir, { readId: READ("E"), at: "2026-11-18T12:00:00.000Z", ref: REF(2), topic: "saucers", postIds: ["301"], added: 1 }); + assert.deepEqual(read.topic, { id: "kettles", title: "Kettles", created: false }); + assert.equal((await readXTrendingTopics(dir)).length, 1, "a merged-away id never makes a topic again"); + // Nor is a new topic ever given that id. + const fresh = await recordXTrendingRead(dir, { readId: READ("F"), at: "2026-11-18T13:00:00.000Z", ref: REF(3), topic: "Saucers!", postIds: [], added: 0 }); + assert.deepEqual(fresh.topic, { id: "saucers-2", title: "Saucers!", created: true }); +}); + +test("merge, two live watches: the target's stands with its own terms, the other is gone, and the sentence says so", async () => { + const dir = await library("merge-watches"); + await watchOn(dir, "kettles", "agent", 45); + await watchOn(dir, "saucers", "operator", 20); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + const watches = await readXTrendingWatches(dir); + assert.deepEqual(Object.keys(watches), ["kettles"]); + assert.deepEqual([watches.kettles.intervalMinutes, watches.kettles.by, watches.kettles.nextSource], [45, "agent", 0]); + assert.deepEqual(r.watch.dropped, ["saucers"]); + assert.equal(r.watch.stands?.from, "kettles"); + assert.match(r.sentence, /The watch of "Kettles" stands with its own terms and reads its 2 pages in turn: Watched every 45 min/); + assert.match(r.sentence, /The watch of "Saucers" is gone: one topic has one watch\./); +}); + +test("merge, only the merged topic watched: its watch becomes the target's; none watched: no watch file is made", async () => { + const dir = await library("merge-watch-moves"); + await watchOn(dir, "saucers", "operator", 20); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + const watches = await readXTrendingWatches(dir); + assert.deepEqual(Object.keys(watches), ["kettles"]); + assert.equal(watches.kettles.intervalMinutes, 20); + assert.match(r.sentence, /The watch of "Saucers" is now the watch of "Kettles" and reads its 2 pages in turn/); + + const plain = await library("merge-no-watch"); + const p = await mergeXTrendingTopics(plain, { into: "saucers", from: ["kettles"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(p.ok && !p.watch.stands && p.watch.dropped.length === 0); + assert.deepEqual(await readXTrendingWatches(plain), {}); + assert.doesNotMatch(p.sentence, /watch/i); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +test("S9: a rename waits for a read, as a merge does: asked before the lock and inside it; nothing is written", async () => { + const dir = await library("rename-waits"); + const before = readFileSync(path.join(dir, "trending", "topics.json"), "utf8"); + assert.deepEqual(await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: () => true }), { ok: false, error: RENAME_WAITS_FOR_READS }); + let asked = 0; + assert.deepEqual(await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: () => ++asked > 1 }), { ok: false, error: RENAME_WAITS_FOR_READS }); + assert.equal(readFileSync(path.join(dir, "trending", "topics.json"), "utf8"), before); + // Why: a read asked for by the old NAME after a rename would make a topic of that name. + assert.ok((await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: IDLE })).ok); + const read = await recordXTrendingRead(dir, { readId: READ("H"), at: "2026-11-18T15:00:00.000Z", ref: REF(5), topic: "Kettles", postIds: [], added: 0 }); + assert.equal(read.topic.created, true, "which is what the refusal prevents while a read is in flight"); +}); + +test("S6: a move into a new topic writes the topic BEFORE the posts: cut between the two, no post names a topic that does not exist", async () => { + const dir = await library("move-crash"); + await assert.rejects( + moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator", now: NOW, betweenWrites: () => { throw new Error("cut here"); } }), + /cut here/, + ); + let topics = await readXTrendingTopics(dir); + let members = await readXTrendingMembership(dir); + assert.deepEqual(topics.map((t) => t.id), ["kettles", "saucers", "spoons"], "the topic is on disk"); + assert.equal(members["201"].topic, "saucers", "the post was not moved"); + for (const m of Object.values(members)) assert.ok(topics.some((t) => t.id === m.topic), `every post's topic exists (${m.topic})`); + // The same move again completes it; no second topic is made. + const again = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator", now: NOW }); + assert.ok(again.ok && again.moved.length === 1 && again.to.id === "spoons" && !again.to.created); + topics = await readXTrendingTopics(dir); + members = await readXTrendingMembership(dir); + assert.deepEqual(topics.map((t) => t.id), ["kettles", "saucers", "spoons"]); + assert.equal(members["201"].topic, "spoons"); +}); + +test("nit: a thread is moved by the key the listing shows, the one kept in the membership record", async () => { + const dir = await library("move-thread-key"); + // 102 was PLACED in thread 102 (its record says so); nothing in its post names a thread. + const listing = await listXTrending(dir, { topic: "kettles" }); + const shown: Record<string, string> = Object.fromEntries(listing.posts.map((p) => [p.id, p.thread])); + const expected: Record<string, string> = { "101": "101", "102": "102", "103": "101" }; + assert.deepEqual(shown, expected); + for (const thread of ["101", "102"]) { + const twin = await library(`move-thread-key-${thread}`); + const r = await moveXTrendingPosts(twin, { to: "saucers", thread, by: "agent" }); + assert.ok(r.ok); + // 101 itself is in "kettles" (a post already placed keeps its topic). + assert.deepEqual([...r.moved, ...r.skipped.map((x) => x.id)].sort(), Object.keys(shown).filter((id) => shown[id] === thread).sort()); + } +}); + +test("S7: a merge and what was published: the merged topic's channel becomes the target's when it has none; with one of its own, the other is left and named", async () => { + const rec = (slug: string, ids: string[]) => ({ slug, firstAt: "2026-11-18T09:00:00.000Z", lastAt: "2026-11-18T09:00:00.000Z", posts: Object.fromEntries(ids.map((id) => [id, "2026-11-18T09:00:00.000Z"])), identity: { ino: 7, birthtimeMs: 9 } }); + const put = (dir: string, all: Record<string, ReturnType<typeof rec>>) => mutateXTrendingPublished(dir, (topics) => { Object.assign(topics, all); return { write: true, result: undefined }; }); + + // The target has none: the merged topic's record is carried, whole. + const carried = await library("merge-published-carried"); + await put(carried, { saucers: rec("saucers-chan", ["201"]) }); + const a = await mergeXTrendingTopics(carried, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); + assert.ok(a.ok); + assert.deepEqual(a.published, { carried: "saucers-chan", left: [] }); + assert.match(a.sentence, /The channel "saucers-chan", which a merged topic was published into, is now the channel of "Kettles": its next publish adds to it\./); + assert.deepEqual(await readXTrendingPublished(carried), { kettles: rec("saucers-chan", ["201"]) }); + + // Both have one: the target's stays; the other is left, named, and no record names it. + const both = await library("merge-published-both"); + await put(both, { kettles: rec("kettles-chan", ["101"]), saucers: rec("saucers-chan", ["201"]) }); + const b = await mergeXTrendingTopics(both, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); + assert.ok(b.ok); + assert.deepEqual(b.published, { left: ["saucers-chan"] }); + assert.match(b.sentence, /The channel "saucers-chan", published from a merged topic, stays as it is and will not be added to again: "Kettles" has a channel of its own\./); + assert.deepEqual(await readXTrendingPublished(both), { kettles: rec("kettles-chan", ["101"]) }); + + // Neither: no record file is made, and the sentence says nothing of channels. + const none = await library("merge-published-none"); + const c = await mergeXTrendingTopics(none, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); + assert.ok(c.ok); + assert.deepEqual(c.published, { left: [] }); + assert.doesNotMatch(c.sentence, /channel/); + assert.deepEqual(await readXTrendingPublished(none), {}); +}); diff --git a/common/lib/xTrending/organise.ts b/common/lib/xTrending/organise.ts @@ -0,0 +1,420 @@ +// ORGANISING A LIBRARY'S TOPICS (lane x-trending-publish, slice 4): rename a +// topic, merge topics into one, move posts between topics. +// +// RENAME changes a topic's title and nothing else: its id stays, so its +// watch, the judge view's marks and addresses keep meaning it. REFUSED WHILE +// A READ OR A REPARSE OF THE LIBRARY IS QUEUED OR RUNNING, as a merge is: a +// read may have been asked for by the topic's NAME, and would make a new +// topic of the old name when it records. +// +// MOVE sets the topic of posts (by id, or a whole thread) under the +// membership file's lock. It is SAFE BESIDE A READ OR A CAPTURE and is not +// refused for one: a read never moves a post that has a place +// (recordXTrendingRead), and a capture writes neither file. Judgements are +// keyed by post and by thread, never by topic, so they travel untouched; so +// do "gone from the page" marks (they are about the page, not the topic). +// +// MERGE puts every page, read and post 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. It is REFUSED WHILE A READ OR A REPARSE OF THE LIBRARY IS QUEUED +// OR RUNNING (the caller answers that from its job registry): a queued watch +// tick names its topic by id. As a second line, the merged topics' ids stay on +// the target as `aliases`, so an ask that still names one means the target +// and never makes a topic again (store.ts resolveXTrendingTopic). +// +// posts every member of a `from` topic → `into` +// pages `into`'s sources, then each `from` topic's; the same page in +// two topics becomes one, its reads joined by read id +// judgements untouched (not keyed by topic) +// published a topic has ONE channel (lib/xTrending/published.ts). The +// target's record stays; when it has none, the first merged +// topic's becomes its own. Any other merged topic's channel +// is left as it is and never added to again; the sentence +// names it. +// watches ONE stands. `into`'s live watch stands with its own terms; +// when `into` has none, the first `from` topic's live watch +// moves to it. Every other watch entry goes. The standing +// watch now reads all the pages in turn (its turn starts +// over); pages X answered "gone" for stay unread. +// +// Written in an order a second run completes: the membership, the watches, +// the publish records, then topics.json — all inside the topics file's lock, so no read records +// between them. SERVER-ONLY (node:fs). + +import type { Post } from "../posts"; +import { + mutateXTrendingMembership, + mutateXTrendingTopics, + readXTrendingMembership, + readXTrendingPosts, + resolveXTrendingTopic, + topicIdFromTitle, + topicTitleProblem, + xTrendingThreadOf, + type XTrendingOrganiseBy, + type XTrendingSource, + type XTrendingTopic, +} from "./store"; +import { mutateXTrendingPublished } from "./published"; +import { describeXTrendingWatch, mutateXTrendingWatches, watchIsLive, type XTrendingWatch } from "./watch"; + +export const X_TRENDING_MOVE_MAX = 500; +export const X_TRENDING_MERGE_MAX = 20; + +export const MERGE_IS_THE_OPERATORS = + `Merging topics is the operator's press: it cannot be undone (there is no unmerge). The operator merges on umtool's Posts library page, ` + + `or with "by": "operator". An agent may rename a topic and move posts between topics.`; + +export const MERGE_WAITS_FOR_READS = + "A read of this library is queued or running: merge its topics once it has finished (its job is on /jobs). A queued read names its topic, and a merge would take that topic away under it."; + +const none = (topics: ReadonlyArray<XTrendingTopic>) => topics.map((t) => t.id).join(", ") || "none yet"; +const noTopic = (asked: string, topics: ReadonlyArray<XTrendingTopic>) => `This library has no topic "${asked}" (its topics: ${none(topics)}).`; +const n = (k: number, what: string) => `${k} ${what}${k === 1 ? "" : "s"}`; + +function byProblem(by: unknown): string | null { + return by === "agent" || by === "operator" ? null : `"by" is "agent" or "operator"`; +} + +export type Refused = { ok: false; error: string }; + +// ── rename ───────────────────────────────────────────────────────────────── + +export type XTrendingRenameResult = { ok: true; op: "rename"; topic: string; title: string; was: string; changed: boolean; sentence: string } | Refused; + +export const RENAME_WAITS_FOR_READS = + "A read of this library is queued or running: rename its topic once it has finished (its job is on /jobs). A read names its topic, by id or by name, and a name changed under it could send its posts to a new topic."; + +export async function renameXTrendingTopic( + channelRoot: string, + ask: { + topic: string; + title: string; + by: XTrendingOrganiseBy; + // A read or a reparse of this library queued or running (required, so no + // door can forget it): a read asked for by a topic's NAME finds its topic + // by that name when it records (review 1 S9). + readInFlight: () => boolean | Promise<boolean>; + now?: number; + }, +): Promise<XTrendingRenameResult> { + const bad = byProblem(ask.by) ?? (typeof ask.topic !== "string" || !ask.topic.trim() ? `"topic" is the topic's id` : null); + if (bad) return { ok: false, error: bad }; + if (typeof ask.title !== "string" || !ask.title.trim()) return { ok: false, error: `"title" is the topic's new name` }; + const problem = topicTitleProblem(ask.title); + if (problem) return { ok: false, error: problem }; + const title = ask.title.trim(); + const at = new Date(ask.now ?? Date.now()).toISOString(); + if (await ask.readInFlight()) return { ok: false, error: RENAME_WAITS_FOR_READS }; + return mutateXTrendingTopics<XTrendingRenameResult>(channelRoot, async (topics) => { + const topic = resolveXTrendingTopic(topics, ask.topic); + if (!topic) return { write: false, result: { ok: false, error: noTopic(ask.topic, topics) } }; + // Asked again inside the lock: a read queued since the first look. + if (await ask.readInFlight()) return { write: false, result: { ok: false, error: RENAME_WAITS_FOR_READS } }; + // A name another topic answers to (its title, its id, an id merged into + // it) would make "which topic" depend on the order of the file. + const other = resolveXTrendingTopic(topics.filter((t) => t !== topic), title); + if (other) { + return { write: false, result: { ok: false, error: `Topic "${other.title}" (${other.id}) already answers to "${title}": a topic's name is its own. Merge the two, or choose another name.` } }; + } + const was = topic.title; + if (was === title) { + return { write: false, result: { ok: true, op: "rename", topic: topic.id, title, was, changed: false, sentence: `Topic ${topic.id} is already named "${title}".` } }; + } + topic.title = title; + topic.organised = { what: "rename", by: ask.by, at }; + return { + write: true, + result: { ok: true, op: "rename", topic: topic.id, title, was, changed: true, sentence: `Topic "${was}" is now "${title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }, + }; + }); +} + +// ── move ─────────────────────────────────────────────────────────────────── + +export type XTrendingMoveResult = + | { + ok: true; + op: "move"; + to: { id: string; title: string; created: boolean }; + moved: string[]; + skipped: Array<{ id: string; reason: string }>; + sentence: string; + } + | Refused; + +export async function moveXTrendingPosts( + channelRoot: string, + ask: { + to: string; + ids?: ReadonlyArray<string>; + thread?: string; + // `to` may name a topic that does not exist yet: it is made, with no page. + create?: boolean; + by: XTrendingOrganiseBy; + now?: number; + posts?: ReadonlyArray<Post>; + // A test's seam: called after a topic made for this move is on disk and + // before any post is put in it. + betweenWrites?: () => void | Promise<void>; + }, +): Promise<XTrendingMoveResult> { + const bad = byProblem(ask.by); + if (bad) return { ok: false, error: bad }; + if (typeof ask.to !== "string" || !ask.to.trim()) return { ok: false, error: `"to" is the topic the posts go to` }; + const hasIds = ask.ids !== undefined; + const hasThread = ask.thread !== undefined; + if (hasIds === hasThread) return { ok: false, error: `a move names posts ("ids") or one thread ("thread"), one of them` }; + if (hasIds && (!Array.isArray(ask.ids) || ask.ids.length === 0 || !ask.ids.every((id) => typeof id === "string" && /^\d+$/.test(id)))) { + return { ok: false, error: `"ids" is a list of post ids` }; + } + if (hasIds && ask.ids!.length > X_TRENDING_MOVE_MAX) return { ok: false, error: `"ids" holds at most ${X_TRENDING_MOVE_MAX} post ids` }; + if (hasThread && (typeof ask.thread !== "string" || !/^\d+$/.test(ask.thread))) return { ok: false, error: `"thread" is a thread's root post id` }; + const at = new Date(ask.now ?? Date.now()).toISOString(); + + // The thread's posts, by the key each was placed with. + let wanted: string[] = hasIds ? [...new Set(ask.ids)] : []; + if (hasThread) { + const [membership, posts] = await Promise.all([readXTrendingMembership(channelRoot), ask.posts ?? readXTrendingPosts(channelRoot)]); + // THE LISTING'S OWN RULE (store.ts listXTrending): every member's key is + // the one kept in its membership record, else derived over ALL the + // library's posts — so "the thread" here is the thread the page shows. + const archived = new Map(posts.map((p) => [p.id, p])); + wanted = Object.keys(membership).filter((id) => { + const post = archived.get(id); + return !!post && xTrendingThreadOf(post, membership, archived) === ask.thread; + }); + if (wanted.length === 0) return { ok: false, error: `This library has no thread "${ask.thread}".` }; + } + + return mutateXTrendingTopics<XTrendingMoveResult>(channelRoot, async (topics, save) => { + let target = resolveXTrendingTopic(topics, ask.to); + let created = false; + if (!target) { + if (!ask.create) return { write: false, result: { ok: false, error: `${noTopic(ask.to, topics)} To move posts into a new topic, say "create": true.` } }; + const problem = topicTitleProblem(ask.to); + if (problem) return { write: false, result: { ok: false, error: problem } }; + const title = ask.to.trim(); + const base = topicIdFromTitle(title) || "topic"; + let id = base; + for (let k = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); k++) id = `${base}-${k}`; + target = { id, title, createdAt: at, sources: [] }; + topics.push(target); + created = true; + // THE TOPIC FIRST, THEN THE POSTS (review 1 S6): cut between the two + // writes, the library holds an empty topic — never a post whose topic + // does not exist. + await save(); + await ask.betweenWrites?.(); + } + const to = target; + const out = await mutateXTrendingMembership(channelRoot, (members) => { + const moved: string[] = []; + const skipped: Array<{ id: string; reason: string }> = []; + for (const id of wanted) { + const m = members[id]; + if (!m) skipped.push({ id, reason: "not in this library" }); + else if (m.topic === to.id) skipped.push({ id, reason: `already in "${to.title}"` }); + else { + m.moved = { from: m.topic, by: ask.by, at }; + m.topic = to.id; + moved.push(id); + } + } + return { write: moved.length > 0, result: { moved, skipped } }; + }); + // A topic made for a move that moved nothing is taken back. + const unmade = created && out.moved.length === 0; + if (unmade) topics.pop(); + const skippedSentence = out.skipped.length ? ` ${n(out.skipped.length, "post")} skipped: ${out.skipped[0].reason}.` : ""; + return { + write: unmade, + result: { + ok: true, + op: "move", + to: { id: to.id, title: to.title, created: created && out.moved.length > 0 }, + moved: out.moved, + skipped: out.skipped, + sentence: + `${n(out.moved.length, "post")} moved to "${to.title}"${created && out.moved.length > 0 ? " (a new topic, with no trending page yet)" : ""}.${skippedSentence}` + + (out.moved.length ? " Their judgements and captures are untouched." : ""), + }, + }; + }); +} + +// ── merge ────────────────────────────────────────────────────────────────── + +export type XTrendingMergeResult = + | { + ok: true; + op: "merge"; + into: { id: string; title: string }; + merged: Array<{ id: string; title: string; posts: number; pages: number }>; + posts: number; + pages: number; + // What became of the watches: which one stands, and whose were dropped. + watch: { stands?: { from: string; sentence: string }; dropped: string[] }; + // What became of the merged topics' PUBLISHED channels (review 1 S7): + // `carried` is now the target's (the next publish adds to it); `left` + // stay as they are and are never added to again. + published: { carried?: string; left: string[] }; + sentence: string; + } + | Refused; + +function joinSources(into: XTrendingSource[], add: ReadonlyArray<XTrendingSource>): void { + for (const s of add) { + const have = into.find((x) => x.trendId === s.trendId); + if (!have) { + into.push({ ...s, reads: [...s.reads] }); + continue; + } + if (!have.title && s.title) have.title = s.title; + if (!have.summary && s.summary) have.summary = s.summary; + for (const r of s.reads) if (!have.reads.some((x) => x.id === r.id)) have.reads.push(r); + have.reads.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0)); + } +} + +export async function mergeXTrendingTopics( + channelRoot: string, + ask: { + into: string; + from: ReadonlyArray<string>; + by: XTrendingOrganiseBy; + // A read or a reparse of this library queued or running (required, so no + // door can forget it). + readInFlight: () => boolean | Promise<boolean>; + now?: number; + }, +): Promise<XTrendingMergeResult> { + const bad = byProblem(ask.by); + if (bad) return { ok: false, error: bad }; + if (ask.by !== "operator") return { ok: false, error: MERGE_IS_THE_OPERATORS }; + if (typeof ask.into !== "string" || !ask.into.trim()) return { ok: false, error: `"into" is the topic that stays` }; + if (!Array.isArray(ask.from) || ask.from.length === 0 || !ask.from.every((t) => typeof t === "string" && t.trim())) { + return { ok: false, error: `"from" is a list of the topics merged into it` }; + } + if (ask.from.length > X_TRENDING_MERGE_MAX) return { ok: false, error: `"from" holds at most ${X_TRENDING_MERGE_MAX} topics` }; + if (await ask.readInFlight()) return { ok: false, error: MERGE_WAITS_FOR_READS }; + const nowMs = ask.now ?? Date.now(); + const at = new Date(nowMs).toISOString(); + + return mutateXTrendingTopics<XTrendingMergeResult>(channelRoot, async (topics) => { + const into = resolveXTrendingTopic(topics, ask.into); + if (!into) return { write: false, result: { ok: false, error: noTopic(ask.into, topics) } }; + const from: XTrendingTopic[] = []; + for (const name of ask.from) { + const t = resolveXTrendingTopic(topics, name); + if (!t) return { write: false, result: { ok: false, error: noTopic(name, topics) } }; + if (t === into) return { write: false, result: { ok: false, error: `"${name}" is the topic that stays ("${into.title}"): a topic is not merged into itself.` } }; + if (!from.includes(t)) from.push(t); + } + // Asked again inside the lock: a read queued since the first look. + if (await ask.readInFlight()) return { write: false, result: { ok: false, error: MERGE_WAITS_FOR_READS } }; + const gone = new Set(from.map((t) => t.id)); + + // 1. the posts + const counts = await mutateXTrendingMembership(channelRoot, (members) => { + const per = new Map<string, number>(); + for (const m of Object.values(members)) { + if (!gone.has(m.topic)) continue; + per.set(m.topic, (per.get(m.topic) ?? 0) + 1); + m.moved = { from: m.topic, by: ask.by, at }; + m.topic = into.id; + } + return { write: per.size > 0, result: per }; + }); + + // 2. the watches: one stands + const pagesAfter = new Set([...into.sources, ...from.flatMap((t) => t.sources)].map((s) => s.trendId)); + type Standing = { from: string; watch: XTrendingWatch }; + const watch = await mutateXTrendingWatches<{ dropped: string[]; stands?: Standing }>(channelRoot, (watches) => { + const dropped: string[] = []; + let stands: Standing | undefined; + if (watchIsLive(watches[into.id])) stands = { from: into.id, watch: watches[into.id] }; + for (const t of from) { + const w = watches[t.id]; + if (!w) continue; + if (!stands && watchIsLive(w)) stands = { from: t.id, watch: w }; + else if (watchIsLive(w)) dropped.push(t.id); + } + const touched = from.some((t) => watches[t.id]) || !!stands; + if (!touched) return { write: false, result: { dropped } }; + const unread = new Set<string>(); + for (const id of [into.id, ...gone]) for (const g of watches[id]?.goneSources ?? []) if (pagesAfter.has(g)) unread.add(g); + for (const id of gone) delete watches[id]; + if (stands) { + stands.watch.goneSources = [...unread]; + stands.watch.nextSource = 0; + watches[into.id] = stands.watch; + } + return { write: true, result: { dropped, ...(stands ? { stands } : {}) } }; + }); + + // 3. what was published: a topic has ONE channel. The target's own stays + // its own; with none, the first merged topic's becomes the target's. + // Any other merged topic's channel is left as it is: no record names + // it any more, so no publish adds to it again. + const published = await mutateXTrendingPublished(channelRoot, (all) => { + const left: string[] = []; + let carried: string | undefined; + let write = false; + for (const t of from) { + const rec = all[t.id]; + if (!rec) continue; + write = true; + if (!all[into.id]) { + all[into.id] = rec; + carried = rec.slug; + } else left.push(rec.slug); + delete all[t.id]; + } + return { write, result: { ...(carried ? { carried } : {}), left } }; + }); + + // 4. the topics + const merged = from.map((t) => ({ id: t.id, title: t.title, posts: counts.get(t.id) ?? 0, pages: t.sources.length })); + for (const t of from) { + joinSources(into.sources, t.sources); + into.aliases = [...new Set([...(into.aliases ?? []), t.id, ...(t.aliases ?? [])])].filter((a) => a !== into.id); + topics.splice(topics.indexOf(t), 1); + } + into.organised = { what: "merge", by: ask.by, at }; + + const posts = merged.reduce((a, m) => a + m.posts, 0); + const names = merged.map((m) => `"${m.title}"`).join(", "); + const title = (id: string) => (id === into.id ? into.title : merged.find((m) => m.id === id)?.title ?? id); + let watchSentence = ""; + const standing = watch.stands; + if (standing) { + const what = describeXTrendingWatch(standing.watch, nowMs); + const whose = standing.from === into.id ? `The watch of "${into.title}" stands with its own terms` : `The watch of "${title(standing.from)}" is now the watch of "${into.title}"`; + const others = watch.dropped.length + ? ` The watch${watch.dropped.length === 1 ? "" : "es"} of ${watch.dropped.map((id) => `"${title(id)}"`).join(", ")} ${watch.dropped.length === 1 ? "is" : "are"} gone: one topic has one watch.` + : ""; + watchSentence = ` ${whose} and reads its ${n(into.sources.length, "page")} in turn: ${what}${others}`; + } + return { + write: true, + result: { + ok: true, + op: "merge", + into: { id: into.id, title: into.title }, + merged, + posts, + pages: into.sources.length, + watch: { ...(standing ? { stands: { from: standing.from, sentence: describeXTrendingWatch(standing.watch, nowMs) } } : {}), dropped: watch.dropped }, + published, + sentence: + `${names} ${merged.length === 1 ? "is" : "are"} now part of "${into.title}": ${n(posts, "post")} moved, ${n(into.sources.length, "trending page")} in the topic. ` + + `The judgements are untouched. This cannot be undone.${watchSentence}` + + (published.carried ? ` The channel "${published.carried}", which a merged topic was published into, is now the channel of "${into.title}": its next publish adds to it.` : "") + + (published.left.length + ? ` The channel${published.left.length === 1 ? "" : "s"} ${published.left.map((c) => `"${c}"`).join(", ")}, published from a merged topic, ${published.left.length === 1 ? "stays as it is" : "stay as they are"} and will not be added to again: "${into.title}" has a channel of its own.` + : ""), + }, + }; + }); +} diff --git a/common/lib/xTrending/published.ts b/common/lib/xTrending/published.ts @@ -0,0 +1,94 @@ +// WHAT A LIBRARY HAS PUBLISHED (lane x-trending-publish, slice 4): +// +// channels/<lib>/trending/published.json topic id → {slug, firstAt, +// lastAt, posts: {post id → when it was published}, identity?: {ino, +// birthtimeMs} of the channel's directory, pending?} +// +// THE RECORD IS THE LIBRARY'S, AND THE ONLY ONE. The channel a topic is +// published into carries no mark of it: nothing in that channel names the +// library, a judgement, a note or a watch. "This channel was made by this +// publish" is therefore answered from here, and from the channel's own +// content (controller/publishXTrending.ts, the three-part proof). +// +// `slug` is fixed at the first publish: renaming the topic afterwards does +// not fork its channel. `posts` is written BEFORE the posts are, so at any +// moment the channel holds no post this record does not name. +// +// A library file like judgements.json: behind every door, never in a build. +// ONE WRITER (this module), under the file's lock. SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; + +const TRENDING_DIRNAME = "trending"; +export const X_TRENDING_PUBLISHED_FILENAME = "published.json"; + +// WHICH DIRECTORY THE CHANNEL IS (review 1 S2): the channel directory's inode +// and birth time, read when this publish made it. A channel deleted and made +// again — by hand, of the very same shape, even empty — is another directory, +// and is refused. The DIRECTORY, not config.json: a config is rewritten +// through a temp file and a rename, so its inode changes with every edit. +// Nothing is written into the channel for this. +export type XTrendingPublishedIdentity = { ino: number; birthtimeMs: number }; + +export type XTrendingPublishedTopic = { + slug: string; + firstAt: string; + lastAt: string; + posts: Record<string, string>; + identity?: XTrendingPublishedIdentity; + // A publish wrote this record and had not yet recorded the directory it + // made (it writes the record first): the next publish may adopt a channel + // of the slug only while it holds no post. + pending?: true; +}; + +type PublishedFile = { version: 1; topics: Record<string, XTrendingPublishedTopic> }; + +export function xTrendingPublishedPath(channelRoot: string): string { + return path.join(channelRoot, TRENDING_DIRNAME, X_TRENDING_PUBLISHED_FILENAME); +} + +const str = (v: unknown): v is string => typeof v === "string" && v !== ""; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export async function readXTrendingPublished(channelRoot: string): Promise<Record<string, XTrendingPublishedTopic>> { + const read = await readJsonFile(xTrendingPublishedPath(channelRoot)); + const topics = read.ok ? (read.value as { topics?: unknown } | null)?.topics : null; + const out: Record<string, XTrendingPublishedTopic> = {}; + if (!topics || typeof topics !== "object" || Array.isArray(topics)) return out; + for (const [id, raw] of Object.entries(topics as Record<string, Partial<XTrendingPublishedTopic> | null>)) { + if (!id || !raw || typeof raw !== "object" || !str(raw.slug) || !SLUG.test(raw.slug) || raw.slug === "..") continue; + const posts: Record<string, string> = {}; + if (raw.posts && typeof raw.posts === "object" && !Array.isArray(raw.posts)) { + for (const [post, at] of Object.entries(raw.posts)) if (/^\d+$/.test(post) && str(at)) posts[post] = at; + } + const ident = raw.identity as Partial<XTrendingPublishedIdentity> | undefined; + const identity = + ident && typeof ident === "object" && Number.isFinite(ident.ino) && Number.isFinite(ident.birthtimeMs) + ? { ino: Number(ident.ino), birthtimeMs: Number(ident.birthtimeMs) } + : undefined; + out[id] = { + slug: raw.slug, + firstAt: str(raw.firstAt) ? raw.firstAt : "", + lastAt: str(raw.lastAt) ? raw.lastAt : "", + posts, + ...(identity ? { identity } : {}), + ...(raw.pending === true ? { pending: true as const } : {}), + }; + } + return out; +} + +// Every write: the file read under its lock, changed, written. +export async function mutateXTrendingPublished<T>( + channelRoot: string, + change: (topics: Record<string, XTrendingPublishedTopic>) => { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(xTrendingPublishedPath(channelRoot), async () => { + const topics = await readXTrendingPublished(channelRoot); + const { write, result } = change(topics); + if (write) await writeJsonAtomic(xTrendingPublishedPath(channelRoot), { version: 1, topics } satisfies PublishedFile, { mkdir: true }); + return result; + }); +} diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -21,7 +21,9 @@ // THIS MODULE IS THE ONE WRITER of topics.json and membership.json; every // write goes through the file's lock (withJsonFileLock) and is atomic. A // re-read of a page adds posts and appends a read; it never drops a post, and -// never moves one out of the topic it is in. +// never moves one out of the topic it is in. Renaming and merging topics and +// moving a post between them (lib/xTrending/organise.ts) write through +// mutateXTrendingTopics / mutateXTrendingMembership here, under the same locks. // // The listing reads these files and the posts shards — never the index (the // library is in no index build). It is a plain module over the corpus on @@ -322,12 +324,23 @@ export type XTrendingSource = { reads: XTrendingSourceRead[]; }; +// Who organised (renamed, merged, moved) and when: the caller's word, as a +// judgement's `by` is (lib/xTrending/organise.ts). +export type XTrendingOrganiseBy = "agent" | "operator"; +export type XTrendingOrganised = { what: "rename" | "merge"; by: XTrendingOrganiseBy; at: string }; + export type XTrendingTopic = { id: string; // The operator's name for it (X's title is the source's). title: string; createdAt: string; sources: XTrendingSource[]; + // The ids of topics merged into this one (lane x-trending-publish): an ask + // that still names one — a queued read, an old address — means this topic, + // and never makes a new one. + aliases?: string[]; + // Its last rename or merge. + organised?: XTrendingOrganised; }; export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number }; @@ -348,6 +361,9 @@ export type XTrendingMember = { gone?: XTrendingGone; // Earlier absences that ended: gone from `from`, shown again at `to`. wasGone?: Array<{ from: string; to: string }>; + // Its last move between topics (lib/xTrending/organise.ts): the topic it + // was in, who moved it and when. + moved?: { from: string; by: XTrendingOrganiseBy; at: string }; }; type TopicsFile = { version: 1; topics: XTrendingTopic[] }; @@ -377,7 +393,20 @@ function parseTopics(raw: unknown): XTrendingTopic[] { reads, }); } - out.push({ id: t.id, title: t.title, createdAt: str(t.createdAt) ? t.createdAt : "", sources }); + const aliases = (Array.isArray(t.aliases) ? t.aliases : []).filter((a: unknown): a is string => str(a) && a !== t.id); + const o = t.organised as Partial<XTrendingOrganised> | undefined; + const organised = + o && typeof o === "object" && (o.what === "rename" || o.what === "merge") && (o.by === "agent" || o.by === "operator") && str(o.at) + ? { what: o.what, by: o.by, at: o.at } + : undefined; + out.push({ + id: t.id, + title: t.title, + createdAt: str(t.createdAt) ? t.createdAt : "", + sources, + ...(aliases.length ? { aliases: [...new Set<string>(aliases)] } : {}), + ...(organised ? { organised } : {}), + }); } return out; } @@ -409,6 +438,11 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { const wasGone = (Array.isArray(m.wasGone) ? m.wasGone : []).filter( (w): w is { from: string; to: string } => !!w && typeof w === "object" && str(w.from) && str(w.to), ); + const mv = m.moved as Partial<NonNullable<XTrendingMember["moved"]>> | undefined; + const moved = + mv && typeof mv === "object" && str(mv.from) && (mv.by === "agent" || mv.by === "operator") && str(mv.at) + ? { from: mv.from, by: mv.by, at: mv.at } + : undefined; out[id] = { topic: m.topic, ...(typeof m.thread === "string" && /^\d+$/.test(m.thread) ? { thread: m.thread } : {}), @@ -416,6 +450,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { ...(media ? { media } : {}), ...(gone ? { gone } : {}), ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}), + ...(moved ? { moved } : {}), }; } return out; @@ -431,6 +466,55 @@ export async function readXTrendingMembership(channelRoot: string): Promise<Reco return read.ok ? parseMembership(read.value) : {}; } +// THE TOPIC AN ASK NAMES: by its id, else by the id of a topic merged into it +// (`aliases`), else by its title in any case. One rule, asked by a read, the +// listing and every organise step, so a merged-away id never makes a topic. +export function resolveXTrendingTopic<T extends { id: string; title: string; aliases?: string[] }>( + topics: ReadonlyArray<T>, + asked: string | undefined, +): T | undefined { + const name = asked?.trim(); + if (!name) return undefined; + return ( + topics.find((t) => t.id === name) ?? + topics.find((t) => t.aliases?.includes(name)) ?? + topics.find((t) => t.title.toLowerCase() === name.toLowerCase()) + ); +} + +// EVERY OTHER WRITE OF topics.json AND membership.json (lane +// x-trending-publish: rename, merge, move — lib/xTrending/organise.ts): the +// file read under its lock, changed, written. `change` answers `write: false` +// to write nothing. A read's own write is recordXTrendingRead below; the two +// share the locks, so neither sees the other's half. +// `save` writes the topics as they stand NOW, inside the lock: for a change +// that must have the topics on disk before it writes another file (a topic +// made for a move is written before any post is put in it). +export async function mutateXTrendingTopics<T>( + channelRoot: string, + change: (topics: XTrendingTopic[], save: () => Promise<void>) => Promise<{ write: boolean; result: T }> | { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(topicsPath(channelRoot), async () => { + const topics = await readXTrendingTopics(channelRoot); + const save = () => writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); + const { write, result } = await change(topics, save); + if (write) await save(); + return result; + }); +} + +export async function mutateXTrendingMembership<T>( + channelRoot: string, + change: (posts: Record<string, XTrendingMember>) => { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(membershipPath(channelRoot), async () => { + const posts = await readXTrendingMembership(channelRoot); + const { write, result } = change(posts); + if (write) await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true }); + return result; + }); +} + // A topic id from a title: lower-case words joined by "-", at most 48 // characters; "" when the title has no letter or digit. export function topicIdFromTitle(title: string): string { @@ -497,9 +581,7 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const asked = input.topic?.trim(); let found: XTrendingTopic | undefined; if (asked) { - found = - topics.find((t) => t.id === asked) ?? - topics.find((t) => t.title.toLowerCase() === asked.toLowerCase()); + found = resolveXTrendingTopic(topics, asked); } else { found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId)); } @@ -508,7 +590,8 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const title = asked || `Trending ${input.ref.trendId}`; const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`; let id = base; - for (let n = 2; topics.some((t) => t.id === id); n++) id = `${base}-${n}`; + // Never the id of a topic merged away: that id means the topic it went into. + for (let n = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); n++) id = `${base}-${n}`; found = { id, title, createdAt: input.at, sources: [] }; topics.push(found); created = true; @@ -712,6 +795,8 @@ export type XTrendingTopicRow = { id: string; title: string; posts: number; + // The ids of topics merged into it: an ask naming one means this topic. + aliases?: string[]; // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it // is doing as one sentence. watch?: XTrendingWatch & { sentence: string }; @@ -874,6 +959,8 @@ export async function listXTrending( readXTrendingJudgementsFile(channelRoot), ]); const archived = new Map((opts.posts ?? (await readXTrendingPosts(channelRoot))).map((p) => [p.id, p])); + // A topic asked for by the id of one merged into it is that topic. + const wantTopic = opts.topic ? (topics.find((t) => t.id === opts.topic) ?? topics.find((t) => t.aliases?.includes(opts.topic!)))?.id ?? opts.topic : undefined; const count = new Map<string, number>(); for (const [id, m] of Object.entries(membership)) { if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1); @@ -902,7 +989,7 @@ export async function listXTrending( if (!Number.isFinite(mark) || Date.parse(firstSeenAt) > mark) fresh.set(m.topic, (fresh.get(m.topic) ?? 0) + 1); } } - if (opts.topic && m.topic !== opts.topic) continue; + if (wantTopic && m.topic !== wantTopic) continue; if (opts.detail) authors.set(post.author, (authors.get(post.author) ?? 0) + 1); const media = m.media ?? { count: post.mediaCount ?? 0, kinds: [] }; if (filter.state && (effective?.state ?? "unjudged") !== filter.state) continue; @@ -966,6 +1053,7 @@ export async function listXTrending( id: t.id, title: t.title, posts: count.get(t.id) ?? 0, + ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}), ...(opts.detail ? { counts: counts.get(t.id) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 } } : {}), ...(opts.detail && opts.seen ? { fresh: fresh.get(t.id) ?? 0 } : {}), diff --git a/common/social/importPost.ts b/common/social/importPost.ts @@ -17,6 +17,7 @@ // platform's queue, so it never runs beside a fetch of the same source. // A post already archived is not read again. +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; @@ -73,6 +74,8 @@ export async function planImportPost( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a posts channel; import-post imports into a channel that archives an account's posts` }; } + // Posts published from a private library: nothing is asked of X for it. + if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) }; const fetcher = (opts.fetcherFor ?? ((c) => resolveSocialFetcher(c.postFetcher, c.url)))(config); if (!fetcher) return { ok: false, error: `${slug} has no post fetcher` }; const want = PLATFORM_LABEL[ref.platform] ?? ref.platform; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,26 @@ # Changelog ## [Unreleased] +- **A trending library's topics can be organised, and a topic published.** + - **Rename** a topic, **move** posts between topics, **merge** topics into one: `pnpm ops organise-trending`, and + on umtool's Posts library page. A merge cannot be undone, so it is the operator's and asks twice; it waits + while a read of the library is queued or running. When both topics are watched, the target's watch stands. + - **Publish kept posts…** on a topic, or `pnpm ops publish-trending`: the posts the operator kept become an + ordinary posts channel, **on no site**. The first press (a dry run) says exactly what would be written: the + slug, posts, files and bytes. The second is the operator's. An agent's keep is not published. + - The published channel names nothing of the library: no judgement, note, read or watch. Its files are copies, + so purging the library and deleting the channel do not affect each other. Nothing fetches it. + - Publishing again adds newly kept posts and removes none: a post since dropped is reported and stays. + - Before the press, the dry run names the sites the channel is already on (what is added goes public at their + next build), the posts that were moved into the topic and by whom, and any file that no longer matches what + its capture recorded. + - A published channel's Configure sets its name and the sites that carry it, and nothing else. + - **Accounts** of a library (`pnpm ops get trending <slug> --accounts`, the MCP's `x_trending_accounts`, the + page's Accounts panel), and **Archive this account…**: `<handle>-x` on no site, **with sync off**. From a + library it asks X nothing, now or at the scheduler's next tick; the answer says how to turn sync on and run + the first fetch. + - `umtool library rename | move | merge | publish | accounts | archive` are the same from a shell. `merge` and + `publish` want `--by operator`. - **The Posts library: a trending library is browsed and judged in umtool.** - **`/tools/library`** in umtool (Tools → posts library): topics on the left with their post, unjudged and new counts and what each watch is doing; each post drawn as the archive's viewer draws one, with its captured diff --git a/editor/app/api/ops/organise-trending/route.ts b/editor/app/api/ops/organise-trending/route.ts @@ -0,0 +1,65 @@ +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}, +// published: {carried?, left}, 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 and +// their judgements are untouched. Refused: a name another topic answers to, +// and A READ OR A REPARSE OF THE LIBRARY QUEUED OR RUNNING (a read may name +// its topic by its name, and would make a new topic of the old one). +// +// 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. A topic has ONE published channel too +// (`published: {carried?, left}`): `into`'s stays its own; when it has none, +// the first merged topic's becomes its own (`carried`: its next publish adds +// to it); any other merged topic's channel is `left` as it is and never +// added to again, and the sentence names it. +// +// 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,175 @@ +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: "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5" }, 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\)/); + // Review 1: where it would go public, who moved what in, and what no longer matches its capture. + assert.deepEqual({ sites: dry.json.sites, movedIn: dry.json.movedIn, mismatched: dry.json.mismatched }, { sites: [], movedIn: [], mismatched: [] }); + 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"); +}); + +// Review 1 M2 and S1: the published channel cannot be given a fetcher, and no door builds an address for one of its posts. +test("the published channel: Scraping method is refused and writes nothing; a Wayback lookup and transcribe-one of one of its posts are refused", async () => { + const SLUG = "kettle-festival-2026"; + const SAYS = `${SLUG} holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it.`; + const { setPostFetcherAction } = await import("../../../channels/[slug]/socialActions"); + const before = await readFile(path.join(ROOT, "channels", SLUG, "config.json"), "utf8"); + for (const fetcher of ["x-gallery-dl", "x-playwright", "nope"]) { + assert.deepEqual(await setPostFetcherAction(SLUG, fetcher), { ok: false, error: SAYS }); + } + assert.equal(await readFile(path.join(ROOT, "channels", SLUG, "config.json"), "utf8"), before, "no key was written"); + + const WAYBACK = (await import("../wayback-lookup/route")).POST; + const looked = await post(WAYBACK, "wayback-lookup", { slug: SLUG, id: A }); + assert.equal(looked.status, 400); + assert.equal(looked.json.error, SAYS); + + const TRANSCRIBE = (await import("../transcribe-one/route")).POST; + const transcribed = await post(TRANSCRIBE, "transcribe-one", { slug: SLUG, id: A }); + assert.ok(transcribed.status >= 400, JSON.stringify(transcribed.json)); + assert.equal(transcribed.json.jobId, undefined, "no job was made"); +}); diff --git a/editor/app/api/ops/publish-trending/route.ts b/editor/app/api/ops/publish-trending/route.ts @@ -0,0 +1,72 @@ +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, sites: [siteId], kept, posts, ids, already, +// movedIn: [{id, by, from}], files, bytes, mismatched: [{id, name}], +// 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). It also says what the operator should know before the +// press: `sites`, THE SITES THE CHANNEL IS ALREADY ON ("these posts go public +// at its next build"); `movedIn`, the posts to publish that somebody MOVED +// into this topic and who did (an agent may move posts); and `mismatched`, +// files whose bytes are no longer what their capture recorded (not copied). +// The `confirm` covers the sites too: a channel put on a site after the dry +// run refuses the publish. 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, one holding a post this topic +// never published, or one that is not the very directory this publish made: +// a channel deleted and made again by hand, even empty, is refused; so is a +// bare directory of the slug). +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/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts @@ -2,6 +2,8 @@ import { NextResponse } from "next/server"; import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient"; import { isWaybackExcluded } from "yt-dlp-transcript-common/lib/waybackClient"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-transcript-common/lib/sourcelessPosts"; import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy"; import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib"; @@ -35,6 +37,9 @@ export async function POST(request: Request) { } else if (hasRecord) { const slug = reqSlug(body, "slug"); const id = reqVideoId(body, "id"); + // Posts published from a private library have no page of their own to + // look up (review 1 S1): refused by name, before any address is built. + if (isSourcelessPostsChannel(await readChannelConfig(getPaths(), slug))) return opsFail(SOURCELESS_POSTS_CHANNEL(slug)); const found = await recordWebpageUrl(getPaths(), slug, id); if (!found) return opsFail(`no page is known for ${slug}/${id} (no metadata, availability check or playlist entry names one)`, 404); url = found; diff --git a/editor/app/api/ops/x-search-lead/route.ts b/editor/app/api/ops/x-search-lead/route.ts @@ -19,6 +19,20 @@ export const dynamic = "force-dynamic"; // 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`. +// +// AN X TRENDING LIBRARY'S ACCOUNTS ARE LEADS TOO (lane x-trending-publish): +// with `slug` a library, "archive" makes `<handle>-x` for an account that +// wrote a post the library holds — on no site, naming nothing of the library +// — and ASKS X NOTHING, now or later: no first fetch is started, and the +// channel is made with SYNC OFF (its priority tier `paused`, which the sync +// scheduler, Sync all and the lanes all honour; a never-synced channel with a +// URL would otherwise be fetched at the scheduler's next tick). The answer +// then carries `syncOff: true` and `sentence`, which says how to turn sync on +// (`pnpm ops channel-priority`, tier "normal") and run the first fetch +// (`pnpm ops fetch-posts`). `fetch: true` asks for the ordinary behaviour +// instead: the first fetch started, sync on. "never" and "restore" are a +// search channel's only. Read the accounts with `get trending <slug> +// --accounts`. export async function POST(request: Request) { return ops(request, ["slug", "handle", "action", "name", "fetch", "dryRun"], async (body) => { const slug = reqSlug(body, "slug"); @@ -29,12 +43,18 @@ export async function POST(request: Request) { const res = await archiveXSearchLeadAction(slug, handle, { ...(name ? { name } : {}), ...(optBool(body, "dryRun") ? { dryRun: true } : {}), - ...(optBool(body, "fetch") === false ? { fetch: false } : {}), + ...(optBool(body, "fetch") !== undefined ? { fetch: optBool(body, "fetch") === true } : {}), }); 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] } : {}) }); + return NextResponse.json({ + ok: true, + slug: res.slug, + jobIds, + ...(jobIds.length === 1 ? { jobId: jobIds[0] } : {}), + ...(res.syncOff ? { syncOff: true, sentence: res.sentence } : {}), + }); } if (body.dryRun !== undefined || body.name !== undefined || body.fetch !== undefined) { return opsFail(`"dryRun", "name" and "fetch" apply only to action "archive"`); diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -43,6 +43,7 @@ import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/sav import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; import { isXTrendingChannel, xTrendingLimits } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-transcript-common/lib/sourcelessPosts"; import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store"; import { XTrendingPanel } from "./components/XTrendingPanel"; import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk"; @@ -301,9 +302,11 @@ export default async function ChannelDetailPage({ lastFetchedCount: fetchState?.lastFetchedCount, lastError: fetchState?.lastError, needsCookies: fetchState?.needsCookies, - fetcherLabel: fetcher?.label ?? "no fetcher configured", + // Posts published from a private library: no source, so no fetcher + // to choose (the select is not offered) and the sentence says why. + fetcherLabel: isSourcelessPostsChannel(config) ? SOURCELESS_POSTS_CHANNEL(slug) : (fetcher?.label ?? "no fetcher configured"), fetcherId: fetcher?.id ?? "", - availableFetchers: await listPostFetchersFor(config.platform ?? ""), + availableFetchers: isSourcelessPostsChannel(config) ? [] : await listPostFetchersFor(config.platform ?? ""), deletedCount: availabilityRecords.filter((r) => isPostGone(r.availability), ).length, diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -23,6 +23,7 @@ import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-transcript-common/lib/sourcelessPosts"; import { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store"; import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements"; import { refuseWatchJob } from "yt-dlp-transcript-common/controller/xTrendingWatch"; @@ -103,6 +104,9 @@ export async function setPostFetcherAction( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a social channel.` }; } + // Posts published from a private library have no source for a fetcher to + // read (review 1 M2): the key is not written. + if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) }; await registerBuiltinSocialFetchers(); const wanted = fetcherId.trim(); const fetcher = getSocialFetcher(wanted); @@ -152,6 +156,8 @@ export async function checkPostAvailabilityAction( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a social channel.` }; } + // Posts published from a private library: nothing is asked of X for them. + if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) }; const key = resolveQueueKey(downloadQueueKey(config), queueKey); return runManagedFunction({ kind: "check-post-availability", @@ -246,6 +252,8 @@ export async function fetchPostsAction( if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; // An X trending library has no timeline: its pages are read one at a time. if (isXTrendingChannel(config)) return { ok: false, info: true, error: X_TRENDING_NOT_FETCHED(slug) }; + // Posts published from a private library: no account to fetch from. + if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) }; // 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 (backfill) { @@ -384,6 +392,8 @@ export async function capturePostsAction( if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a social channel.` }; } + // Posts published from a private library: their captures came with them. + if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) }; // A Wayback pages channel has no fetcher: its records are rendered from // their captures, on archive.org's queue (release 37 S4). const pages = isWaybackPagesChannel(config); diff --git a/editor/app/channels/[slug]/xSearchActions.ts b/editor/app/channels/[slug]/xSearchActions.ts @@ -15,12 +15,14 @@ import { setXSearchLeadHidden, type XSearchLeadsView, } from "yt-dlp-transcript-common/controller/xSearchLeads"; +import { isXTrendingLibrary } from "yt-dlp-transcript-common/lib/xTrending/library-server"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { applyChannelFormPatch } from "../components/channelConfigToForm"; -import { createChannelFromForm } from "../actions"; +import { applyChannelPriorityPresetAction, createChannelFromForm, setChannelTierAction } from "../actions"; +import { xLeadArchiveMode, xLeadSyncOffSentence } from "yt-dlp-transcript-common/lib/xSearch/leads"; export type XLeadActionResult = - | { ok: true; slug?: string; jobIds?: string[]; exclude?: string[]; changed?: boolean; dryRun?: boolean; fields?: Record<string, string> } + | { ok: true; slug?: string; jobIds?: string[]; exclude?: string[]; changed?: boolean; dryRun?: boolean; fields?: Record<string, string>; syncOff?: boolean; sentence?: string } | { ok: false; error: string }; export async function readXSearchLeadsAction( @@ -44,11 +46,33 @@ export async function archiveXSearchLeadAction( const fd = new FormData(); applyChannelFormPatch(fd, plan.fields); fd.set("slug", plan.slug); - if (opts.fetch !== false) fd.set("fetchPostsNow", "on"); + // From an X TRENDING LIBRARY's accounts (lane x-trending-publish) the press + // makes the channel and asks X nothing, now or at the scheduler's next tick: + // the channel is made with SYNC OFF (lib/xSearch/leads.ts xLeadArchiveMode + // says why). The tier is written BEFORE the channel is, so there is no + // moment at which the new channel exists and is due. From a search + // channel's leads nothing changes: the first fetch starts unless `fetch: + // false`, and no priority is written. + const library = await isXTrendingLibrary(getPaths().channelsDir, slug); + const mode = xLeadArchiveMode({ library, ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}) }); + if (mode.fetchNow) fd.set("fetchPostsNow", "on"); + if (mode.syncOff) { + const paused = await setChannelTierAction([plan.slug], "paused"); + if (paused?.error) return { ok: false, error: `The channel was not made: its sync could not be switched off first (${paused.error}).` }; + } const created = await createChannelFromForm(fd); - if (!created.ok) return { ok: false, error: created.error }; + if (!created.ok) { + // No channel: no entry for it either. + if (mode.syncOff) await applyChannelPriorityPresetAction([plan.slug], "clear"); + return { ok: false, error: created.error }; + } safeRevalidate([`/channels/${slug}`, `/channels/${created.slug}`, "/channels"]); - return { ok: true, slug: created.slug, jobIds: created.jobIds }; + return { + ok: true, + slug: created.slug, + jobIds: created.jobIds, + ...(mode.syncOff ? { syncOff: true, sentence: xLeadSyncOffSentence(created.slug, handle) } : {}), + }; } // Never archive (hidden: true) and its undo (hidden: false). 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,117 @@ 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, + readInFlight: () => libraryJobInFlight(ask.slug, [READ_X_TRENDING_KIND, REPARSE_X_TRENDING_KIND]), + }); + } 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/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -43,6 +43,7 @@ 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 { X_TRENDING_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL, syncSkipForShape } from "yt-dlp-transcript-common/lib/sourcelessPosts"; import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings"; import { LANES, @@ -370,6 +371,49 @@ export async function createChannelFromForm( return { ok: true, slug, jobIds, warnings: [] }; } +// The form fields that would give a channel a source. +const SOURCE_FIELDS = ["url", "socialHandle", "xSearchQuery", "waybackTargets"] as const; + +async function configureSourcelessPosts( + slug: string, + existing: NonNullable<Awaited<ReturnType<typeof readChannelConfig>>>, + formData: FormData, + values: ReturnType<typeof formValues>, +): Promise<ActionResult> { + const said = (k: string) => String(formData.get(k) ?? "").trim(); + const gives: string[] = SOURCE_FIELDS.filter((k) => said(k) !== ""); + const platform = said("platform"); + if (platform && platform !== "twitter") gives.push("platform"); + if (said("sourceKind") && said("sourceKind") !== "social") gives.push("sourceKind"); + if (said("postFetcher") && said("postFetcher") !== (existing.postFetcher ?? "")) gives.push("postFetcher"); + if (gives.length > 0) { + return { error: `${SOURCELESS_POSTS_CHANNEL(slug)} It cannot be given a source (${gives.join(", ")}): Configure sets its name and the sites that carry it.`, values }; + } + const paths = getPaths(); + let siteWrites: Site[] = []; + try { + const requests = parseSiteMembershipsField(formData.get("siteMembershipsJson")); + if (requests) siteWrites = planSiteMembershipWrites(paths, slug, requests); + } catch (e) { + return { error: (e as Error).message, values }; + } + const name = said("name"); + if (name && name !== existing.name) { + const written = await patchChannelConfig(paths, slug, { name }); + if (!written) return { error: `Channel "${slug}" not found`, values }; + } + try { + await applySiteWrites(siteWrites, paths); + } catch (e) { + return { error: (e as Error).message, values }; + } + revalidatePath("/channels"); + revalidatePath(`/channels/${slug}`); + revalidatePath("/sites"); + revalidatePath("/"); + return undefined; +} + export async function updateChannelAction( slug: string, _prev: ActionResult, @@ -390,6 +434,14 @@ export async function updateChannelAction( : `${slug} is not an X trending library, and Configure cannot make it one: create a new channel with platform "X trending library".`; const asked = libraryProblem(String(formData.get("platform") ?? "") === "x-trending"); if (asked) return { error: asked, values }; + // POSTS PUBLISHED FROM A PRIVATE LIBRARY (lane x-trending-publish; review 1 + // M2): the channel has no account, so the form's parse ("a social source + // needs an account handle") is not run for it. What Configure sets for such + // a channel is its NAME and THE SITES THAT CARRY IT — the operator's + // separate act after a publish, with `channel-config {slug, sites}` its ops + // twin. It cannot be given a source: a url, a handle, a search, a page + // scope, another platform or a fetcher is refused, and nothing is written. + if (isSourcelessPostsChannel(existing)) return configureSourcelessPosts(slug, existing, formData, values); let parsed; try { parsed = parseChannelForm(formData, { stored: existing }); @@ -673,7 +725,8 @@ export async function syncAllChannelsAction( // successful sweep over a channel nothing could read. skip: async (slug) => { const config = bySlug.get(slug); - if (!config?.url) return "no url"; + const shape = syncSkipForShape(config); + if (shape) return shape; if (isRemoteOnlyChannel(config)) return "remote-only"; if (isChannelPaused(priority, slug, "sync")) return "paused for sync"; if (active.has(slug)) return "already running"; diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -350,3 +350,195 @@ test("an X trending library: judgements, a watch tick, media kept once, gone fro expect(purged.posts.find((p) => p.id === NEW)?.capture).toBeUndefined(); expect(purged.posts.find((p) => p.id === B)).toMatchObject({ judgement: { state: "drop", by: "operator" } }); }); + +// SLICE 4 (lane x-trending-publish): the library's topics organised, a topic +// PUBLISHED into an ordinary channel on no site, and an account broken out. +// Over ops (umtool's Posts library page is the operator's form of the same +// actions: umtool/e2e/library.spec.ts). X is never contacted: the one read is +// the fake browser's, the capture is planted, and archiving an account from a +// library starts no fetch. +test("an X trending library: rename, move, merge; a topic published into an ordinary channel that names nothing of the library; an account archived with nothing asked of X", async ({ page, request }) => { + test.setTimeout(240_000); + await seed(); + const post = async (action: string, data: Record<string, unknown>) => { + const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data }); + return { status: res.status(), json: (await res.json()) as Record<string, any> }; + }; + const get = async (query: string) => (await (await request.get(`${baseUrl}/api/ops/trending?${query}`, { headers: AUTH })).json()) as Record<string, any>; + const A = "1900000000000001001"; + const B = "1900000000000001002"; + const D = "1900000000000001004"; + + const made = await post("create-channel", { slug: SLUG, fields: { name: "Trending", handling: "transcribe", platform: "x-trending" } }); + expect(made.status, JSON.stringify(made.json)).toBe(200); + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL, topic: "Kettle Festival" })).status).toBe(200); + await expect.poll(archiveLines, { timeout: 60_000 }).toBe(4); + // (The read's job has ended before anything below asks whether one is in flight.) + await expect.poll(async () => ((await (await request.get(`${baseUrl}/api/ops/jobs?active=1&slug=${SLUG}`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs?.length ?? 0, { timeout: 60_000 }).toBe(0); + + // RENAME (an agent may): the name changes, the id stays. + const renamed = await post("organise-trending", { slug: SLUG, op: "rename", topic: "kettle-festival", title: "Kettles 2026" }); + expect(renamed.json).toMatchObject({ ok: true, topic: "kettle-festival", title: "Kettles 2026", was: "Kettle Festival", changed: true }); + expect((await get(`slug=${SLUG}`)).topics.map((t: any) => [t.id, t.title])).toEqual([["kettle-festival", "Kettles 2026"]]); + + // MOVE a post into a new topic, then try to merge it back. + const moved = await post("organise-trending", { slug: SLUG, op: "move", to: "Spoons", ids: [B], create: true }); + expect(moved.json).toMatchObject({ ok: true, to: { id: "spoons", title: "Spoons", created: true }, moved: [B], skipped: [] }); + expect((await get(`slug=${SLUG}&topic=spoons`)).total).toBe(1); + // A merge is the operator's: an agent's is refused, and nothing changes. + const agentMerge = await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"] }); + expect(agentMerge.status).toBe(400); + expect(String(agentMerge.json.error)).toContain("Merging topics is the operator's press"); + // …and it waits for a read: one is started (the same page, read again), and the merge is refused while it is queued or running. + expect((await post("read-x-trending", { slug: SLUG, url: FIXTURE_TREND_URL })).status).toBe(200); + // S9: a rename waits for it too (a read may name its topic by its name)… + const renameWaits = await post("organise-trending", { slug: SLUG, op: "rename", topic: "spoons", title: "Spoons and forks", by: "operator" }); + expect(renameWaits.status).toBe(400); + expect(String(renameWaits.json.error)).toContain("A read of this library is queued or running: rename its topic once it has finished"); + const waiting = await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"], by: "operator" }); + expect(waiting.status).toBe(400); + expect(String(waiting.json.error)).toContain("A read of this library is queued or running: merge its topics once it has finished"); + expect((await get(`slug=${SLUG}`)).topics).toHaveLength(2); + let merged: Record<string, any> = {}; + await expect + .poll( + async () => { + merged = (await post("organise-trending", { slug: SLUG, op: "merge", into: "kettle-festival", from: ["spoons"], by: "operator" })).json; + return merged.ok === true; + }, + { timeout: 90_000 }, + ) + .toBe(true); + expect(merged).toMatchObject({ into: { id: "kettle-festival", title: "Kettles 2026" }, merged: [{ id: "spoons", title: "Spoons", posts: 1, pages: 0 }], posts: 1 }); + expect(String(merged.sentence)).toContain("This cannot be undone."); + const one = await get(`slug=${SLUG}&topic=spoons`); + expect(one.topics.map((t: any) => [t.id, t.posts, t.aliases])).toEqual([["kettle-festival", 4, ["spoons"]]]); + expect(one.total).toBe(4); + + // KEEP: the operator keeps A (its capture planted, as a capture job leaves one), an agent keeps D. + expect((await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: A, state: "keep", note: "a private note" }] })).json).toMatchObject({ kept: [A] }); + expect((await post("judge-trending", { slug: SLUG, archive: false, set: [{ id: D, state: "keep" }] })).json).toMatchObject({ kept: [D] }); + const libCapture = t(`channels/${SLUG}/trending/posts-media/${A}`); + await mkdir(libCapture, { recursive: true }); + await writeFile(`${libCapture}/shot.png`, "FIXTURE SHOT BYTES"); + await writeFile( + `${libCapture}/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: 18, sha256: "6d61761833abb83a81e789df143b2b3d569aeb136516ee31791ec30c60d26c2a" }, mediaState: "skipped", mediaOwed: "kept", media: [] }), + ); + + // PUBLISH, step one: what would be written. Nothing is. + const dry = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true }); + expect(dry.status, JSON.stringify(dry.json)).toBe(200); + expect(dry.json).toMatchObject({ dryRun: true, channel: "kettles-2026", creates: true, sites: [], kept: 1, posts: 1, ids: [A], already: 0, movedIn: [], files: 1, bytes: 18, mismatched: [], textOnly: [], noLongerKept: [] }); + expect(String(dry.json.sentence)).toContain('would make the channel "kettles-2026", on no site, writing 1 post and 1 file (18 B)'); + expect(await pathExists(rel("channels/kettles-2026"))).toBe(false); + // An agent may not publish; a confirm that is not this dry run's is refused. + const agent = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: dry.json.confirm }); + expect(agent.status).toBe(400); + expect(String(agent.json.error)).toContain("Publishing a topic is the operator's press"); + expect(String((await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: "0".repeat(24), by: "operator" })).json.error)).toContain("has changed since it was counted"); + expect(await pathExists(rel("channels/kettles-2026"))).toBe(false); + + // Step two, the operator's: an ordinary channel, on no site. + const done = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: dry.json.confirm, by: "operator" }); + expect(done.status, JSON.stringify(done.json)).toBe(200); + expect(done.json).toMatchObject({ dryRun: false, channel: "kettles-2026", creates: true, posts: 1, files: 1 }); + expect(await readJson<Config & { name?: string }>(rel("channels/kettles-2026/config.json"))).toEqual({ name: "Kettles 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + const lines = (await readFile(t("channels/kettles-2026/posts/2026-11.jsonl"), "utf8").catch(async () => { + const dir = t("channels/kettles-2026/posts"); + return readFile(`${dir}/${(await readdir(dir))[0]}`, "utf8"); + })).trim().split("\n").map((l) => JSON.parse(l) as { id: string; slug: string; channelSlug: string; author: string }); + expect(lines.map((p) => [p.id, p.slug, p.channelSlug, p.author])).toEqual([[A, `kettles-2026/${A}`, "kettles-2026", "teapot_news"]]); + // The shot is a COPY: its own inode, one name. + const copy = await stat(t(`channels/kettles-2026/posts-media/${A}/shot.png`)); + expect(await readFile(t(`channels/kettles-2026/posts-media/${A}/shot.png`), "utf8")).toBe("FIXTURE SHOT BYTES"); + expect(copy.ino).not.toBe((await stat(`${libCapture}/shot.png`)).ino); + expect(copy.nlink).toBe(1); + // NOTHING OF THE LIBRARY in the channel: not its slug, a judgement, the note, a read, what was owed. + const walk = async (dir: string): Promise<string[]> => (await Promise.all((await readdir(dir, { withFileTypes: true })).map((e) => (e.isDirectory() ? walk(`${dir}/${e.name}`) : [`${dir}/${e.name}`])))).flat(); + for (const file of await walk(t("channels/kettles-2026"))) { + const text = await readFile(file, "utf8"); + for (const word of [`${SLUG}/`, `"${SLUG}"`, "xTrending", "a private note", "judg", "operator", "agent", "mediaOwed", "tr-01", "gone"]) { + expect(text.includes(word), `${file} carries ${word}`).toBe(false); + } + } + // On no site; the agent's keep and the undecided posts stayed in the library. + expect(JSON.stringify(await readJson<Record<string, unknown>>(rel("sites/demo-site/site.json")))).not.toContain("kettles-2026"); + expect((await readJson<{ topics: Record<string, { slug: string; posts: Record<string, string> }> }>(rel(`channels/${SLUG}/trending/published.json`))).topics["kettle-festival"]).toMatchObject({ slug: "kettles-2026" }); + + // THE PUBLISHED CHANNEL MAKES NO REQUEST: a direct ask is refused with one sentence, and no job is made. + const SAYS = "kettles-2026 holds posts published from a private library: it has no account to fetch from"; + for (const [action, data] of [ + ["fetch-posts", { slug: "kettles-2026" }], + ["capture-posts", { slug: "kettles-2026", ids: [A] }], + ["check-post-availability", { slug: "kettles-2026" }], + ["x-run", { channels: ["kettles-2026"] }], + // Configure cannot give it a source (a url, a handle). + ["channel-config", { slug: "kettles-2026", patch: { url: "https://x.com/teapot_news" } }], + ["channel-config", { slug: "kettles-2026", patch: { socialHandle: "teapot_news" } }], + ] as const) { + const refused = await post(action, data); + expect(refused.status, `${action}: ${JSON.stringify(refused.json)}`).toBeGreaterThanOrEqual(400); + expect(String(refused.json.error), action).toContain(SAYS); + } + expect((((await (await request.get(`${baseUrl}/api/ops/jobs?slug=kettles-2026`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs ?? []).length).toBe(0); + // It is a channel like any other on the editor's pages. + await page.goto("/channels/kettles-2026"); + await expect(page.locator("body")).toContainText("Kettles 2026"); + + // RE-PUBLISH adds and removes nothing: A is dropped, B is kept. + await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: A, state: "drop" }, { id: B, state: "keep" }] }); + const again = await post("publish-trending", { slug: SLUG, topic: "spoons", dryRun: true }); + expect(again.json).toMatchObject({ channel: "kettles-2026", creates: false, sites: [], kept: 1, posts: 1, ids: [B], already: 0, files: 0, textOnly: [B], noLongerKept: [A] }); + // S5: B was moved (by an agent, into "spoons", which the operator's merge then brought here): the last hand is the merge's. + expect(again.json.movedIn).toEqual([{ id: B, by: "operator", from: "spoons" }]); + expect(String(again.json.sentence)).toContain("1 post to publish was moved into this topic: 0 by an agent, 1 by the operator."); + // S4: THE OPERATOR PUTS THE CHANNEL ON A SITE between the count and the press: the confirm no longer holds, and + // the next dry run names the site and says the post goes public. + // Configure sets a published channel's name and its sites, and nothing else (channel-config is its ops twin). + const onSite = await post("channel-config", { slug: "kettles-2026", patch: { name: "Kettles, 2026" }, sites: [{ siteId: "demo-site" }] }); + expect(onSite.status, JSON.stringify(onSite.json)).toBe(200); + expect(await readJson<Config & { name?: string }>(rel("channels/kettles-2026/config.json"))).toEqual({ name: "Kettles, 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); + expect(JSON.stringify((await readJson<{ channels: unknown }>(rel("sites/demo-site/site.json"))).channels)).toContain("kettles-2026"); + const stale2 = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: again.json.confirm, by: "operator" }); + expect(String(stale2.json.error)).toContain("has changed since it was counted"); + const named = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true }); + expect(named.json.sites).toEqual(["demo-site"]); + expect(String(named.json.sentence)).toContain("THIS CHANNEL IS ON THE SITE demo-site: this post goes public at its next build."); + again.json.confirm = named.json.confirm; + const second = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", confirm: again.json.confirm, by: "operator" }); + expect(second.status, JSON.stringify(second.json)).toBe(200); + expect(String(second.json.sentence)).toContain("1 post published before is no longer kept: it stays in the channel (a publish removes nothing)."); + expect((await readFile(t("channels/kettles-2026/posts-archive"), "utf8")).split("\n").filter(Boolean).sort()).toEqual([`twitter ${A}`, `twitter ${B}`]); + expect(await pathExists(rel(`channels/kettles-2026/posts-media/${A}/shot.png`))).toBe(true); + // A channel of the slug that this publish did not make is never appended to. + const taken = await post("publish-trending", { slug: SLUG, topic: "kettle-festival", dryRun: true, channel: "elsewhere" }); + expect(String(taken.json.error)).toContain('published into the channel "kettles-2026": a topic has one channel'); + + // THE ACCOUNTS, and one broken out: <handle>-x on no site, and X is asked nothing. + const accounts = await get(`slug=${SLUG}&accounts=1`); + expect(accounts.accounts.map((a: any) => a.handle).sort()).toEqual(expect.arrayContaining(["saucer_fan", "spout_clips", "teapot_news"])); + expect(accounts.accounts.find((a: any) => a.handle === "saucer_fan")).toMatchObject({ posts: 1, kept: 1, keptByOperator: 1, topics: ["kettle-festival"] }); + const plan = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive", dryRun: true }); + expect(plan.json).toMatchObject({ ok: true, dryRun: true, slug: "saucer_fan-x" }); + expect(await pathExists(rel("channels/saucer_fan-x"))).toBe(false); + const archived = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); + expect(archived.status, JSON.stringify(archived.json)).toBe(200); + expect(archived.json).toMatchObject({ ok: true, slug: "saucer_fan-x", jobIds: [], syncOff: true }); + // M1: MADE WITH SYNC OFF. A never-synced channel with a URL is the most overdue one the scheduler knows, so + // without this its next tick would fetch it. The sentence says so and how to turn it on. + expect(String(archived.json.sentence)).toBe( + `Made the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["saucer_fan-x"],"tier":"normal"}'). Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"saucer_fan-x"}').`, + ); + const settings = await readJson<{ channelPriority?: { channels?: Record<string, { tier?: string }> } }>(testPaths().settingsFile); + expect(settings.channelPriority?.channels?.["saucer_fan-x"]).toMatchObject({ tier: "paused" }); + // (That a paused tier keeps it out of the scheduler, Sync all and the lanes: common/jobs/xLeadSyncOff.test.ts.) + const account = await readJson<Config>(rel("channels/saucer_fan-x/config.json")); + expect(account).toMatchObject({ platform: "twitter", sourceKind: "social", url: "https://x.com/saucer_fan", socialHandle: "saucer_fan" }); + expect(JSON.stringify(account)).not.toContain(SLUG); + expect((((await (await request.get(`${baseUrl}/api/ops/jobs?slug=saucer_fan-x`, { headers: AUTH })).json()) as { jobs?: unknown[] }).jobs ?? []).length).toBe(0); + expect(JSON.stringify(await readJson<Record<string, unknown>>(rel("sites/demo-site/site.json")))).not.toContain("saucer_fan-x"); + expect((await get(`slug=${SLUG}&accounts=1`)).accounts.find((a: any) => a.handle === "saucer_fan").archivedAs).toEqual(["saucer_fan-x"]); + const twice = await post("x-search-lead", { slug: SLUG, handle: "saucer_fan", action: "archive" }); + expect(String(twice.json.error)).toContain("@saucer_fan is already archived: saucer_fan-x."); +}); diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts @@ -52,6 +52,7 @@ const EXPECTED_TOOLS = [ "x_search_leads", "x_trending_topics", "x_trending_posts", + "x_trending_accounts", "generation_policy", "generate", "list_sources", diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -100,7 +100,7 @@ import { type ToolAnswer, } from "./archivalTools"; import { X_SEARCH_TOOLS, xSearchLeadsTool } from "./xSearchLeads"; -import { X_TRENDING_TOOLS, xTrendingPostsTool, xTrendingTopicsTool } from "./xTrending"; +import { X_TRENDING_TOOLS, xTrendingAccountsTool, xTrendingPostsTool, xTrendingTopicsTool } from "./xTrending"; import { GENERATION_TOOLS, generateTool, @@ -1357,6 +1357,8 @@ export function createServer( return fromAnswer(await xTrendingTopicsTool(args, fetchClipDeps)); case "x_trending_posts": return fromAnswer(await xTrendingPostsTool(args, fetchClipDeps)); + case "x_trending_accounts": + return fromAnswer(await xTrendingAccountsTool(args, fetchClipDeps)); case "notes": return fromAnswer(await notesTool(args, fetchClipDeps)); case "generation_policy": diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -163,3 +163,43 @@ test("the tools say a topic's watch, and a post's thread, capture, gone-from-the " judged keep by operator (its thread) (2026-11-18 09:00 UTC)", ]); }); + +// Lane x-trending-publish: the library's accounts. +test("x_trending_accounts: one GET with accounts=1; handle, posts, kept, topics and who archives it", async () => { + const ACCOUNTS = { + ok: true, + slug: "trending", + accounts: [ + { handle: "teapot_news", key: "teapot_news", name: "Teapot News", posts: 3, kept: 2, keptByOperator: 1, topics: ["kettle-festival", "cups"], last: "2026-11-16T12:00:00.000Z" }, + { handle: "saucer_fan", key: "saucer_fan", posts: 1, kept: 0, keptByOperator: 0, topics: ["cups"], last: "2026-11-16T13:00:00.000Z", archivedAs: ["saucer_fan-x"] }, + ], + total: 4, + posts: 6, + more: 2, + }; + const { deps, sent } = fakeEditor(() => ({ status: 200, body: ACCOUNTS }), env); + const client = await connectWith(deps); + const res = await client.callTool({ name: "x_trending_accounts", arguments: { channel: "trending", topic: "cups", limit: 2 } }); + assert.ok(!isError(res)); + assert.equal(sent.length, 1); + assert.equal(sent[0].method, "GET"); + assert.equal(new URL(sent[0].url).pathname, "/api/ops/trending"); + assert.deepEqual([...new URL(sent[0].url).searchParams.entries()], [["slug", "trending"], ["accounts", "1"], ["topic", "cups"], ["limit", "2"]]); + const text = body(res); + assert.match(text, /^X trending library trending, topic cups: 4 accounts over 6 posts \(2 listed, 2 more\)\./); + assert.match(text, /- @teapot_news \(Teapot News\): 3 posts, 2 kept \(1 by the operator\); topics: kettle-festival, cups; newest 2026-11-16 12:00/); + assert.match(text, /- @saucer_fan: 1 post; topics: cups; newest 2026-11-16 13:00; already archived as saucer_fan-x/); + assert.match(text, /From a library it asks X nothing/); + + assert.match(textOf(await client.callTool({ name: "x_trending_accounts", arguments: { channel: "" } })), /channel is required/); + assert.match(textOf(await client.callTool({ name: "x_trending_accounts", arguments: { channel: "trending", limit: 501 } })), /limit is a whole number, 1–500/); + assert.match(textOf(await client.callTool({ name: "x_trending_accounts", arguments: { channel: "trending", topic: " " } })), /topic is a topic's id/); + assert.equal(sent.length, 1, "a refused ask sends nothing"); +}); + +test("the MCP has a tool to read a library's accounts and none to organise or publish", async () => { + const { deps } = fakeEditor(() => ({ status: 200, body: {} }), env); + const client = await connectWith(deps); + const names = (await client.listTools()).tools.map((t) => t.name).filter((n) => /trending/.test(n)); + assert.deepEqual(names.sort(), ["x_trending_accounts", "x_trending_posts", "x_trending_topics"]); +}); diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -146,6 +146,65 @@ export async function xTrendingPostsTool(args: Record<string, unknown>, deps: Ed return { text: renderXTrendingPosts(channel, a.body as ListingBody, topic) }; } +// ─── x_trending_accounts (lane x-trending-publish, slice 4) ─── +// +// THE LIBRARY'S ACCOUNTS, like an X search channel's leads: who wrote the +// posts it holds (GET /api/ops/trending?slug=&accounts=1[&topic=][&limit=]). +// Read only. Organising a library's topics and publishing one are asks of the +// editor (`pnpm ops`), and a publish is the operator's: this server has no +// tool for either. + +type AccountRow = { handle: string; name?: string; posts: number; kept: number; keptByOperator?: number; topics?: string[]; last?: string; archivedAs?: string[] }; +type AccountsBody = { accounts?: AccountRow[]; total?: number; posts?: number; more?: number }; + +export const X_TRENDING_ACCOUNTS_MAX = 500; + +export function renderXTrendingAccounts(slug: string, body: AccountsBody, topic?: string): string { + const rows = body.accounts ?? []; + const where = topic ? `${slug}, topic ${topic}` : slug; + const lines = [`X trending library ${where}: ${body.total ?? rows.length} account${(body.total ?? rows.length) === 1 ? "" : "s"} over ${body.posts ?? 0} post${body.posts === 1 ? "" : "s"}${body.more ? ` (${rows.length} listed, ${body.more} more)` : ""}.`]; + if (rows.length === 0) lines.push("No account yet: read a trending page into the library first (`pnpm ops read-x-trending`)."); + for (const a of rows) { + const kept = a.kept ? `, ${a.kept} kept${a.keptByOperator !== undefined && a.keptByOperator !== a.kept ? ` (${a.keptByOperator} by the operator)` : ""}` : ""; + lines.push( + `- @${a.handle}${a.name ? ` (${a.name})` : ""}: ${a.posts} post${a.posts === 1 ? "" : "s"}${kept}` + + `${a.topics?.length ? `; topics: ${a.topics.join(", ")}` : ""}` + + `${a.last ? `; newest ${day(a.last)}` : ""}` + + `${a.archivedAs?.length ? `; already archived as ${a.archivedAs.join(", ")}` : ""}`, + ); + } + lines.push( + "", + "Archiving an account as its own X channel (<handle>-x, on no site) is the operator's or an agent's ask of the editor: " + + "`pnpm ops x-search-lead --json '{\"slug\":\"<library>\",\"handle\":\"<handle>\",\"action\":\"archive\",\"dryRun\":true}'`. From a library it asks X nothing: the first fetch is a separate step.", + ); + return lines.join("\n"); +} + +export async function xTrendingAccountsTool(args: Record<string, unknown>, deps: EditorDeps): Promise<ToolAnswer> { + const channel = slugOf("x_trending_accounts", args); + if (typeof channel !== "string") return channel; + const q = new URLSearchParams({ slug: channel, accounts: "1" }); + let topic: string | undefined; + if (args.topic !== undefined) { + if (typeof args.topic !== "string" || !args.topic.trim()) { + return { text: "x_trending_accounts: topic is a topic's id (x_trending_topics lists them)", isError: true }; + } + topic = args.topic.trim(); + q.set("topic", topic); + } + if (args.limit !== undefined) { + const n = Number(args.limit); + if (!Number.isInteger(n) || n < 1 || n > X_TRENDING_ACCOUNTS_MAX) { + return { text: `x_trending_accounts: limit is a whole number, 1–${X_TRENDING_ACCOUNTS_MAX}`, isError: true }; + } + q.set("limit", String(n)); + } + const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`); + if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_accounts", a), isError: true }; + return { text: renderXTrendingAccounts(channel, a.body as AccountsBody, topic) }; +} + export const X_TRENDING_TOOLS = [ { name: "x_trending_topics", @@ -191,4 +250,24 @@ export const X_TRENDING_TOOLS = [ additionalProperties: false, }, }, + { + name: "x_trending_accounts", + description: + "The ACCOUNTS of an X TRENDING LIBRARY (or of one of its topics), like an X search channel's " + + "leads: each account's handle and name, how many of the library's posts it wrote, how many of " + + "them are kept, the topics they are in, and the X channels that already archive it — most " + + "posts first. For deciding which account deserves an archive of its own (`pnpm ops " + + "x-search-lead`, action \"archive\": <handle>-x on no site). PRIVATE material, like the " + + "library's posts. Read only. Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", + inputSchema: { + type: "object", + properties: { + channel: { type: "string", description: "The X trending library's slug (the editor's)." }, + topic: { type: "string", description: "A topic's id (from x_trending_topics): only its posts' accounts." }, + limit: { type: "number", description: `Accounts to list (default 100, at most ${X_TRENDING_ACCOUNTS_MAX}).` }, + }, + required: ["channel"], + additionalProperties: false, + }, + }, ] as const; diff --git a/mcp/src/xTrendingPrivacy.test.ts b/mcp/src/xTrendingPrivacy.test.ts @@ -177,7 +177,9 @@ test("every read-only corpus tool over the composed site: the account's post, ne // THE MCP BUILDS ITS QUERY WITH `new URLSearchParams({…})` AND `.set("…")`, so // that is what is read: every key given to either, in a source that asks the // listing, is one of the three. -const LISTING_KEYS = new Set(["slug", "topic", "limit"]); +// `accounts` (lane x-trending-publish): the library's accounts, a read like +// the other two. Still never a judge view's key. +const LISTING_KEYS = new Set(["slug", "topic", "limit", "accounts"]); function queryKeys(text: string): string[] { const keys: string[] = []; @@ -203,6 +205,11 @@ test("posts-library: no MCP source asks the listing for the judge view's fields, let asking = 0; for (const name of sources) { const text = readFileSync(path.join(here, name), "utf8"); + // Lane x-trending-publish: nor a way to organise a library or publish a + // topic — those are asks of the editor, and a publish is the operator's. + for (const word of ["/api/ops/organise-trending", "/api/ops/publish-trending", "publishXTrending", "organiseXTrending", "mergeXTrendingTopics", "published.json"]) { + assert.ok(!text.includes(word), `mcp/src/${name} names ${word}`); + } for (const word of ["purge-trending", "purgeXTrending", "removeXTrendingPostCapture", "/api/library", "judge-trending\"", "watch-trending\""]) { assert.ok(!text.includes(word), `mcp/src/${name} names ${word}`); } diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -220,10 +220,126 @@ again by the watch; keeping the post asks again. another hand's entry); the bar says so. A bulk press over more than 500 posts whose later chunk fails says how many were written and returns the undo of those. -## Slice 4: topics and publishing +## Slice 4, as built: topics, publishing, accounts (lane `lane/x-trending-publish`) -Rename, merge, move a post between topics; publish a topic's kept posts into an ordinary posts channel; -break out a user. +**Rulings (orchestrator, 18 Nov; the operator may overturn, each is one place in the code).** + +1. Rename and move are an agent's or the operator's and record who. **Merge is the operator's**: there is no unmerge. +2. Two live watches on a merge: the target's stands with its own terms; the sentence says so. +3. The channel's slug is derived from the topic's title at the first publish (the New channel form's slugify), may be + named in the ask, and is then fixed in the library's record. +4. The published channel carries no mark. "Made by this publish" is the library's record and the channel itself + (its content, and which directory it is). +5. A kept post with no capture is published as its words (`textOnly`); a later publish adds its files. +6. Archiving an account from a library asks X nothing by default (`fetch: false`), now or at the scheduler's next + tick: the channel is made with sync off. +7. The published posts' availability entries go to the channel. +8. The published channel makes no request anywhere. +9. A publish is refused while a read, a reparse or a capture of the library is queued or running. + +**As built.** + +- **Organise** (`common/lib/xTrending/organise.ts`, `organise-trending`). `store.ts` stays the one writer of + `topics.json` and `membership.json` (`mutateXTrendingTopics`, `mutateXTrendingMembership`). A topic gains + `aliases` (the ids merged into it; `resolveXTrendingTopic` is the one rule for "which topic an ask names", used + by a read, the listing and every organise step) and `organised` (its last rename or merge); a member gains + `moved`. A merge writes the membership, the watches, then the topics, inside the topics file's lock, in an order + a second run completes. It asks the job registry for a read or a reparse of the library before and inside the + lock. A move is safe beside a read (a read never moves a placed post) and is not refused for one. +- **Publish** (`common/controller/publishXTrending.ts`, `publish-trending`). Two steps held by a digest of the + library, the topic, the slug, the exact posts and the exact files; the set is read again inside the media + index's lock. Posts are rebuilt from an explicit allowlist: `POST_FIELDS satisfies Record<keyof Post, boolean>` + makes a new field of `Post` a compile error until it is decided, and it is not copied until then; `slug` and + `channelSlug` are the channel's. A capture is the files its record names and a record rebuilt from an allowlist, + without `mediaOwed`, `error` and `threadError`. The channel is made with `createChannel`, the posts written with + `writePosts`, the availability with `writePostAvailability`. +- **Copies, never links.** `copyFile` with `COPYFILE_FICLONE` to a temp name, checked against its source, renamed. + The purge frees a blob only when nothing else links to it, so a hardlink into the channel would keep every blob + and make the purge's count untrue. Pinned: no published inode is a library inode and each has one name; a purge + after a publish frees exactly what it frees without one; deleting either side leaves the other whole. +- **"Made by this publish"** is `trending/published.json` (`common/lib/xTrending/published.ts`: topic id → slug, + times, post ids), written BEFORE the posts, and a three-part proof asked of a channel that exists: the record + names the slug; the channel still has the source-less shape; it holds no post the record does not name. +- **A posts channel with no source** (`common/lib/sourcelessPosts.ts`): an X posts channel with no url, handle, + fetcher, search, page or marker. `platform: "twitter"` keeps `social.x.visibility` applying to it. One + predicate, asked by `fetchPosts`, `capturePosts`, `checkPostAvailability`, the X run (its list and a direct + ask), Sync all's skip reason and Configure; `common/controller/sourcelessPosts.test.ts` pins that no fetcher is + called and no binary run. +- **Accounts** (`common/lib/xTrending/accounts.ts`, `GET /api/ops/trending?accounts=1`, the MCP's + `x_trending_accounts`). `planArchiveXLead` takes a library, for an account that wrote a post it holds; the + editor's archive action starts no fetch from a library unless asked. +- **umtool**: `/api/library/{organise,publish,archive}` are the page's only, stamped the operator's + (`lib/library/presses.mjs`); `GET /api/library/accounts`; `umtool library rename | move | merge | publish | + accounts | archive`. After a merge umtool's Mark seen state follows (`seen.mjs mergeSeen`: the earliest of the + merged topics' marks stands; a topic that stays and was never marked stays unmarked). +- **The pins, as they now distinguish.** The library stays behind every door (the four pins of slices 1 to 3 are + unchanged in what they refuse). The published channel is an ordinary channel: + `common/controller/publishXTrending.test.ts` pins that it holds exactly the operator's keeps and that no file of + it carries the library's slug, a note, a read id, a judgement, a hand, a watch or a gone mark; + `common/bin/xTrendingPublishedSite.test.ts` puts the published channel on a site through the site writer, builds + the index and composes the site, and finds the operator's kept post there and nothing else of the library (and + that `social.x.visibility` still covers the channel, and that no build or publisher module imports the publish + or organise bodies). The MCP's sweep + allows the listing key `accounts` and refuses any source naming the organise or publish routes. umtool's sweep + names the three new editor asks as the only ways out of a library, the lead action as "archive" only, and that no + site is named to the editor from the page. + +**Found on the way.** + +- A stored library post carries the library's slug in `slug` and `channelSlug`: a copy of the record would have + named the library in every published post. +- A source-less X posts channel did not exist. Configure asked it for an account handle, `fetch-posts` answered "No + post fetcher", and an X run listed it. The only other multi-author X channel, an X search channel, is barred from + every site; a published topic is the first a site may carry. +- `common/controller/xTrendingGuards.test.ts` used that source-less shape as its example of an X posts channel; the + example now carries an account. +- umtool's slice-3 e2e line "no button says publish" now says there is exactly one, the topic's. + +**Review 1 (18 Nov), as fixed.** + +- **M1.** "Archive this account" from a library caused a fetch at the scheduler's next tick: a never-synced channel + with a URL is maximally overdue (`common/jobs/syncScheduler.ts overdueAmount`). The channel is now made with + SYNC OFF: its priority tier `paused`, written before the channel is (`xLeadArchiveMode`, + `editor/app/channels/[slug]/xSearchActions.ts`). `paused` is the one switch the scheduler, Sync all and the lanes + ask (`isChannelPaused`); `common/jobs/xLeadSyncOff.test.ts` shows the channel due without it and out of every + operation with it. A search channel's lead is archived as before, pinned by the same function. +- **M2.** A fetcher key is not a source: `isSourcelessPostsChannel` no longer asks `postFetcher`, and + `setPostFetcherAction` refuses such a channel. The other writers of a source key, one by one: Configure (now + sets the name and the sites only, and refuses a url, a handle, a search, a page scope, another platform or + kind, a fetcher); `setWaybackAutoAction` (needs an existing page scope: refused); `setXSearchLeadHidden` (needs + an X search channel: refused); the trending settings (need a library: refused); local media (refuses a posts + channel); the rest (`lastSyncedAt`, `mediaDir`, the exclude flags, the sync intervals) write no source key. +- **Found while fixing M2: Configure refused a published channel outright, and Configure's Sites section is how a + channel is put on a site** (with `channel-config {sites}` its ops twin). The operator's "separate, existing act" + had no door. Configure now sets such a channel's name and sites. +- **S1.** `findVideoSourceUrl` answers null for a source-less channel; the fetch-windows job fails such an item + before any lookup, whatever address it carries; `wayback-lookup {slug, id}` and `import-post` refuse by name. +- **S2, S3.** The proof has a fourth part: the record keeps the channel DIRECTORY's inode and birth time (not + config.json's: a config is rewritten through a rename, so its inode changes with every edit). A channel deleted + and made again by hand, even empty, is refused; so is a bare directory of the slug. A publish cut between making + the channel and recording which directory it was leaves the record `pending`, and the next publish takes the + channel up only while it holds no post. +- **S4, S5, S8.** The dry run names the sites the channel is on (in the digest too), the posts to publish that + were moved into the topic and by whom, and the files whose bytes are no longer what their capture recorded (not + copied, no digest written for them). +- **S6.** A move into a new topic writes the topic before the posts. **S7.** A merge carries the merged topic's + publish record to a target that has none, and otherwise leaves that channel as it is and says so. **S9.** A + rename waits for a read, as a merge does. +- **S10 and the nits.** The pin has the three precedence cases; a capture's context posts, a thread shot's + redaction and an article's extraction are rebuilt field by field; an interrupted copy's temp names are swept + under the lock; the plan (judgements, membership, captures, record, sites) is read from disk inside the lock; + ids are digits before they are paths; `planArchiveXLead` asks the posts, not a capped listing; a thread is + moved by the key the listing shows. + +**Left.** + +- A published post is not removed by a later drop (ruled: reported, never deleted). There is no "unpublish". +- `renameChannel` of a published channel is not followed by the library's record: the next publish makes a new + channel under the recorded slug and leaves the renamed one alone. +- A channel made by "Archive this account" from a library stays paused until the operator sets its priority to + normal: nothing reminds him that it is. +- A file system that keeps no birth time leaves the directory proof with the inode alone. +- The library's settings still have no form. ## Open 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,17 @@ 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, now or later: no first fetch is", + " started and the channel is made with SYNC OFF (its priority tier", + " paused, which the scheduler, Sync all and the lanes honour) ->", + " {slug, jobIds: [], syncOff: true, sentence}. The sentence says how to", + " turn sync on (channel-priority, tier normal) and run the first fetch", + " (fetch-posts). \"fetch\": true asks for the ordinary behaviour instead", + " (the first fetch started, sync on). \"never\" and", + " \"restore\" are a search channel's only.", "", '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 +2021,61 @@ 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,", + " and so is a rename while a read or a reparse of the library is queued", + " or running (a read may name its topic by its name).", + ' {"slug", "op": "move", "to", "ids": [..] | "thread", "create"?} moves', + " posts (or every post of one thread, by its root post's id) into the", + ' topic "to" (an id or a name; "create": true makes a topic of that name,', + " with no trending page, when there is none) -> {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. A topic has one published", + " channel too (published: {carried?, left}): the target's stays; with", + " none, the first merged topic's becomes its own; any other is left as it", + " is, never added to again, and named in the sentence.", + "", + 'publish-trending publishes a topic of an X trending library, in two', + ' steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it', + " says what would be written (channel, creates, posts, ids, already,", + " files, bytes, textOnly, noLongerKept) and what to know before the", + " press: sites (the sites the channel is ALREADY ON: what is added goes", + " public at their next build), movedIn (posts to publish that were moved", + " into the topic, and by whom) and mismatched (files that no longer match", + " the digest their capture recorded: not copied). It answers \"confirm\",", + " a digest of exactly that, the sites included.", + ' Then {"slug", "topic", "confirm", "by": "operator"} publishes:', + " the topic's posts whose judgement in force is keep BY THE OPERATOR", + " (their own entry, or their thread's) go into an ORDINARY posts channel", + ' ("channel": a slug of the topic\'s name unless given, fixed at the first', + " publish) with their captured media and screenshots, COPIED (the library", + " keeps its own; a purge of the library and a delete of the channel do", + " not reach each other). An agent's keep is not published. The channel is", + " on NO site (adding it to one is a separate step: site-config, /sites),", + " names nothing of the library (no judgement, note, read, watch or gone", + " mark) and is never fetched. It is the operator's press: an agent's", + " publish is refused (an agent may ask for the dry run), and a confirm", + " that no longer matches is refused with nothing written. Re-publishing", + " adds newly kept posts and files and removes nothing: a post published", + " before and since dropped is listed in noLongerKept and left; textOnly", + " lists kept posts with no capture yet (published as their words; a later", + " publish adds the files). Refused while a read, a reparse or a capture", + " of the library is queued or running (a dry run then says inFlight),", + " and when a channel of that slug exists that this publish did not make", + " (no record of it, a source of its own, a post this topic never", + " published, or not the very directory this publish made: a channel", + " deleted and made again by hand is refused, even empty).", + "", '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/); diff --git a/umtool/app/api/library/accounts/route.ts b/umtool/app/api/library/accounts/route.ts @@ -0,0 +1,31 @@ +import { askEditor } from "@/lib/articles/generation"; +import { listAccounts } from "@/lib/library/client.mjs"; +import { unavailableSentence } from "@/lib/library/load"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library/accounts?lib=&topic= -> { ok: true, accounts: [{handle, name?, posts, kept, keptByOperator, +// topics, last, archivedAs?}], total, posts, more } or { ok: false, sentence } +// +// THE LIBRARY'S ACCOUNTS (lane x-trending-publish), read THROUGH THE EDITOR +// (GET /api/ops/trending?accounts=1) when the page's Accounts panel is +// opened. READ ONLY, and a private library's: a cross-site request is +// refused, and nothing caches it. +const PRIVATE = { "cache-control": "private, no-store", "cross-origin-resource-policy": "same-origin" }; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export async function GET(request: Request) { + if (crossSiteRefusal(request.headers)) return Response.json({ error: "refused: the library is read by umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const sp = new URL(request.url).searchParams; + const lib = sp.get("lib") ?? ""; + const topic = sp.get("topic") ?? ""; + if (!SLUG.test(lib)) return Response.json({ ok: false, sentence: `"lib" is the library's slug` }, { status: 400, headers: PRIVATE }); + try { + const ask = (route: string) => askEditor<Record<string, unknown>>(route, { fresh: true }); + const answer = await listAccounts(ask, { slug: lib, ...(topic ? { topic } : {}), limit: 200 }); + return Response.json({ ok: true, accounts: answer.accounts ?? [], total: answer.total ?? 0, posts: answer.posts ?? 0, more: answer.more ?? 0 }, { headers: PRIVATE }); + } catch (err) { + return Response.json({ ok: false, ...unavailableSentence(err) }, { headers: PRIVATE }); + } +} diff --git a/umtool/app/api/library/archive/route.ts b/umtool/app/api/library/archive/route.ts @@ -0,0 +1,18 @@ +import { archivePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, handle, name?, dryRun? } -> { ok, slug, dryRun?, fields?, jobIds?, sentence } +// +// THE POSTS LIBRARY PAGE'S "ARCHIVE THIS ACCOUNT" (lane x-trending-publish): +// the editor's `x-search-lead`, action "archive", for an account that wrote a +// post the library holds — `<handle>-x`, an X channel on NO site that names +// nothing of the library. The page's press only (lib/library/route.ts). IT +// ASKS X NOTHING, now or later: this route never sends "fetch", and the editor +// makes the channel with SYNC OFF (a never-synced channel with a URL would +// otherwise be fetched at the scheduler's next tick). The answer's sentence is +// the editor's: it says how to turn sync on and run the first fetch. +export async function POST(request: Request) { + return press(request, (body) => archivePress(ask, body)); +} diff --git a/umtool/app/api/library/organise/route.ts b/umtool/app/api/library/organise/route.ts @@ -0,0 +1,19 @@ +import { organisePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; +import { mergeSeen } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, op: "rename", topic, title } -> { topic, title, was, changed, sentence } +// POST { lib, op: "move", to, ids | thread, create? } -> { to, moved, skipped, sentence } +// POST { lib, op: "merge", into, from: [topic, …] } -> { into, merged, posts, pages, watch, sentence, seen? } +// +// THE POSTS LIBRARY PAGE'S ORGANISING (lane x-trending-publish): the editor's +// `organise-trending`, written as the OPERATOR's (the page's press only: +// lib/library/route.ts). umtool writes no file of the library. A merge cannot +// be undone; after one, umtool's own Mark seen state follows it (the earliest +// of the merged topics' marks stands: lib/library/seen.mjs mergeSeen). +export async function POST(request: Request) { + return press(request, (body) => organisePress(ask, body, { mergeSeen: (lib: string, into: string, from: string[]) => mergeSeen(REPORTS_ROOT, { slug: lib, into, from }) })); +} diff --git a/umtool/app/api/library/publish/route.ts b/umtool/app/api/library/publish/route.ts @@ -0,0 +1,16 @@ +import { publishPress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic, dryRun: true, channel? } -> what would be written: { channel, creates, posts, files, bytes, textOnly, noLongerKept, confirm, sentence, … } +// POST { lib, topic, confirm, channel? } -> published, when it is still what the dry run showed +// +// THE POSTS LIBRARY PAGE'S PUBLISH (lane x-trending-publish): the editor's +// `publish-trending`, the OPERATOR's, in two presses (the page's press only: +// lib/library/route.ts). The topic's posts the operator kept go into an +// ordinary posts channel on NO site; umtool writes nothing itself, and adding +// the channel to a site stays a separate act in the editor. +export async function POST(request: Request) { + return press(request, (body) => publishPress(ask, body)); +} diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -14,6 +14,7 @@ import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; import type { LibraryData, LibraryPost, LibraryTopic, LibraryView as View } from "@/lib/library/load"; import { cn } from "@/lib/utils"; +import { AccountsPanel, MoveControl, send, TopicOrganise } from "./OrganisePanel"; // THE POSTS LIBRARY (app/tools/library/page.tsx): topics on the left, the // posts of the view with their captured media in the body, and the presses. @@ -67,12 +68,6 @@ export function utc(iso: string): string { return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}, ${p(d.getUTCHours())}:${p(d.getUTCMinutes())} UTC`; } -async function send(path: string, body: unknown): Promise<Record<string, unknown>> { - const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); - const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; - if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); - return j; -} /** The archive row a library post is drawn from. Never marked deleted: the library records no such thing. */ function postOf(lib: string, row: LibraryPost): Post { @@ -369,7 +364,8 @@ export default function LibraryView({ data: opened }: { data: Ok }) { <section className="min-w-0"> {/* A purge takes the undo memory with it: an undo must never put back a keep whose capture was just removed. */} - <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} onPurged={() => setLast(null)} /> + <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} onPurged={() => setLast(null)} go={(id) => router.push(here({ topic: id }))} /> + <AccountsPanel key={`accounts-${topic?.id ?? "all"}`} lib={lib} topic={topic?.id ?? null} topics={topics} off={off} run={run} /> {/* ── filters: links and one plain form, so they work before the page is alive ── */} <div data-library-filters="" className="mb-3 mt-3 flex flex-wrap items-center gap-x-2 gap-y-2"> @@ -640,6 +636,7 @@ export default function LibraryView({ data: opened }: { data: Ok }) { </Button> ))} </span> + <MoveControl lib={lib} topics={topics} here={topic?.id ?? null} targets={targetsOf(current)} off={off} run={run} /> <Button size="sm" disabled={off || !last} data-library-undo="" title={UNDO_SAYS} onClick={() => void undo()}> Undo </Button> @@ -726,7 +723,7 @@ function TopicList({ topics, view, here, lib }: { topics: LibraryTopic[]; view: ); } -function TopicPanel({ lib, topic, topics, off, run, onPurged }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void>; onPurged: () => void }) { +function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void>; onPurged: () => void; go: (topicId: string) => void }) { const w = topic?.watch; const live = !!w && w.on && !w.ended; const failing = live && w?.paused?.reason === "failing"; @@ -836,6 +833,8 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged }: { lib: string; t Purge dropped posts’ captures… </Button> </div> + {/* Rename, merge and publish: the topic's own (lane x-trending-publish). */} + {topic && <TopicOrganise key={`${topic.id}:${topic.title}`} lib={lib} topic={topic} topics={topics} off={off} run={run} go={go} when={utc} />} {plan && ( <div role="alertdialog" aria-label="Purge" data-library-purge-plan={plan.posts} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> <p className="m-0" data-library-purge-sentence=""> diff --git a/umtool/components/tools/library/OrganisePanel.tsx b/umtool/components/tools/library/OrganisePanel.tsx @@ -0,0 +1,345 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import type { LibraryTopic } from "@/lib/library/load"; + +// ORGANISE, PUBLISH AND THE ACCOUNTS of the Posts library page (lane +// x-trending-publish). Every press is a POST to /api/library/*, which is the +// editor's action written as the operator's; nothing here writes a library's +// file or asks X anything. +// +// rename the topic's name; its id stays +// merge this topic INTO another: there is no unmerge, so it is asked +// twice, and the second press says so +// move the posts a press would judge (the selection, else the post or +// its thread) into another topic +// publish the posts the operator KEPT, into an ordinary channel on no +// site: the first press says exactly what would be written +// accounts who wrote the library's posts; "Archive this account" makes +// <handle>-x on no site, with sync off, and asks X nothing + +type Run = (what: () => Promise<string | void>) => Promise<void>; + +export async function send(path: string, body: unknown): Promise<Record<string, unknown>> { + const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); + return j; +} + +const field = "rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text"; + +export function bytesSaid(n: number): string { + if (n < 1024) return `${n} B`; + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; + if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`; + return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`; +} + +type PublishPlan = { + channel: string; + creates: boolean; + kept: number; + posts: number; + already: number; + files: number; + bytes: number; + textOnly?: string[]; + noLongerKept?: string[]; + // Where it goes public, who moved what into the topic, and what no longer matches its capture. + sites?: string[]; + movedIn?: Array<{ id: string; by: "agent" | "operator"; from: string }>; + mismatched?: Array<{ id: string; name: string }>; + inFlight?: boolean; + confirm: string; + sentence: string; +}; + +export function TopicOrganise({ lib, topic, topics, off, run, go, when }: { lib: string; topic: LibraryTopic; topics: LibraryTopic[]; off: boolean; run: Run; go: (topicId: string) => void; when: (iso: string) => string }) { + const [title, setTitle] = useState(topic.title); + const others = topics.filter((t) => t.id !== topic.id); + const [into, setInto] = useState(""); + const [merging, setMerging] = useState(false); + const [plan, setPlan] = useState<PublishPlan | null>(null); + const [channel, setChannel] = useState(""); + const target = others.find((t) => t.id === into) ?? null; + const published = topic.published; + const kept = topic.counts?.keep ?? 0; + + const dryRun = (slug: string) => + run(async () => { + const r = (await send("/api/library/publish", { lib, topic: topic.id, dryRun: true, ...(slug ? { channel: slug } : {}) })) as unknown as PublishPlan; + setPlan(r); + setChannel(r.channel); + }); + + return ( + <div className="mt-3 border-t border-seam pt-2" data-library-organise={topic.id}> + <div className="flex flex-wrap items-end gap-x-3 gap-y-2 text-[12px] text-muted"> + <label className="flex min-w-0 flex-col gap-0.5"> + name + <input type="text" value={title} maxLength={120} onChange={(e) => setTitle(e.target.value)} data-library-rename-input="" className={`${field} w-[14rem] max-w-full`} /> + </label> + <Button + size="sm" + disabled={off || !title.trim() || title.trim() === topic.title} + data-library-rename="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "rename", topic: topic.id, title }); + return String(r.sentence ?? ""); + }) + } + > + Rename + </Button> + {others.length > 0 && ( + <> + <label className="flex min-w-0 flex-col gap-0.5"> + merge this topic into + <select value={into} onChange={(e) => { setInto(e.target.value); setMerging(false); }} data-library-merge-into="" className={`${field} max-w-[14rem]`}> + <option value="">choose a topic</option> + {others.map((t) => ( + <option key={t.id} value={t.id}> + {t.title} + </option> + ))} + </select> + </label> + <Button size="sm" disabled={off || !target} data-library-merge="" onClick={() => setMerging(true)}> + Merge… + </Button> + </> + )} + </div> + {merging && target && ( + <div role="alertdialog" aria-label="Merge" data-library-merge-plan={target.id} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-merge-sentence=""> + Merge “{topic.title}” into “{target.title}”? Its {topic.posts} post{topic.posts === 1 ? "" : "s"} and {topic.sources.length} trending page{topic.sources.length === 1 ? "" : "s"} move there and “{topic.title}” is gone. The judgements are + untouched. This cannot be undone: there is no unmerge. + {topic.watch && target.watch && topic.watch.on && target.watch.on && !topic.watch.ended && !target.watch.ended + ? ` Both are watched: the watch of “${target.title}” stands with its own terms, and this topic's watch is gone.` + : topic.watch && topic.watch.on && !topic.watch.ended + ? ` This topic's watch becomes the watch of “${target.title}”.` + : ""} + </p> + <div className="mt-1.5 flex flex-wrap gap-1.5"> + <Button + size="sm" + variant="go" + disabled={off} + data-library-merge-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "merge", into: target.id, from: [topic.id] }); + setMerging(false); + go(target.id); + return String(r.sentence ?? ""); + }) + } + > + Merge into “{target.title}” + </Button> + <Button size="sm" data-library-merge-no="" onClick={() => setMerging(false)}> + Cancel + </Button> + </div> + </div> + )} + + <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1.5"> + <Button size="sm" disabled={off || kept === 0} data-library-publish="" title="The posts the operator kept, into a channel on no site" onClick={() => void dryRun("")}> + Publish kept posts… + </Button> + <span className="text-[11.5px] text-muted" data-library-published={published?.channel ?? ""}> + {published + ? `Published into the channel “${published.channel}”: ${published.posts} post${published.posts === 1 ? "" : "s"}, last ${when(published.lastAt)}.` + : "Not published."} + </span> + </div> + {plan && ( + <div role="alertdialog" aria-label="Publish" data-library-publish-plan={plan.posts} className="mt-2 rounded-md border border-doubt-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-publish-sentence=""> + {plan.sentence} + </p> + <p className="m-0 mt-1 text-muted" data-library-publish-numbers=""> + channel {plan.channel} + {plan.creates ? " (new, on no site)" : ""} · {plan.posts} post{plan.posts === 1 ? "" : "s"} to add · {plan.files} file{plan.files === 1 ? "" : "s"} · {bytesSaid(plan.bytes)} · {plan.already} there already + {(plan.textOnly ?? []).length ? ` · ${(plan.textOnly ?? []).length} as words alone` : ""} + {(plan.noLongerKept ?? []).length ? ` · ${(plan.noLongerKept ?? []).length} no longer kept, left` : ""} + {(plan.movedIn ?? []).length ? ` · ${(plan.movedIn ?? []).length} moved here (${(plan.movedIn ?? []).filter((m) => m.by === "agent").length} by an agent)` : ""} + {(plan.mismatched ?? []).length ? ` · ${(plan.mismatched ?? []).length} file${(plan.mismatched ?? []).length === 1 ? "" : "s"} not copied` : ""} + </p> + {(plan.sites ?? []).length > 0 && (plan.posts > 0 || plan.files > 0) && ( + <p className="m-0 mt-1 font-semibold text-reject-text" data-library-publish-sites={(plan.sites ?? []).join(",")}> + On {(plan.sites ?? []).length === 1 ? "the site" : "the sites"} {(plan.sites ?? []).join(", ")}: public at the next build. + </p> + )} + {plan.creates && !published && ( + <div className="mt-1.5 flex flex-wrap items-end gap-x-2 gap-y-1.5 text-[12px] text-muted"> + <label className="flex min-w-0 flex-col gap-0.5"> + the channel’s slug + <input type="text" value={channel} onChange={(e) => setChannel(e.target.value.trim())} data-library-publish-channel="" className={`${field} w-[14rem] max-w-full`} /> + </label> + <Button size="sm" disabled={off || !channel || channel === plan.channel} data-library-publish-recount="" onClick={() => void dryRun(channel)}> + Use this slug + </Button> + </div> + )} + <div className="mt-1.5 flex flex-wrap gap-1.5"> + {(plan.posts > 0 || plan.files > 0 || plan.creates) && ( + <Button + size="sm" + variant="go" + disabled={off || plan.inFlight === true || channel !== plan.channel} + data-library-publish-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/publish", { lib, topic: topic.id, confirm: plan.confirm, ...(plan.creates && !published ? { channel: plan.channel } : {}) }); + setPlan(null); + return String(r.sentence ?? ""); + }) + } + > + Publish {plan.posts} post{plan.posts === 1 ? "" : "s"} into “{plan.channel}” + </Button> + )} + <Button size="sm" data-library-publish-no="" onClick={() => setPlan(null)}> + {plan.posts > 0 || plan.files > 0 || plan.creates ? "Cancel" : "Close"} + </Button> + </div> + </div> + )} + </div> + ); +} + +/** The bar's move: the posts a press would judge, into another topic. */ +export function MoveControl({ lib, topics, here, targets, off, run }: { lib: string; topics: LibraryTopic[]; here: string | null; targets: Array<{ id: string } | { thread: string }>; off: boolean; run: Run }) { + const [to, setTo] = useState(""); + const choices = topics.filter((t) => t.id !== here); + if (topics.length < 2) return null; + const ids = targets.flatMap((t) => ("id" in t ? [t.id] : [])); + const thread = targets.length === 1 && "thread" in targets[0] ? targets[0].thread : null; + return ( + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted" data-library-move-control=""> + Move to: + <select value={to} onChange={(e) => setTo(e.target.value)} aria-label="Move to topic" data-library-move-to="" className={`${field} max-w-[11rem]`}> + <option value="">a topic</option> + {choices.map((t) => ( + <option key={t.id} value={t.id}> + {t.title} + </option> + ))} + </select> + <Button + size="sm" + disabled={off || !to || targets.length === 0} + data-library-move="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "move", to, ...(thread ? { thread } : { ids }) }); + return String(r.sentence ?? ""); + }) + } + > + Move + </Button> + </span> + ); +} + +type Account = { handle: string; name?: string; posts: number; kept: number; keptByOperator?: number; topics?: string[]; archivedAs?: string[] }; + +export function AccountsPanel({ lib, topic, topics, off, run }: { lib: string; topic: string | null; topics: LibraryTopic[]; off: boolean; run: Run }) { + const [open, setOpen] = useState(false); + const [state, setState] = useState<{ accounts: Account[]; total: number; more: number } | { sentence: string } | null>(null); + const [asking, setAsking] = useState<string | null>(null); + const [made, setMade] = useState<Record<string, string>>({}); + const names = new Map(topics.map((t) => [t.id, t.title])); + + useEffect(() => { + if (!open) return; + let live = true; + setState(null); + fetch(`/api/library/accounts?lib=${encodeURIComponent(lib)}${topic ? `&topic=${encodeURIComponent(topic)}` : ""}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j: { ok?: boolean; accounts?: Account[]; total?: number; more?: number; sentence?: string; error?: string }) => { + if (!live) return; + setState(j.ok ? { accounts: j.accounts ?? [], total: j.total ?? 0, more: j.more ?? 0 } : { sentence: j.sentence ?? j.error ?? "The accounts could not be read." }); + }) + .catch((err) => live && setState({ sentence: `The accounts could not be read: ${err instanceof Error ? err.message : String(err)}` })); + return () => { + live = false; + }; + }, [open, lib, topic]); + + return ( + <details className="mt-3 rounded-md border border-seam p-3" data-library-accounts={open ? "open" : "closed"} onToggle={(e) => setOpen((e.currentTarget as HTMLDetailsElement).open)}> + <summary className="cursor-pointer text-[12.5px] text-text">Accounts{topic ? " in this topic" : " in the library"}</summary> + {open && !state && <p className="m-0 mt-2 text-[12.5px] text-muted">Reading the accounts…</p>} + {state && "sentence" in state && ( + <p className="m-0 mt-2 text-[12.5px] text-reject-text" data-library-accounts-error=""> + {state.sentence} + </p> + )} + {state && "accounts" in state && ( + <> + <p className="m-0 mt-2 text-[12px] text-muted" data-library-accounts-count={state.total}> + {state.total} account{state.total === 1 ? "" : "s"} + {state.more ? `, the first ${state.accounts.length} shown` : ""}. Archiving one makes its own X channel, on no site, with sync off: nothing is asked of X until you turn its sync on or fetch it in the editor. + </p> + <ul className="m-0 mt-2 list-none space-y-1.5 p-0"> + {state.accounts.map((a) => { + const archived = made[a.handle] ? [made[a.handle]] : (a.archivedAs ?? []); + return ( + <li key={a.handle} data-library-account={a.handle} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12.5px] text-text-2"> + <span className="min-w-0 break-words text-text"> + @{a.handle} + {a.name ? <span className="text-muted"> {a.name}</span> : null} + </span> + <span className="text-muted"> + {a.posts} post{a.posts === 1 ? "" : "s"} · {a.kept} kept{topic ? "" : ` · ${(a.topics ?? []).map((t) => names.get(t) ?? t).join(", ")}`} + </span> + {archived.length > 0 ? ( + <span className="text-muted" data-library-account-archived=""> + archived as {archived.join(", ")} + </span> + ) : asking === a.handle ? ( + <span role="alertdialog" aria-label="Archive this account" className="inline-flex flex-wrap items-center gap-1.5" data-library-archive-plan={a.handle}> + Makes the channel “{a.handle.toLowerCase()}-x”, on no site, with sync off. Nothing is asked of X. + <Button + size="sm" + variant="go" + disabled={off} + data-library-archive-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/archive", { lib, handle: a.handle, ...(a.name ? { name: a.name } : {}) }); + setAsking(null); + if (typeof r.slug === "string") setMade((m) => ({ ...m, [a.handle]: r.slug as string })); + return String(r.sentence ?? ""); + }) + } + > + Make the channel + </Button> + <Button size="sm" data-library-archive-no="" onClick={() => setAsking(null)}> + Cancel + </Button> + </span> + ) : ( + <Button size="sm" disabled={off} data-library-archive="" onClick={() => setAsking(a.handle)}> + Archive this account… + </Button> + )} + </li> + ); + })} + </ul> + </> + )} + </details> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -100,6 +100,10 @@ Inbox cannot disagree about what is wrong with one. | `library watch <lib> <topic> on\|off [--interval MIN] [--hours H] [--shots] [--by agent\|operator]` | the editor's `watch-trending` for one topic. A watch runs only while X's cookie jar is fresh, and one paused as failing is switched on again only with `--by operator`; the editor's refusal is printed, **exit 1** | | `library purge <lib> [--topic T] (--dry-run \| --confirm DIGEST --by operator)` | the editor's `purge-trending`, in two steps: `--dry-run` says what would be removed (the captures of posts THE OPERATOR dropped: posts, files, bytes; how many of them are gone from the page, whose capture is the only copy; how many an agent dropped, which are never purged) and prints the `--confirm` digest; the removal carries it and `--by operator`. Judgements stay; media another post uses is left; refused while a capture is queued or running, or when the set changed since the dry run (**exit 1**) | | `library seen <lib> (<topic>… \| --all) --by operator` | Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count. **The operator's**: without `--by operator` it is refused (an agent marking topics seen would hide posts from him), and a topic the library does not hold is refused, nothing marked (**exit 1**) | +| `library rename <lib> <topic> --title NAME [--by agent\|operator]` · `library move <lib> --to TOPIC (--id ID,… \| --thread ID) [--create] [--by agent\|operator]` | the editor's `organise-trending`. **rename** changes a topic's name and nothing else (its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused, and so is a rename while a read of the library is queued or running). **move** puts posts, or every post of one thread, into another topic (`--create` makes a topic of that name when there is none); judgements and captures are untouched and a later read never moves a post back. Both say `agent` unless told, and who is recorded | +| `library merge <lib> --into TOPIC --from T,… --by operator` | the editor's `organise-trending`, op `merge`: every post, page and read of the `--from` topics goes into `--into`, and they are gone. **There is no unmerge, so it is the operator's**: without `--by operator` it is refused before the editor is asked (**exit 1**). Refused while a read of the library is queued or running. One watch stands (the target's, with its own terms; else the merged topic's moves to it), and the sentence says which. umtool's Mark seen state follows: the earliest of the merged topics' marks stands | +| `library publish <lib> <topic> [--channel SLUG] (--dry-run \| --confirm DIGEST --by operator)` | the editor's `publish-trending`, in two steps: `--dry-run` says exactly what would be written (the channel's slug and whether it is made, posts, files, bytes; the sites the channel is already on, where what is added goes public at the next build; posts moved into the topic and by whom; files that no longer match their capture and are not copied; posts published as their words alone; posts published before and no longer kept, which stay) and prints the `--confirm` digest; the publish carries it and **`--by operator`** (an agent's is refused, **exit 1**). Only posts THE OPERATOR kept are published, into an ordinary channel on NO site whose files are copies; `--channel` names the slug at the first publish only. Refused while a read or a capture of the library is queued or running | +| `library accounts <lib> [--topic T] [--limit N] [--json]` · `library archive <lib> <handle> [--name N] [--dry-run] [--fetch]` | the library's **accounts** (handle, posts, kept, topics, the X channels that already archive each), and **archive**: the editor's `x-search-lead`, action `archive`, for an account of the library: `<handle>-x`, an X channel on no site that names nothing of the library. **It asks X nothing, now or later**: the channel is made with sync off (its priority paused) and no first fetch is started, and the editor's sentence says how to turn sync on and fetch; `--fetch` asks for the ordinary behaviour instead (the first fetch started, sync on); `--dry-run` creates nothing | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | | `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | | `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) | @@ -297,6 +301,12 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `library watch` | watch a topic of a trending library, or stop (the editor's watch-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | | `library purge` | remove dropped posts' captures, after a dry run (the editor's purge-trending) | none: the removal is the operator's press on the Posts library page (/tools/library), in two steps | | `library seen` | mark topics of a trending library seen | none: the Posts library page's Mark seen (/tools/library) | +| `library rename` | rename a topic of a trending library; its id stays (the editor's organise-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library move` | move posts of a trending library into another topic (the editor's organise-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library merge` | merge topics of a trending library into one; no unmerge (the editor's organise-trending) | none: the merge is the operator's press on the Posts library page (/tools/library), behind a confirm | +| `library publish` | publish a topic's kept posts into a channel on no site, after a dry run (the editor's publish-trending) | none: the publish is the operator's press on the Posts library page (/tools/library), in two steps | +| `library accounts` | a trending library's accounts: posts, kept, topics | none: a read the Posts library page (/tools/library) shows | +| `library archive` | archive an account of a trending library as its own X channel, on no site (the editor's x-search-lead) | none: the Posts library page's Archive this account (/tools/library) | | `library help` | the library verbs | none: prints the usage | | `pool stats [--since SINCE]` | the render pool: what it holds | form · *corpus* | | `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* | diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md @@ -48,7 +48,8 @@ A trending library is the editor's private collection of posts read off X's tren `read-x-trending`). This page is where it is judged before anything of it is published. **Everything is the editor's**: the page reads the library through the editor and every press is the editor's action, written as the operator's. umtool writes no file of a library and asks X nothing; nothing here puts a post into a project, a report, an article, the post -archive or a site. With the editor down, or no library in it, the page says so in a sentence. +archive or a site. The one way out is **Publish**: the posts the operator kept in a topic become an ordinary channel, +on no site. With the editor down, or no library in it, the page says so in a sentence. - **Topics** (left; a fold on a phone): posts, unjudged, new, and what its watch is doing. A paused watch says why; a failing one (three reads in a row that did not end as read) is restarted only by the operator: **Watch again**. @@ -71,6 +72,23 @@ archive or a site. With the editor down, or no library in it, the page says so i captures of posts **the operator** dropped: an agent's drop is a suggestion, counted and left alone. For a dropped post that is gone from the page the capture is the only copy, and the confirm says that removing it cannot be undone. Judgements stay; media another post uses is left. +- **Organise** (a topic's panel, and **Move to** in the bar): **Rename** a topic (its id stays: its watch, posts and + judgements are untouched; refused while a read of the library is queued or running); **Move** the posts a press would judge (the selection, else the post, or its thread) into + another topic; **Merge…** this topic into another, behind a confirm that says it **cannot be undone** and which watch + stands when both are watched (the target's, with its own terms). A merge waits while a read of the library is queued + or running. +- **Publish kept posts…** says exactly what would be written: the channel's slug (a slug of the topic's name; it can be + changed before the first publish, and is fixed after it), posts, files and bytes, how many go as their words alone + (no capture yet) and how many published before are no longer kept (they stay: a publish removes nothing). Then + **Publish**. Only posts **the operator** kept are published, into an ordinary channel **on no site** whose files are + copies. Adding that channel to a site is a separate act in the editor. Publishing again adds what was kept since. + When the channel is already on a site, the plan says so in red: what is added goes public at that site's next + build. It also counts the posts that were moved into the topic (and how many by an agent) and any file that no + longer matches what its capture recorded, which is not copied. +- **Accounts**: who wrote the posts (of the topic, or of the library), with posts, kept and topics. **Archive this + account…** makes `<handle>-x`, an X channel on no site, **with sync off**, and **asks X nothing**: the sentence + it answers says how to turn its sync on and run its first fetch in the editor. An account an X channel already + archives says so. | Key | | |---|---| diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -1,28 +1,31 @@ // The editor's X trending library, stubbed for umtool's Posts library page // (library.spec.ts; lane posts-library): GET /api/ops/trending with the judge -// view's asks, and the three presses — judge-trending, watch-trending, -// purge-trending — over an invented library held in memory +// view's asks, and the presses — judge-trending, watch-trending, +// purge-trending, and (lane x-trending-publish) organise-trending, +// publish-trending and x-search-lead's archive — over an invented library held in memory // (library-fixture.mjs libraryState). Every press is RECORDED with the `by` // it carried, which is the part no page shows. // // POST /__stub/trending {reset?: true, mode?: "ok" | "unreachable" | "none"} // "unreachable": every trending route drops the connection (the editor is down); // "none": the editor holds no library -// GET /__stub/trending -> { mode, requests, reads, judgements, captured, watches } +// GET /__stub/trending -> { mode, requests, reads, judgements, captured, watches, topics, published, archived } // `reads`: how many times the listing was asked (GET /api/ops/trending) since the reset // // Nothing here asks X, or any host, anything. import { createHash } from "node:crypto"; import { libraryState } from "./library-fixture.mjs"; -let state = libraryState(); +const fresh = () => ({ ...libraryState(), published: {}, archived: {} }); +let state = fresh(); let mode = "ok"; let requests = []; let reads = 0; let jobs = 0; const NOW = "2026-11-18T09:00:00.000Z"; -const ROUTES = ["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"]; +// Lane x-trending-publish: organise-trending, publish-trending and the lead action's archive. +const ROUTES = ["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending", "/api/ops/organise-trending", "/api/ops/publish-trending", "/api/ops/x-search-lead"]; const effective = (p) => { const own = state.judgements.posts[p.id]; @@ -81,7 +84,7 @@ function row(p, detail) { } function listing(sp) { - const topic = sp.get("topic"); + const topic = topicOf(sp.get("topic"))?.id ?? sp.get("topic"); const detail = sp.get("detail") === "1"; const words = (sp.get("q") ?? "").toLowerCase().split(/\s+/).filter(Boolean); const author = sp.get("author")?.replace(/^@/, "").toLowerCase() ?? null; @@ -114,7 +117,8 @@ function listing(sp) { if (p.gone) counts.gone++; } const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null; - return { id: t.id, title: t.title, posts: mine.length, ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] }; + const pub = detail ? state.published?.[t.id] : undefined; + return { id: t.id, title: t.title, posts: mine.length, ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(pub ? { published: { channel: pub.channel, firstAt: NOW, lastAt: NOW, posts: pub.posts.length } } : {}), ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] }; }), posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), total: rows.length, @@ -124,6 +128,164 @@ function listing(sp) { }; } +// ── lane x-trending-publish ──────────────────────────────────────────────── + +/** A topic by its id, the id of one merged into it, or its name. */ +function topicOf(name) { + if (!name) return undefined; + return state.topics.find((t) => t.id === name) ?? state.topics.find((t) => t.aliases?.includes(name)) ?? state.topics.find((t) => t.title.toLowerCase() === String(name).toLowerCase()); +} +const slugOf = (title) => title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); +const live = (w) => !!w && w.on && !w.ended; +const none = (name) => ({ ok: false, error: `This library has no topic "${name}" (its topics: ${state.topics.map((t) => t.id).join(", ")}).` }); + +// The editor's rules (common/lib/xTrending/organise.ts): a rename keeps the id; a move changes a post's topic; +// a merge is the operator's, keeps the merged ids as aliases and ONE watch (the target's when it is live). +function organise(body) { + if (body.by !== "agent" && body.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; + if (body.op === "rename") { + const topic = topicOf(body.topic); + if (!topic) return none(body.topic); + // The editor's refusal while a read of the library is queued or running (review 1 S9). + if (state.reading) return { ok: false, error: "A read of this library is queued or running: rename its topic once it has finished (its job is on /jobs). A read names its topic, by id or by name, and a name changed under it could send its posts to a new topic." }; + const other = state.topics.find((t) => t !== topic && (t.id === body.title || t.title.toLowerCase() === String(body.title).toLowerCase())); + if (other) return { ok: false, error: `Topic "${other.title}" (${other.id}) already answers to "${body.title}": a topic's name is its own. Merge the two, or choose another name.` }; + const was = topic.title; + topic.title = String(body.title).trim(); + return { ok: true, slug: state.slug, op: "rename", topic: topic.id, title: topic.title, was, changed: was !== topic.title, sentence: `Topic "${was}" is now "${topic.title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }; + } + if (body.op === "move") { + let to = topicOf(body.to); + let created = false; + if (!to) { + if (!body.create) return { ok: false, error: `${none(body.to).error} To move posts into a new topic, say "create": true.` }; + to = { id: slugOf(body.to), title: body.to }; + state.topics.push(to); + created = true; + } + const wanted = body.thread ? state.posts.filter((p) => p.thread === body.thread).map((p) => p.id) : body.ids ?? []; + const moved = []; + const skipped = []; + for (const pid of wanted) { + const p = state.posts.find((x) => x.id === pid); + if (!p) skipped.push({ id: pid, reason: "not in this library" }); + else if (p.topic === to.id) skipped.push({ id: pid, reason: `already in "${to.title}"` }); + else { + p.movedFrom = p.topic; + p.movedBy = body.by; + p.topic = to.id; + moved.push(pid); + } + } + return { ok: true, slug: state.slug, op: "move", to: { id: to.id, title: to.title, created }, moved, skipped, sentence: `${moved.length} post${moved.length === 1 ? "" : "s"} moved to "${to.title}".${skipped.length ? ` ${skipped.length} post${skipped.length === 1 ? "" : "s"} skipped: ${skipped[0].reason}.` : ""}${moved.length ? " Their judgements and captures are untouched." : ""}` }; + } + if (body.op === "merge") { + if (body.by !== "operator") return { ok: false, error: "Merging topics is the operator's press: it cannot be undone (there is no unmerge)." }; + const into = topicOf(body.into); + if (!into) return none(body.into); + const from = []; + for (const name of body.from ?? []) { + const t = topicOf(name); + if (!t) return none(name); + if (t === into) return { ok: false, error: `"${name}" is the topic that stays ("${into.title}"): a topic is not merged into itself.` }; + from.push(t); + } + const merged = from.map((t) => ({ id: t.id, title: t.title, posts: state.posts.filter((p) => p.topic === t.id).length, pages: 1 })); + let watchSentence = ""; + const dropped = []; + for (const t of from) { + for (const p of state.posts) if (p.topic === t.id) p.topic = into.id; + if (live(t.watch)) { + if (live(into.watch)) dropped.push(t.title); + else { + into.watch = t.watch; + watchSentence = ` The watch of "${t.title}" is now the watch of "${into.title}".`; + } + } + into.aliases = [...(into.aliases ?? []), t.id, ...(t.aliases ?? [])]; + state.topics.splice(state.topics.indexOf(t), 1); + } + if (dropped.length) watchSentence = ` The watch of "${into.title}" stands with its own terms. The watch of ${dropped.map((d) => `"${d}"`).join(", ")} is gone: one topic has one watch.`; + const posts = merged.reduce((n, m) => n + m.posts, 0); + return { ok: true, slug: state.slug, op: "merge", into: { id: into.id, title: into.title }, merged, posts, pages: 1 + merged.length, watch: { dropped }, sentence: `${merged.map((m) => `"${m.title}"`).join(", ")} ${merged.length === 1 ? "is" : "are"} now part of "${into.title}": ${posts} post${posts === 1 ? "" : "s"} moved. The judgements are untouched. This cannot be undone.${watchSentence}` }; + } + return { ok: false, error: `"op" is "rename", "move" or "merge"` }; +} + +// The editor's rule (common/controller/publishXTrending.ts): the posts KEPT BY THE OPERATOR, in two steps held +// by a digest; the slug fixed at the first publish; a re-publish adds and removes nothing. +function publish(body) { + const topic = topicOf(body.topic); + if (!topic) return { ok: false, error: `${state.slug} has no topic "${body.topic}"` }; + const record = state.published[topic.id]; + if (record && body.channel !== undefined && body.channel !== record.channel) return { ok: false, error: `"${topic.title}" is published into the channel "${record.channel}": a topic has one channel, fixed at its first publish.` }; + const channel = record?.channel ?? body.channel ?? slugOf(topic.title); + const kept = state.posts.filter((p) => p.topic === topic.id && effective(p)?.state === "keep" && effective(p).by === "operator"); + if (kept.length === 0) return { ok: false, error: `The operator has kept no post in "${topic.title}": there is nothing to publish. (An agent's keep is a suggestion and is not published.)` }; + const have = new Set(record?.posts ?? []); + const fresh = kept.filter((p) => !have.has(p.id)); + const files = fresh.reduce((n, p) => n + (state.captured.includes(p.id) ? 1 + (captureFiles(p)?.media.length ?? 0) : 0), 0); + const textOnly = kept.filter((p) => !state.captured.includes(p.id)).map((p) => p.id); + const noLongerKept = [...have].filter((pid) => !kept.some((p) => p.id === pid)); + const confirm = createHash("sha256").update(JSON.stringify([state.slug, topic.id, channel, fresh.map((p) => p.id).sort(), state.sites?.[channel] ?? []])).digest("hex").slice(0, 24); + const answer = { ok: true, slug: state.slug, library: state.slug, topic: { id: topic.id, title: topic.title }, channel, creates: !record, kept: kept.length, posts: fresh.length, ids: fresh.map((p) => p.id), already: kept.length - fresh.length, files, bytes: files * 68, textOnly, noLongerKept, sites: state.sites?.[channel] ?? [], movedIn: fresh.filter((p) => p.movedBy).map((p) => ({ id: p.id, by: p.movedBy, from: p.movedFrom })), mismatched: [], confirm }; + const n = (k, what) => `${k} ${what}${k === 1 ? "" : "s"}`; + const onSites = answer.sites.length && fresh.length ? ` THIS CHANNEL IS ON THE SITE ${answer.sites.join(", ")}: ${fresh.length === 1 && files === 0 ? "this post goes" : "these posts go"} public at its next build.` : ""; + const say = (would) => `${sayHead(would)}${onSites}`; + const sayHead = (would) => + fresh.length === 0 && record + ? `Nothing to add: the channel "${channel}" already holds the ${n(kept.length, "post")} the operator kept in "${topic.title}".` + : `Publishing "${topic.title}" ${record ? (would ? "would add to" : "added to") : would ? "would make" : "made"} the channel "${channel}"${record ? "" : ", on no site,"} ${would ? "writing" : "and wrote"} ${n(fresh.length, "post")} and ${n(files, "file")} (${files * 68} B); ${answer.already} of the ${n(kept.length, "kept post")} ${answer.already === 1 ? "is" : "are"} there already.${noLongerKept.length ? ` ${n(noLongerKept.length, "post")} published before ${noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).` : ""}`; + if (body.dryRun === true) return { ...answer, dryRun: true, sentence: say(true) }; + if (body.by !== "operator") return { ok: false, error: "Publishing a topic is the operator's press: an agent may ask for the dry run" }; + if (body.confirm !== confirm) return { ok: false, error: "What would be published has changed since it was counted (a post kept or dropped, a capture finished, a post moved): nothing was written. Ask for the dry run again." }; + state.published[topic.id] = { channel, posts: [...have, ...fresh.map((p) => p.id)] }; + return { ...answer, dryRun: false, sentence: say(false) }; +} + +function accounts(sp) { + const topic = topicOf(sp.get("topic"))?.id ?? null; + const rows = new Map(); + for (const p of state.posts) { + if (topic && p.topic !== topic) continue; + const row = rows.get(p.author) ?? { handle: p.author, key: p.author.toLowerCase(), name: p.authorName, posts: 0, kept: 0, keptByOperator: 0, topics: [], last: p.createdAt }; + row.posts++; + const j = effective(p); + if (j?.state === "keep") { + row.kept++; + if (j.by === "operator") row.keptByOperator++; + } + if (!row.topics.includes(p.topic)) row.topics.push(p.topic); + if (state.archived[p.author]) row.archivedAs = [state.archived[p.author]]; + rows.set(p.author, row); + } + const all = [...rows.values()].sort((a, b) => b.posts - a.posts || (a.key < b.key ? -1 : 1)); + return { ok: true, slug: state.slug, accounts: all, total: all.length, posts: all.reduce((n, a) => n + a.posts, 0), more: 0 }; +} + +// The lead action's archive, for an account of the library: <handle>-x, and NO fetch unless asked. +function lead(body) { + if (body.action !== "archive") return { ok: false, error: `${state.slug} is not an X search channel (its config has no xSearch query).` }; + const handle = String(body.handle ?? "").replace(/^@/, ""); + if (!state.posts.some((p) => p.author.toLowerCase() === handle.toLowerCase())) return { ok: false, error: `${state.slug} holds no post by @${handle}: "Archive this account" is for an account in the library.` }; + if (state.archived[handle]) return { ok: false, error: `@${handle} is already archived: ${state.archived[handle]}.` }; + const slug = `${handle.toLowerCase()}-x`; + if (body.dryRun === true) return { ok: true, dryRun: true, slug, fields: { url: `https://x.com/${handle}` } }; + state.archived[handle] = slug; + if (body.fetch === true) return { ok: true, slug, jobIds: [`stub-fetch-${++jobs}`] }; + // The editor's sentence (common/lib/xSearch/leads.ts xLeadSyncOffSentence). + return { + ok: true, + slug, + jobIds: [], + syncOff: true, + sentence: + `Made the channel "${slug}" for @${handle}, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. ` + + `To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["${slug}"],"tier":"normal"}'). ` + + `Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"${slug}"}').`, + }; +} + function judge(body) { const before = new Map(state.posts.map((p) => [p.id, effective(p)?.state])); const written = []; @@ -188,17 +350,25 @@ export function trendingControl(req, res, url, { json, readBody }) { if (url.pathname !== "/__stub/trending") return false; if (req.method === "GET") { req.resume(); - json(res, 200, { mode, requests, reads, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])) }); + json(res, 200, { + mode, requests, reads, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])), + topics: state.topics.map((t) => ({ id: t.id, title: t.title, aliases: t.aliases ?? [], posts: state.posts.filter((p) => p.topic === t.id).map((p) => p.id) })), + published: state.published, + archived: state.archived, + }); return true; } readBody(req, (body) => { if (body?.reset === true) { - state = libraryState(); + state = fresh(); requests = []; reads = 0; jobs = 0; mode = "ok"; } + // What the editor would know and umtool cannot: a read in flight, and the sites a channel is on. + if (body?.reading !== undefined) state.reading = body.reading === true; + if (body?.sites !== undefined) state.sites = body.sites; if (body?.mode !== undefined) { if (!["ok", "unreachable", "none"].includes(body.mode)) return json(res, 400, { error: `mode "${body.mode}" is not one of ok, unreachable, none` }); mode = body.mode; @@ -227,8 +397,12 @@ export function trendingRoute(req, res, url, { json, readBody, authorization }) json(res, 404, { ok: false, error: `No such channel: ${url.searchParams.get("slug")}` }); return true; } + if (url.searchParams.get("accounts") === "1") { + json(res, 200, accounts(url.searchParams)); + return true; + } const topic = url.searchParams.get("topic"); - if (topic && !state.topics.some((t) => t.id === topic)) { + if (topic && !state.topics.some((t) => t.id === topic || t.aliases?.includes(topic))) { json(res, 400, { ok: false, error: `${state.slug} has no topic "${topic}" (its topics: ${state.topics.map((t) => t.id).join(", ")})` }); return true; } @@ -240,7 +414,13 @@ export function trendingRoute(req, res, url, { json, readBody, authorization }) const action = url.pathname.slice("/api/ops/".length); requests.push({ action, body, authorization }); if (!body || body.slug !== state.slug) return json(res, 400, { ok: false, error: `${body?.slug} is not an X trending library` }); - const answer = action === "judge-trending" ? judge(body) : action === "watch-trending" ? watch(body) : purge(body); + const answer = + action === "judge-trending" ? judge(body) + : action === "watch-trending" ? watch(body) + : action === "organise-trending" ? organise(body) + : action === "publish-trending" ? publish(body) + : action === "x-search-lead" ? lead(body) + : purge(body); json(res, answer.ok ? 200 : 400, answer); }); return true; diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -108,8 +108,10 @@ test("found from Tools; topics on the left with their counts and what each watch await expect(page.locator(`[data-library-panel="${KETTLES}"]`)).toContainText("6 posts · 4 unjudged · 0 kept · 1 dropped · 1 later"); // It fits a desk without scrolling sideways. expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); - // Nothing here offers a post to a project, a report or a site. - await expect(page.locator("[data-posts-library]").getByRole("button", { name: /add to|publish|cut|project|report/i })).toHaveCount(0); + // Nothing here offers a post to a project, a report or a site. THE ONE WAY OUT (lane x-trending-publish) is the + // topic's own Publish, the operator's, into a channel on no site: one button, and it names no site. + await expect(page.locator("[data-posts-library]").getByRole("button", { name: /add to|cut|project|report|site/i })).toHaveCount(0); + await expect(page.locator("[data-posts-library]").getByRole("button", { name: /publish/i })).toHaveText(["Publish kept posts…"]); await expect(page.locator("[data-posts-library]").getByRole("link", { name: /add to|publish/i })).toHaveCount(0); }); @@ -608,6 +610,249 @@ test("on a phone (360 px): nothing pushes the page sideways, the topics fold, an await page.screenshot({ path: test.info().outputPath("library-360.png"), fullPage: true }); }); +// ── lane x-trending-publish: organise, publish, the accounts ─────────────── + +type Slice4 = StubState & { topics: { id: string; title: string; aliases: string[]; posts: string[] }[]; published: Record<string, { channel: string; posts: string[] }>; archived: Record<string, string> }; +const stub4 = async (request: APIRequestContext): Promise<Slice4> => (await request.get(`${STUB}/__stub/trending`)).json(); + +test("organise: rename a topic, move the selection to another, merge behind a confirm that says it cannot be undone and which watch stands", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const organise = page.locator(`[data-library-organise="${KETTLES}"]`); + + // RENAME: the id stays (the address does not change), the rail says the new name. + await expect(organise.locator("[data-library-rename]")).toBeDisabled(); + await organise.locator("[data-library-rename-input]").fill("Kettle festival 2026"); + // S9: while a read of the library is queued or running the editor refuses it, and the page says why. + expect((await request.post(`${STUB}/__stub/trending`, { data: { reading: true } })).status()).toBe(200); + await organise.locator("[data-library-rename]").click(); + await expect(status(page)).toHaveAttribute("data-library-status", "error"); + await expect(status(page)).toContainText("A read of this library is queued or running: rename its topic once it has finished"); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"]`)).not.toContainText("2026"); + await idle(page); + expect((await request.post(`${STUB}/__stub/trending`, { data: { reading: false } })).status()).toBe(200); + await organise.locator("[data-library-rename]").click(); + await expect(status(page)).toHaveText('Topic "Kettle festival" is now "Kettle festival 2026". Its id stays kettle-festival: its watch, its posts and their judgements are untouched.'); + expect((await last(request)).action).toBe("organise-trending"); + expect((await last(request)).body).toEqual({ slug: LIB, op: "rename", topic: KETTLES, title: "Kettle festival 2026", by: "operator" }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"]`)).toContainText("Kettle festival 2026"); + await idle(page); + + // MOVE: what a press would judge (here the selection) goes to the topic chosen. + await expect(page.locator("[data-library-move]")).toBeDisabled(); + await page.getByLabel("Select the post by @kettle_fan").check(); + await page.locator("[data-library-move-to]").selectOption(CUPS); + await page.locator("[data-library-move]").click(); + await expect(status(page)).toHaveText('1 post moved to "Cup shortage". Their judgements and captures are untouched.'); + expect((await last(request)).body).toEqual({ slug: LIB, op: "move", to: CUPS, ids: [P.fresh], by: "operator" }); + await expect(post(page, P.fresh)).toHaveCount(0); + expect((await stub4(request)).topics.find((t) => t.id === CUPS)!.posts).toContain(P.fresh); + await idle(page); + + // Mark seen first: umtool's own mark must follow the merge. + await page.locator("[data-library-seen]").click(); + await expect(status(page)).toContainText("marked seen"); + await idle(page); + expect(Object.keys(JSON.parse(readFileSync(SEEN, "utf8")).libraries[LIB].topics)).toEqual([KETTLES]); + + // MERGE: asked twice. The first press writes nothing and says what is true of it. + await expect(organise.locator("[data-library-merge]")).toBeDisabled(); + await organise.locator("[data-library-merge-into]").selectOption(CUPS); + await organise.locator("[data-library-merge]").click(); + const plan = page.locator("[data-library-merge-plan]"); + await expect(plan.locator("[data-library-merge-sentence]")).toContainText("Merge “Kettle festival 2026” into “Cup shortage”?"); + await expect(plan.locator("[data-library-merge-sentence]")).toContainText("This cannot be undone: there is no unmerge."); + await expect(plan.locator("[data-library-merge-sentence]")).toContainText("Both are watched: the watch of “Cup shortage” stands with its own terms, and this topic's watch is gone."); + expect((await stub4(request)).requests.filter((r) => r.body.op === "merge")).toHaveLength(0); + await plan.locator("[data-library-merge-no]").click(); + await expect(plan).toHaveCount(0); + expect((await stub4(request)).topics.map((t) => t.id)).toContain(KETTLES); + + await organise.locator("[data-library-merge]").click(); + await plan.locator("[data-library-merge-yes]").click(); + await expect(status(page)).toContainText('"Kettle festival 2026" is now part of "Cup shortage"'); + await expect(status(page)).toContainText("This cannot be undone."); + await expect(status(page)).toContainText('The watch of "Cup shortage" stands with its own terms.'); + const merge = (await stub4(request)).requests.filter((r) => r.body.op === "merge"); + expect(merge.map((r) => r.body)).toEqual([{ slug: LIB, op: "merge", into: CUPS, from: [KETTLES], by: "operator" }]); + // The page is on the topic that stays, which now holds the merged posts. + await expect(page).toHaveURL(new RegExp(`topic=${CUPS}`)); + await expect(page.locator(`[data-library-panel="${CUPS}"]`)).toBeVisible(); + await expect(post(page, P.opening)).toBeVisible(); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"]`)).toHaveCount(0); + const after = await stub4(request); + expect(after.topics.find((t) => t.id === CUPS)!.aliases).toEqual([KETTLES]); + // umtool's mark followed: the topic that stays was never marked, so it stays unmarked and the merged one's mark is gone. + expect(JSON.parse(readFileSync(SEEN, "utf8")).libraries[LIB].topics).toEqual({}); +}); + +test("publish: the first press says exactly what would be written and writes nothing; the slug can be changed before a first publish; publishing again adds and removes nothing", async ({ page, request }) => { + // No post kept by the operator: nothing to publish (an agent's judgement is not one). + await open(page, { topic: CUPS }); + await expect(page.locator("[data-library-publish]")).toBeDisabled(); + await expect(page.locator("[data-library-published]")).toHaveText("Not published."); + + await open(page, { topic: KETTLES }); + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + await idle(page); + await page.locator("[data-library-publish]").click(); + const plan = page.locator("[data-library-publish-plan]"); + await expect(plan.locator("[data-library-publish-sentence]")).toHaveText('Publishing "Kettle festival" would make the channel "kettle-festival", on no site, writing 1 post and 3 files (204 B); 0 of the 1 kept post are there already.'); + await expect(plan.locator("[data-library-publish-numbers]")).toHaveText("channel kettle-festival (new, on no site) · 1 post to add · 3 files · 204 B · 0 there already"); + let r = await last(request); + expect(r.action).toBe("publish-trending"); + expect(r.body).toEqual({ slug: LIB, topic: KETTLES, dryRun: true, by: "operator" }); + expect((await stub4(request)).published).toEqual({}); + await idle(page); + + // The slug, changed before the first publish: counted again under it, and the publish waits for that. + await plan.locator("[data-library-publish-channel]").fill("Kettles-2026"); + await expect(plan.locator("[data-library-publish-yes]")).toBeDisabled(); + await plan.locator("[data-library-publish-recount]").click(); + await expect(plan.locator("[data-library-publish-numbers]")).toContainText("channel Kettles-2026 (new, on no site)"); + expect((await last(request)).body).toEqual({ slug: LIB, topic: KETTLES, channel: "Kettles-2026", dryRun: true, by: "operator" }); + await idle(page); + await expect(plan.locator("[data-library-publish-yes]")).toHaveText("Publish 1 post into “Kettles-2026”"); + await plan.locator("[data-library-publish-yes]").click(); + await expect(status(page)).toContainText('Publishing "Kettle festival" made the channel "Kettles-2026", on no site, and wrote 1 post and 3 files'); + r = await last(request); + expect(r.body.by).toBe("operator"); + expect(r.body.channel).toBe("Kettles-2026"); + expect(r.body.confirm).toMatch(/^[0-9a-f]{24}$/); + expect(r.body.dryRun).toBeUndefined(); + expect((await stub4(request)).published).toEqual({ [KETTLES]: { channel: "Kettles-2026", posts: [P.opening] } }); + await expect(page.locator("[data-library-published]")).toHaveAttribute("data-library-published", "Kettles-2026"); + await expect(page.locator("[data-library-published]")).toContainText("Published into the channel “Kettles-2026”: 1 post, last"); + await idle(page); + + // AGAIN: the opening post is dropped, the reply kept. One is added; the dropped one is reported and stays. + await post(page, P.opening).locator('[data-library-press="drop"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "drop"); + await idle(page); + await post(page, P.reply).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.reply)).toHaveAttribute("data-library-judgement", "keep"); + await idle(page); + // S4: the operator has put the channel on a site meanwhile: the plan says where the post goes public. + await expect(plan.locator("[data-library-publish-sites]")).toHaveCount(0); + expect((await request.post(`${STUB}/__stub/trending`, { data: { sites: { "Kettles-2026": ["kettle-site"] } } })).status()).toBe(200); + await page.locator("[data-library-publish]").click(); + await expect(plan.locator("[data-library-publish-sites]")).toHaveText("On the site kettle-site: public at the next build."); + await expect(plan.locator("[data-library-publish-sentence]")).toContainText("THIS CHANNEL IS ON THE SITE kettle-site: these posts go public at its next build."); + await expect(plan.locator("[data-library-publish-numbers]")).toHaveText("channel Kettles-2026 · 1 post to add · 1 file · 68 B · 0 there already · 1 no longer kept, left"); + await expect(plan.locator("[data-library-publish-sentence]")).toContainText("1 post published before is no longer kept: it stays in the channel (a publish removes nothing)."); + // The slug is fixed now: no field for it. + await expect(plan.locator("[data-library-publish-channel]")).toHaveCount(0); + await idle(page); + await plan.locator("[data-library-publish-yes]").click(); + await expect(status(page)).toContainText('added to the channel "Kettles-2026"'); + expect((await last(request)).body.channel).toBeUndefined(); + expect((await stub4(request)).published[KETTLES].posts).toEqual([P.opening, P.reply]); + await idle(page); + + // On a phone the panel and an open plan fit. + await page.setViewportSize({ width: 360, height: 740 }); + await page.locator("[data-library-publish]").click(); + await expect(plan.locator("[data-library-publish-sentence]")).toContainText("Nothing to add"); + await expect(plan.locator("[data-library-publish-yes]")).toHaveCount(0); + for (const sel of ["[data-library-organise]", "[data-library-publish-plan]", "[data-library-move-control]"]) { + const box = (await page.locator(sel).first().boundingBox())!; + expect(box.x, sel).toBeGreaterThanOrEqual(-1); + expect(box.x + box.width, sel).toBeLessThanOrEqual(361); + } + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await plan.locator("[data-library-publish-no]").click(); +}); + +test("the accounts: who wrote the posts; Archive this account makes <handle>-x and asks X nothing", async ({ page, request }) => { + await open(page); + const accounts = page.locator("[data-library-accounts]"); + await expect(accounts).toHaveAttribute("data-library-accounts", "closed"); + await accounts.locator("summary").click(); + await expect(accounts.locator("[data-library-accounts-count]")).toContainText("accounts. Archiving one makes its own X channel, on no site, with sync off: nothing is asked of X until you turn its sync on or fetch it in the editor."); + const row = accounts.locator('[data-library-account="saucer_fan"]'); + await expect(row).toContainText("@saucer_fan"); + await expect(row).toContainText("1 post · 0 kept · Kettle festival"); + await expect(accounts.locator('[data-library-account="teapot_news"]')).toContainText("2 posts"); + + // Asked twice; the first press asks the editor nothing. + await row.locator("[data-library-archive]").click(); + await expect(row.locator("[data-library-archive-plan]")).toContainText("Makes the channel “saucer_fan-x”, on no site, with sync off. Nothing is asked of X."); + expect((await stub4(request)).requests.filter((r) => r.action === "x-search-lead")).toHaveLength(0); + await row.locator("[data-library-archive-no]").click(); + await row.locator("[data-library-archive]").click(); + await row.locator("[data-library-archive-yes]").click(); + // The editor's sentence, whole: sync off, nothing asked of X, how to turn sync on and run the first fetch. + await expect(status(page)).toHaveText( + `Made the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. To turn sync on, set its priority to normal on /channels (pnpm ops channel-priority --json '{"slugs":["saucer_fan-x"],"tier":"normal"}'). Its first fetch is Fetch posts on its page (pnpm ops fetch-posts --json '{"slug":"saucer_fan-x"}').`, + ); + // The lead action, "archive", and NO fetch. + const r = await last(request); + expect(r.action).toBe("x-search-lead"); + expect(r.body).toEqual({ slug: LIB, handle: "saucer_fan", action: "archive", name: "Saucer Fan" }); + expect((await stub4(request)).archived).toEqual({ saucer_fan: "saucer_fan-x" }); + await expect(row.locator("[data-library-account-archived]")).toHaveText("archived as saucer_fan-x"); + await expect(row.locator("[data-library-archive]")).toHaveCount(0); + + // Of one topic. + await open(page, { topic: CUPS }); + await page.locator("[data-library-accounts] summary").click(); + await expect(page.locator("[data-library-account]")).toHaveCount(1); + await expect(page.locator('[data-library-account="cup_other"]')).toContainText("2 posts · 0 kept"); +}); + +test("the organise, publish and archive routes take a press from umtool's own page only, and stamp it the operator's", async ({ request, baseURL }) => { + const page = asPage(baseURL); + const bodies: Record<string, Record<string, unknown>> = { + organise: { lib: LIB, op: "rename", topic: "lids", title: "Lids and tops", by: "agent" }, + publish: { lib: LIB, topic: KETTLES, dryRun: true, by: "agent" }, + archive: { lib: LIB, handle: "lid_watch", dryRun: true, fetch: true }, + }; + // A request no browser sent — curl, a script, an agent, with a bearer or with nothing — is refused before its body is read. + const before = (await stub(request)).requests.length; + for (const [route, data] of Object.entries(bodies)) { + for (const headers of [{}, { authorization: "Bearer umtool-e2e-token" }, { ...page, authorization: "Bearer umtool-e2e-token" }, { origin: "https://example.org", "sec-fetch-site": "cross-site" }] as Record<string, string>[]) { + const res = await request.post(`/api/library/${route}`, { headers, data }); + expect(res.status(), `${route} ${JSON.stringify(headers)}`).toBe(403); + if (!headers.origin || headers.authorization) expect((await res.json()).error).toContain("`organise-trending` / `publish-trending` or `umtool library`"); + } + } + for (const data of [{ lib: LIB, op: "merge", into: KETTLES, from: [CUPS] }, { lib: LIB, topic: KETTLES, confirm: "FAKE-TEST-VALUE01234567" }]) { + expect((await request.post(`/api/library/${"op" in data ? "organise" : "publish"}`, { data })).status()).toBe(403); + } + expect((await stub(request)).requests.length).toBe(before); + + // The page's own press, whatever its body says about who. + expect((await request.post("/api/library/organise", { headers: page, data: bodies.organise })).status()).toBe(200); + expect((await last(request)).body).toEqual({ slug: LIB, op: "rename", topic: "lids", title: "Lids and tops", by: "operator" }); + // No post kept by the operator: the editor's refusal, in its words. + const none = await request.post("/api/library/publish", { headers: page, data: bodies.publish }); + expect(none.status()).toBe(400); + expect((await none.json()).error).toContain('The operator has kept no post in "Kettle festival"'); + expect((await last(request)).body).toEqual({ slug: LIB, topic: KETTLES, dryRun: true, by: "operator" }); + // A publish with no dry run's confirm asks the editor nothing. + const asked = (await stub(request)).requests.length; + const noConfirm = await request.post("/api/library/publish", { headers: page, data: { lib: LIB, topic: KETTLES } }); + expect(noConfirm.status()).toBe(400); + expect((await noConfirm.json()).error).toContain('carries the "confirm" its dry run answered'); + expect((await stub(request)).requests.length).toBe(asked); + // Archive never sends "fetch", even when the body asks for it. + const dry = await request.post("/api/library/archive", { headers: page, data: bodies.archive }); + expect(dry.status()).toBe(200); + expect((await last(request)).body).toEqual({ slug: LIB, handle: "lid_watch", action: "archive", dryRun: true }); + expect((await dry.json()).sentence).toBe('Would make the channel "lid_watch-x" for @lid_watch, on no site, with sync off. Nothing is asked of X.'); + // An agent's merge cannot come through the page's route dressed as the operator's without a browser; from the page it is the operator's. + expect((await request.post("/api/library/organise", { headers: page, data: { lib: LIB, op: "merge", into: KETTLES, from: ["lids"], by: "agent" } })).status()).toBe(200); + expect((await last(request)).body).toEqual({ slug: LIB, op: "merge", into: KETTLES, from: ["lids"], by: "operator" }); + + // The accounts read: umtool's own pages only, never cached. + const read = await request.get(`/api/library/accounts?lib=${LIB}`); + expect(read.status()).toBe(200); + expect(read.headers()["cache-control"]).toBe("private, no-store"); + expect((await read.json()).accounts.map((a: { handle: string }) => a.handle)).toContain("teapot_news"); + expect((await request.get(`/api/library/accounts?lib=${LIB}`, { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403); + expect((await request.get("/api/library/accounts?lib=../x")).status()).toBe(400); +}); + test("with the editor down, or holding no library, the page says so in a sentence", async ({ page, request }) => { await reset(request, "unreachable"); await page.goto(lib()); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -715,6 +715,10 @@ export const GROUPS = [ " watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", " purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", " seen <lib> (<topic>… | --all) --by operator Mark seen: what --new counts from", + " rename <lib> <topic> --title NAME | move <lib> --to TOPIC (--id ID,… | --thread ID) [--create] [--by agent|operator]", + " merge <lib> --into TOPIC --from T,… --by operator topics into one: no unmerge", + " publish <lib> <topic> [--channel SLUG] (--dry-run | --confirm DIGEST --by operator) kept posts into a channel on no site", + " accounts <lib> [--topic T] [--limit N] | archive <lib> <handle> [--name N] [--dry-run] [--fetch]", ], docs: [ ["`library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]`", @@ -727,6 +731,14 @@ export const GROUPS = [ "the editor's `purge-trending`, in two steps: `--dry-run` says what would be removed (the captures of posts THE OPERATOR dropped: posts, files, bytes; how many of them are gone from the page, whose capture is the only copy; how many an agent dropped, which are never purged) and prints the `--confirm` digest; the removal carries it and `--by operator`. Judgements stay; media another post uses is left; refused while a capture is queued or running, or when the set changed since the dry run (**exit 1**)"], ["`library seen <lib> (<topic>… \\| --all) --by operator`", "Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count. **The operator's**: without `--by operator` it is refused (an agent marking topics seen would hide posts from him), and a topic the library does not hold is refused, nothing marked (**exit 1**)"], + ["`library rename <lib> <topic> --title NAME [--by agent\\|operator]` · `library move <lib> --to TOPIC (--id ID,… \\| --thread ID) [--create] [--by agent\\|operator]`", + "the editor's `organise-trending`. **rename** changes a topic's name and nothing else (its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused, and so is a rename while a read of the library is queued or running). **move** puts posts, or every post of one thread, into another topic (`--create` makes a topic of that name when there is none); judgements and captures are untouched and a later read never moves a post back. Both say `agent` unless told, and who is recorded"], + ["`library merge <lib> --into TOPIC --from T,… --by operator`", + "the editor's `organise-trending`, op `merge`: every post, page and read of the `--from` topics goes into `--into`, and they are gone. **There is no unmerge, so it is the operator's**: without `--by operator` it is refused before the editor is asked (**exit 1**). Refused while a read of the library is queued or running. One watch stands (the target's, with its own terms; else the merged topic's moves to it), and the sentence says which. umtool's Mark seen state follows: the earliest of the merged topics' marks stands"], + ["`library publish <lib> <topic> [--channel SLUG] (--dry-run \\| --confirm DIGEST --by operator)`", + "the editor's `publish-trending`, in two steps: `--dry-run` says exactly what would be written (the channel's slug and whether it is made, posts, files, bytes; the sites the channel is already on, where what is added goes public at the next build; posts moved into the topic and by whom; files that no longer match their capture and are not copied; posts published as their words alone; posts published before and no longer kept, which stay) and prints the `--confirm` digest; the publish carries it and **`--by operator`** (an agent's is refused, **exit 1**). Only posts THE OPERATOR kept are published, into an ordinary channel on NO site whose files are copies; `--channel` names the slug at the first publish only. Refused while a read or a capture of the library is queued or running"], + ["`library accounts <lib> [--topic T] [--limit N] [--json]` · `library archive <lib> <handle> [--name N] [--dry-run] [--fetch]`", + "the library's **accounts** (handle, posts, kept, topics, the X channels that already archive each), and **archive**: the editor's `x-search-lead`, action `archive`, for an account of the library: `<handle>-x`, an X channel on no site that names nothing of the library. **It asks X nothing, now or later**: the channel is made with sync off (its priority paused) and no first fetch is started, and the editor's sentence says how to turn sync on and fetch; `--fetch` asks for the ordinary behaviour instead (the first fetch started, sync on); `--dry-run` creates nothing"], ], }, { diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -358,6 +358,12 @@ export const VERBS = Object.freeze([ none("library watch", "corpus", "watch a topic of a trending library, or stop (the editor's watch-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), none("library purge", "corpus", "remove dropped posts' captures, after a dry run (the editor's purge-trending)", "the removal is the operator's press on the Posts library page (/tools/library), in two steps"), none("library seen", "corpus", "mark topics of a trending library seen", "the Posts library page's Mark seen (/tools/library)"), + none("library rename", "corpus", "rename a topic of a trending library; its id stays (the editor's organise-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library move", "corpus", "move posts of a trending library into another topic (the editor's organise-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library merge", "corpus", "merge topics of a trending library into one; no unmerge (the editor's organise-trending)", "the merge is the operator's press on the Posts library page (/tools/library), behind a confirm"), + none("library publish", "corpus", "publish a topic's kept posts into a channel on no site, after a dry run (the editor's publish-trending)", "the publish is the operator's press on the Posts library page (/tools/library), in two steps"), + none("library accounts", "corpus", "a trending library's accounts: posts, kept, topics", "a read the Posts library page (/tools/library) shows"), + none("library archive", "corpus", "archive an account of a trending library as its own X channel, on no site (the editor's x-search-lead)", "the Posts library page's Archive this account (/tools/library)"), none("library help", "corpus", "the library verbs", "prints the usage"), form("pool stats", "corpus", "the render pool: what it holds", [opt("--since", { help: "7d" })], { shape: "pool stats" }), form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()], { confirm: { what: "delete render pool files past the cap", unless: ["--dry-run"] } }), diff --git a/umtool/lib/library/caller.mjs b/umtool/lib/library/caller.mjs @@ -19,7 +19,7 @@ import { crossSiteRefusal } from "../report/sameOrigin.mjs"; import { fromBrowser } from "../report/writeGuard.mjs"; export const AGENTS_GO_ELSEWHERE = - "This route is the Posts library page's: its presses are written as the operator's, so it takes them from umtool's own page in a browser only. An agent or a script uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` or `umtool library`, and says \"by\": \"agent\"."; + "This route is the Posts library page's: its presses are written as the operator's, so it takes them from umtool's own page in a browser only. An agent or a script uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` / `organise-trending` / `publish-trending` or `umtool library`, and says \"by\": \"agent\"."; /** * Why a request may not press, or null when it is the page's. diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -7,7 +7,9 @@ // WHO IS ASKING. `--by` is "agent" unless told otherwise, as `pnpm ops` is: an // agent's judgement is a suggestion the operator's outranks, a failing watch is // restarted only by the operator, and a purge's removal is the operator's -// (`--by operator`, with the `--confirm` its `--dry-run` printed). +// (`--by operator`, with the `--confirm` its `--dry-run` printed). Lane +// x-trending-publish: `rename` and `move` are anyone's and record who; a +// `merge` (no unmerge) and a `publish` are the operator's (`--by operator`). // // Needs the editor at ARCHILYZER_EDITOR_URL (default http://localhost:3001) and // WORKER_TOKEN (else the editor's env files). Exit 1 on a refusal. @@ -15,11 +17,11 @@ // Plain ESM. import { agentToken } from "../annotations/agentAuth.mjs"; import { REPORTS_ROOT } from "../paths.mjs"; -import { archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listLibraries, listLibrary, listLibraryIds, purge, watch } from "./client.mjs"; -import { markSeen, seenOf } from "./seen.mjs"; +import { archiveAccount, archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listAccounts, listLibraries, listLibrary, listLibraryIds, organise, publish, purge, watch } from "./client.mjs"; +import { markSeen, mergeSeen, seenOf } from "./seen.mjs"; -const VALUE_FLAGS = new Set(["--topic", "--state", "--author", "--q", "--limit", "--offset", "--id", "--thread", "--note", "--by", "--interval", "--hours", "--confirm", "--where"]); -const BOOL_FLAGS = new Set(["--json", "--gone", "--media", "--new", "--filter", "--yes", "--dry-run", "--no-archive", "--shots", "--all"]); +const VALUE_FLAGS = new Set(["--topic", "--state", "--author", "--q", "--limit", "--offset", "--id", "--thread", "--note", "--by", "--interval", "--hours", "--confirm", "--where", "--title", "--to", "--into", "--from", "--channel", "--name"]); +const BOOL_FLAGS = new Set(["--json", "--gone", "--media", "--new", "--filter", "--yes", "--dry-run", "--no-archive", "--shots", "--all", "--create", "--fetch"]); export const LIBRARY_USAGE = [ "umtool library [ls] [--json] the editor's X trending libraries", @@ -32,6 +34,15 @@ export const LIBRARY_USAGE = [ "umtool library watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", "umtool library purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", "umtool library seen <lib> (<topic>… | --all) --by operator Mark seen: what `--new` counts from (the operator's mark)", + "umtool library rename <lib> <topic> --title NAME [--by agent|operator] a topic's name (its id stays)", + "umtool library move <lib> --to TOPIC (--id ID[,ID…] | --thread ID) [--create] [--by agent|operator]", + " posts into another topic (--create makes it)", + "umtool library merge <lib> --into TOPIC --from T[,T…] --by operator topics into one: the operator's, no unmerge", + "umtool library publish <lib> <topic> [--channel SLUG] (--dry-run | --confirm DIGEST --by operator)", + " the operator's kept posts into a channel on no site", + "umtool library accounts <lib> [--topic T] [--limit N] [--json] the library's accounts: posts, kept, topics", + "umtool library archive <lib> <handle> [--name NAME] [--dry-run] [--fetch]", + " <handle>-x on no site, with sync off; asks X nothing unless --fetch", ].join("\n"); class Refusal extends Error {} @@ -207,6 +218,81 @@ export async function libraryCommand(args, deps = {}) { say({ ok: true, ...marked }, `${topics.length} topic${topics.length === 1 ? "" : "s"} marked seen: ${topics.join(", ")}`); return 0; } + if (sub === "rename") { + need(lib); + const topic = words[2]; + if (!topic || !flags["--title"]) throw new Refusal("rename: umtool library rename <lib> <topic> --title NAME"); + const done = await organise(ask, { slug: lib, op: "rename", topic, title: flags["--title"], by: byOf(flags) }); + say(done, String(done.sentence ?? "")); + return 0; + } + if (sub === "move") { + need(lib); + if (!flags["--to"]) throw new Refusal("move: --to names the topic the posts go to"); + if ((flags["--id"] !== undefined) === (flags["--thread"] !== undefined)) throw new Refusal("move: give --id or --thread, one of them"); + const ids = flags["--id"] !== undefined ? String(flags["--id"]).split(",").map((x) => x.trim()).filter(Boolean) : null; + if (ids && !ids.length) throw new Refusal("move: --id names no post"); + const done = await organise(ask, { slug: lib, op: "move", to: flags["--to"], ...(ids ? { ids } : { thread: String(flags["--thread"]) }), ...(flags["--create"] ? { create: true } : {}), by: byOf(flags) }); + const skipped = (done.skipped ?? []).map((x) => `\n skipped ${x.id}: ${x.reason}`).join(""); + say(done, `${done.sentence ?? ""}${skipped}`); + return 0; + } + if (sub === "merge") { + need(lib); + const from = String(flags["--from"] ?? "").split(",").map((x) => x.trim()).filter(Boolean); + if (!flags["--into"] || !from.length) throw new Refusal("merge: umtool library merge <lib> --into TOPIC --from T[,T…] --by operator"); + // There is no unmerge: it is the operator's, here as in the editor. + if (byOf(flags) !== "operator") throw new Refusal("merge: merging topics is the operator's (it cannot be undone): say --by operator. An agent may rename a topic and move posts."); + const done = await organise(ask, { slug: lib, op: "merge", into: flags["--into"], from, by: "operator" }); + // umtool's own Mark seen state follows the merge (the earliest mark stands). + const merged = (done.merged ?? []).map((m) => m.id); + const seen = done.into?.id && merged.length ? await mergeSeen(reportsRoot, { slug: lib, into: done.into.id, from: merged }).catch((e) => ({ error: e instanceof Error ? e.message : String(e) })) : null; + say({ ...done, ...(seen ? { seen } : {}) }, String(done.sentence ?? "")); + return 0; + } + if (sub === "publish") { + need(lib); + const topic = words[2]; + if (!topic) throw new Refusal("publish: umtool library publish <lib> <topic> (--dry-run | --confirm DIGEST --by operator)"); + const scope = { slug: lib, topic, ...(flags["--channel"] ? { channel: flags["--channel"] } : {}) }; + const by = byOf(flags); + if (flags["--dry-run"]) { + const plan = await publish(ask, { ...scope, dryRun: true, by }); + say(plan, `${plan.sentence}\nchannel: ${plan.channel}${plan.creates ? " (new)" : ""} · ${plan.posts} post${plan.posts === 1 ? "" : "s"} · ${plan.files} file${plan.files === 1 ? "" : "s"} · ${plan.bytes} bytes\nconfirm: ${plan.confirm} (umtool library publish ${lib} ${topic}${flags["--channel"] ? ` --channel ${flags["--channel"]}` : ""} --confirm ${plan.confirm} --by operator)`); + return 0; + } + if (!flags["--confirm"]) throw new Refusal("publish: --dry-run says what would be written and prints the --confirm the publish needs"); + if (by !== "operator") throw new Refusal("publish: publishing a topic is the operator's: say --by operator. An agent may ask for --dry-run."); + const done = await publish(ask, { ...scope, confirm: flags["--confirm"], by }); + say(done, String(done.sentence ?? "")); + return 0; + } + if (sub === "accounts") { + const view = await listAccounts(ask, { slug: need(lib), topic: flags["--topic"] ?? null, limit: whole(flags, "--limit", 1) }); + const rows = view.accounts ?? []; + say( + { slug: lib, accounts: rows, total: view.total, posts: view.posts, more: view.more }, + rows.length + ? `${view.total} account${view.total === 1 ? "" : "s"} over ${view.posts} post${view.posts === 1 ? "" : "s"}${view.more ? ` (${rows.length} shown)` : ""}\n${rows.map((a) => `@${a.handle} ${a.posts} post${a.posts === 1 ? "" : "s"} · ${a.kept} kept · topics: ${(a.topics ?? []).join(", ")}${a.archivedAs?.length ? ` · archived as ${a.archivedAs.join(", ")}` : ""}`).join("\n")}` + : `${lib} holds no post yet.`, + ); + return 0; + } + if (sub === "archive") { + need(lib); + const handle = words[2]; + if (!handle) throw new Refusal("archive: umtool library archive <lib> <handle>"); + const done = await archiveAccount(ask, { slug: lib, handle: handle.replace(/^@/, ""), ...(flags["--name"] ? { name: flags["--name"] } : {}), ...(flags["--dry-run"] ? { dryRun: true } : {}), ...(flags["--fetch"] ? { fetch: true } : {}) }); + const h = handle.replace(/^@/, ""); + const text = flags["--dry-run"] + ? `Would make the channel "${done.slug}" for @${h}, on no site${flags["--fetch"] ? ", and start its first fetch" : ", with sync off. Nothing is asked of X"}. A dry run creates nothing.` + : flags["--fetch"] + ? `Made the channel "${done.slug}" for @${h}, on no site. Its first fetch was started${done.jobIds?.length ? ` (${done.jobIds.join(", ")})` : ""}.` + : // The editor's own sentence: sync off, nothing asked of X, how to turn sync on and run the first fetch. + String(done.sentence ?? `Made the channel "${done.slug}" for @${h}, on no site.`); + say(done, text); + return 0; + } throw new Refusal(`library: unknown verb "${sub}"\n${LIBRARY_USAGE}`); } catch (e) { err(e instanceof Error ? e.message : String(e)); diff --git a/umtool/lib/library/client.mjs b/umtool/lib/library/client.mjs @@ -1,8 +1,9 @@ // THE POSTS LIBRARY, ASKED OF THE EDITOR (lane posts-library). One set of // calls for umtool's Posts library page (through lib/articles/generation.ts // askEditor) and for `umtool library` (through editorAsker below): the -// listing (GET /api/ops/trending) and the three presses (judge-trending, -// watch-trending, purge-trending). +// listing (GET /api/ops/trending) and the presses (judge-trending, +// watch-trending, purge-trending; lane x-trending-publish: organise-trending, +// publish-trending and, for an account, x-search-lead's archive). // // UMTOOL WRITES NOTHING OF A LIBRARY AND ASKS X NOTHING. Every press is the // editor's action; a keep's capture is the editor's paced job. This module @@ -114,6 +115,40 @@ export function purge(ask, body) { return ask("/api/ops/purge-trending", { method: "POST", body }); } +/** organise-trending's body, as given ({slug, op: "rename" | "move" | "merge", …, by}) (lane x-trending-publish). */ +export function organise(ask, body) { + return ask("/api/ops/organise-trending", { method: "POST", body }); +} + +/** publish-trending's body, as given ({slug, topic, dryRun: true, channel?} or {slug, topic, confirm, by: "operator"}). */ +export function publish(ask, body) { + return ask("/api/ops/publish-trending", { method: "POST", body }); +} + +/** + * A library's accounts: { accounts: [{handle, name?, posts, kept, keptByOperator, topics, last, archivedAs?}], total, posts, more }. + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {{ slug: string, topic?: string | null, limit?: number }} p + */ +export function listAccounts(ask, { slug, topic, limit }) { + const q = new URLSearchParams({ slug, accounts: "1" }); + if (topic) q.set("topic", topic); + if (limit) q.set("limit", String(limit)); + return ask(`/api/ops/trending?${q.toString()}`); +} + +/** + * "Archive this account": the editor's x-search-lead, action "archive", for an account of the library — + * `<handle>-x` on no site. FROM A LIBRARY IT ASKS X NOTHING: `fetch` is sent only when it is true. + * @param {{ slug: string, handle: string, name?: string, dryRun?: boolean, fetch?: boolean }} p + */ +export function archiveAccount(ask, p) { + return ask("/api/ops/x-search-lead", { + method: "POST", + body: { slug: p.slug, handle: p.handle, action: "archive", ...(p.name ? { name: p.name } : {}), ...(p.dryRun ? { dryRun: true } : {}), ...(p.fetch === true ? { fetch: true } : {}) }, + }); +} + /** * What became of the keeps' archiving, as one sentence (or "" when nothing was kept). * @param {{ kept: string[], archives: Array<{jobId?: string, error?: string, ids: string[]}> }} r diff --git a/umtool/lib/library/load.ts b/umtool/lib/library/load.ts @@ -20,7 +20,8 @@ import { REPORTS_ROOT } from "@/lib/paths.mjs"; export type LibraryView = ReturnType<typeof parseLibraryView>; export type LibrarySummary = { slug: string; name: string; topics: number; posts: number; unjudged: number }; -export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number }; +// `published` (lane x-trending-publish): the channel the topic's kept posts were published into, when they were. +export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number; published?: { channel: string; firstAt: string; lastAt: string; posts: number } }; export type LibraryPost = XTrendingPostRow; export type LibraryData = diff --git a/umtool/lib/library/organise.test.mjs b/umtool/lib/library/organise.test.mjs @@ -0,0 +1,230 @@ +// Organise, publish and "Archive this account" from the Posts library page +// and from `umtool library` (lane x-trending-publish): each the editor's +// action; the page's presses stamped the operator's whatever the body says; +// the CLI's `--by` "agent" unless told, with a merge and a publish the +// operator's. A fake `ask` (no socket), a temp reports root. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { libraryCommand } from "./cli.mjs"; +import { archivePress, organisePress, PressError, publishPress } from "./presses.mjs"; +import { markSeen, mergeSeen, seenFile, seenOf } from "./seen.mjs"; + +const CONFIRM = "FAKE-TEST-VALUE01234567"; +const SYNC_OFF = (slug, handle) => `Made the channel "${slug}" for @${handle}, on no site, with sync off (its priority is paused): nothing was asked of X, and nothing will be until you say so. To turn sync on, set its priority to normal on /channels. Its first fetch is Fetch posts on its page.`; + +function editor({ refuse } = {}) { + const asked = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + if (refuse) throw new Error(refuse); + const b = init.body ?? {}; + if (route === "/api/ops/organise-trending") { + if (b.op === "rename") return { ok: true, op: "rename", topic: b.topic, title: b.title, was: "Kettles", changed: true, sentence: `Topic "Kettles" is now "${b.title}".` }; + if (b.op === "move") return { ok: true, op: "move", to: { id: "cups", title: "Cups", created: false }, moved: b.ids ?? ["11", "12"], skipped: [{ id: "99", reason: "not in this library" }], sentence: "2 posts moved." }; + return { ok: true, op: "merge", into: { id: "kettles", title: "Kettles" }, merged: [{ id: "cups", title: "Cups", posts: 2, pages: 1 }], posts: 2, pages: 2, watch: { dropped: [] }, sentence: '"Cups" is now part of "Kettles". This cannot be undone.' }; + } + if (route === "/api/ops/publish-trending") { + return b.dryRun + ? { ok: true, dryRun: true, channel: b.channel ?? "kettles", creates: true, posts: 2, files: 3, bytes: 204, confirm: CONFIRM, sentence: 'Publishing "Kettles" would make the channel "kettles", on no site.' } + : { ok: true, dryRun: false, channel: "kettles", creates: true, posts: 2, files: 3, bytes: 204, confirm: CONFIRM, sentence: 'Publishing "Kettles" made the channel "kettles", on no site.' }; + } + if (route === "/api/ops/x-search-lead") { + if (b.dryRun) return { ok: true, dryRun: true, slug: `${b.handle}-x`, fields: {} }; + // From a library with no "fetch": sync off, and the editor's own sentence. + return b.fetch ? { ok: true, slug: `${b.handle}-x`, jobIds: ["job-1"] } : { ok: true, slug: `${b.handle}-x`, jobIds: [], syncOff: true, sentence: SYNC_OFF(`${b.handle}-x`, b.handle) }; + } + if (route.startsWith("/api/ops/trending?")) { + return { ok: true, accounts: [{ handle: "teapot_news", posts: 3, kept: 2, keptByOperator: 1, topics: ["kettles", "cups"], archivedAs: ["teapot_news-x"] }, { handle: "saucer_fan", posts: 1, kept: 0, keptByOperator: 0, topics: ["cups"] }], total: 2, posts: 4, more: 0 }; + } + throw new Error(`unexpected ${route}`); + }; + return { ask, asked, posts: () => asked.filter((a) => a.method === "POST") }; +} + +async function withRoot(fn) { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-organise-")); + try { + return await fn(root); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +async function cli(args, e, root) { + const lines = []; + const errors = []; + const code = await libraryCommand(args, { ask: e.ask, out: (s) => lines.push(s), err: (s) => errors.push(s), reportsRoot: root }); + return { code, lines, errors }; +} + +test("the page's organise presses are the operator's, whatever the body says about who", async () => { + const e = editor(); + await organisePress(e.ask, { lib: "lib", op: "rename", topic: " kettles ", title: " Teapots ", by: "agent" }); + await organisePress(e.ask, { lib: "lib", op: "move", to: "cups", ids: ["11", "11", "12"], by: "agent" }); + await organisePress(e.ask, { lib: "lib", op: "move", to: "Spoons", thread: "11", create: true }); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", op: "rename", topic: "kettles", title: "Teapots", by: "operator" }, + { slug: "lib", op: "move", to: "cups", ids: ["11", "12"], by: "operator" }, + { slug: "lib", op: "move", to: "Spoons", thread: "11", create: true, by: "operator" }, + ]); + for (const [body, re] of [ + [{ lib: "lib", op: "split" }, /"op" is/], + [{ lib: "../x", op: "rename", topic: "a", title: "b" }, /"lib" is the library's slug/], + [{ lib: "lib", op: "rename", topic: "a" }, /"title" is/], + [{ lib: "lib", op: "move", to: "cups" }, /one of them/], + [{ lib: "lib", op: "move", to: "cups", ids: ["x"] }, /list of post ids/], + [{ lib: "lib", op: "move", ids: ["11"] }, /"to" is/], + [{ lib: "lib", op: "merge", into: "kettles", from: [] }, /"from" is/], + ]) { + await assert.rejects(organisePress(e.ask, body), (err) => err instanceof PressError && re.test(err.message), JSON.stringify(body)); + } + assert.equal(e.posts().length, 3, "a refused press asks the editor nothing"); +}); + +test("a merge press is the operator's, and umtool's Mark seen state follows it: the earliest mark stands", async () => { + await withRoot(async (root) => { + await markSeen(root, { slug: "lib", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + await markSeen(root, { slug: "lib", topics: ["kettles", "spoons"], now: Date.parse("2026-11-18T08:00:00.000Z") }); + const e = editor(); + const out = await organisePress(e.ask, { lib: "lib", op: "merge", into: "Kettles", from: [" Cups "], by: "agent" }, { mergeSeen: (lib, into, from) => mergeSeen(root, { slug: lib, into, from }) }); + assert.deepEqual(e.posts()[0].body, { slug: "lib", op: "merge", into: "Kettles", from: ["Cups"], by: "operator" }); + // By the EDITOR's ids (kettles, cups), not the names the press was sent with. + assert.deepEqual(out.seen, { slug: "lib", into: "kettles", seenAt: "2026-11-17T08:00:00.000Z", changed: true }); + const seen = await seenOf(root, "lib"); + assert.deepEqual(Object.keys(seen).sort(), ["kettles", "spoons"]); + assert.equal(seen.kettles, "2026-11-17T08:00:00.000Z"); + assert.equal(JSON.parse(await readFile(seenFile(root), "utf8")).libraries.lib.topics.kettles.previous, "2026-11-18T08:00:00.000Z"); + + // A topic that stays and was never marked stays unmarked; nothing to change writes nothing. + await markSeen(root, { slug: "other", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + assert.deepEqual(await mergeSeen(root, { slug: "other", into: "kettles", from: ["cups"] }), { slug: "other", into: "kettles", seenAt: null, changed: true }); + assert.deepEqual(await seenOf(root, "other"), {}); + assert.deepEqual(await mergeSeen(root, { slug: "other", into: "kettles", from: ["cups"] }), { slug: "other", into: "kettles", seenAt: null, changed: false }); + + // The mark failing to follow is said, never thrown: the merge is done. + const said = await organisePress(e.ask, { lib: "lib", op: "merge", into: "kettles", from: ["cups"] }, { mergeSeen: async () => { throw new Error("posts-library.json does not parse"); } }); + assert.deepEqual(said.seen, { error: "posts-library.json does not parse" }); + assert.equal(said.ok, true); + }); +}); + +test("the publish press: two steps, the operator's; a confirm that is not a dry run's digest asks nothing", async () => { + const e = editor(); + const dry = await publishPress(e.ask, { lib: "lib", topic: "kettles", dryRun: true, by: "agent", channel: "Kettles-2026" }); + assert.equal(dry.confirm, CONFIRM); + await publishPress(e.ask, { lib: "lib", topic: "kettles", confirm: CONFIRM, by: "agent" }); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", topic: "kettles", channel: "Kettles-2026", dryRun: true, by: "operator" }, + { slug: "lib", topic: "kettles", confirm: CONFIRM, by: "operator" }, + ]); + for (const [body, re] of [ + [{ lib: "lib", topic: "kettles" }, /carries the "confirm" its dry run answered/], + [{ lib: "lib", topic: "kettles", confirm: "yes" }, /carries the "confirm"/], + [{ lib: "lib", dryRun: true }, /"topic" is/], + [{ lib: "lib", topic: "kettles", dryRun: true, channel: "../x" }, /"channel" is the channel's slug/], + ]) { + await assert.rejects(publishPress(e.ask, body), (err) => err instanceof PressError && re.test(err.message), JSON.stringify(body)); + } + assert.equal(e.posts().length, 2); + const refused = editor({ refuse: "A read or a capture of this library is queued or running: publish once it has finished (its job is on /jobs)." }); + await assert.rejects(publishPress(refused.ask, { lib: "lib", topic: "kettles", confirm: CONFIRM }), /queued or running/); +}); + +test("Archive this account from the page: the lead action, and never a fetch", async () => { + const e = editor(); + const dry = await archivePress(e.ask, { lib: "lib", handle: "@saucer_fan", name: "Saucer Fan", dryRun: true, fetch: true }); + assert.equal(dry.sentence, 'Would make the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off. Nothing is asked of X.'); + const done = await archivePress(e.ask, { lib: "lib", handle: "saucer_fan", fetch: true }); + // The editor's sentence, whole: sync off, nothing asked of X, how to turn sync on and run the first fetch. + assert.equal(done.sentence, SYNC_OFF("saucer_fan-x", "saucer_fan")); + assert.equal(done.syncOff, true); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", handle: "saucer_fan", action: "archive", name: "Saucer Fan", dryRun: true }, + { slug: "lib", handle: "saucer_fan", action: "archive" }, + ]); + await assert.rejects(archivePress(e.ask, { lib: "lib", handle: "not a handle" }), /"handle" is the account's handle/); +}); + +test("umtool library rename / move: --by is agent unless told", async () => { + await withRoot(async (root) => { + const e = editor(); + assert.equal((await cli(["rename", "lib", "kettles", "--title", "Teapots"], e, root)).code, 0); + assert.equal((await cli(["move", "lib", "--to", "cups", "--id", "11, 12", "--by", "operator"], e, root)).code, 0); + const moved = await cli(["move", "lib", "--to", "Spoons", "--thread", "11", "--create"], e, root); + assert.match(moved.lines[0], /2 posts moved\.\n skipped 99: not in this library/); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", op: "rename", topic: "kettles", title: "Teapots", by: "agent" }, + { slug: "lib", op: "move", to: "cups", ids: ["11", "12"], by: "operator" }, + { slug: "lib", op: "move", to: "Spoons", thread: "11", create: true, by: "agent" }, + ]); + for (const [args, re] of [ + [["rename", "lib", "kettles"], /rename: umtool library rename/], + [["move", "lib", "--id", "11"], /--to names the topic/], + [["move", "lib", "--to", "cups"], /--id or --thread, one of them/], + [["move", "lib", "--to", "cups", "--id", "1", "--thread", "1"], /one of them/], + ]) { + const r = await cli(args, e, root); + assert.equal(r.code, 1); + assert.match(r.errors[0], re); + } + assert.equal(e.posts().length, 3); + }); +}); + +test("umtool library merge and publish want --by operator; a dry run of a publish is anyone's and prints the confirm", async () => { + await withRoot(async (root) => { + const e = editor(); + const agent = await cli(["merge", "lib", "--into", "kettles", "--from", "cups"], e, root); + assert.equal(agent.code, 1); + assert.match(agent.errors[0], /merging topics is the operator's \(it cannot be undone\): say --by operator/); + assert.equal(e.posts().length, 0, "an agent's merge asks the editor nothing"); + await markSeen(root, { slug: "lib", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + await markSeen(root, { slug: "lib", topics: ["kettles"], now: Date.parse("2026-11-18T08:00:00.000Z") }); + const merged = await cli(["merge", "lib", "--into", "kettles", "--from", "cups, spoons", "--by", "operator", "--json"], e, root); + assert.equal(merged.code, 0); + assert.deepEqual(e.posts()[0].body, { slug: "lib", op: "merge", into: "kettles", from: ["cups", "spoons"], by: "operator" }); + assert.deepEqual(JSON.parse(merged.lines[0]).seen, { slug: "lib", into: "kettles", seenAt: "2026-11-17T08:00:00.000Z", changed: true }); + + const dry = await cli(["publish", "lib", "kettles", "--dry-run"], e, root); + assert.equal(dry.code, 0); + assert.match(dry.lines[0], /would make the channel "kettles", on no site\.\nchannel: kettles \(new\) · 2 posts · 3 files · 204 bytes\nconfirm: FAKE-TEST-VALUE01234567 \(umtool library publish lib kettles --confirm FAKE-TEST-VALUE01234567 --by operator\)/); + assert.deepEqual(e.posts()[1].body, { slug: "lib", topic: "kettles", dryRun: true, by: "agent" }); + const asAgent = await cli(["publish", "lib", "kettles", "--confirm", CONFIRM], e, root); + assert.equal(asAgent.code, 1); + assert.match(asAgent.errors[0], /publishing a topic is the operator's: say --by operator/); + const none = await cli(["publish", "lib", "kettles"], e, root); + assert.match(none.errors[0], /--dry-run says what would be written/); + assert.equal(e.posts().length, 2); + const done = await cli(["publish", "lib", "kettles", "--confirm", CONFIRM, "--by", "operator", "--channel", "kettles"], e, root); + assert.equal(done.code, 0); + assert.deepEqual(e.posts()[2].body, { slug: "lib", topic: "kettles", channel: "kettles", confirm: CONFIRM, by: "operator" }); + assert.match(done.lines[0], /made the channel "kettles", on no site\./); + }); +}); + +test("umtool library accounts and archive: the accounts by posts; archive asks X nothing unless --fetch", async () => { + await withRoot(async (root) => { + const e = editor(); + const view = await cli(["accounts", "lib", "--topic", "cups", "--limit", "20"], e, root); + assert.equal(view.code, 0); + assert.equal(e.asked[0].route, "/api/ops/trending?slug=lib&accounts=1&topic=cups&limit=20"); + assert.equal(view.lines[0], "2 accounts over 4 posts\n@teapot_news 3 posts · 2 kept · topics: kettles, cups · archived as teapot_news-x\n@saucer_fan 1 post · 0 kept · topics: cups"); + const dry = await cli(["archive", "lib", "@saucer_fan", "--dry-run"], e, root); + assert.equal(dry.lines[0], 'Would make the channel "saucer_fan-x" for @saucer_fan, on no site, with sync off. Nothing is asked of X. A dry run creates nothing.'); + const made = await cli(["archive", "lib", "saucer_fan", "--name", "Saucer Fan"], e, root); + assert.equal(made.lines[0], SYNC_OFF("saucer_fan-x", "saucer_fan")); + const fetched = await cli(["archive", "lib", "saucer_fan", "--fetch"], e, root); + assert.equal(fetched.lines[0], 'Made the channel "saucer_fan-x" for @saucer_fan, on no site. Its first fetch was started (job-1).'); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", handle: "saucer_fan", action: "archive", dryRun: true }, + { slug: "lib", handle: "saucer_fan", action: "archive", name: "Saucer Fan" }, + { slug: "lib", handle: "saucer_fan", action: "archive", fetch: true }, + ]); + assert.equal((await cli(["archive", "lib"], e, root)).code, 1); + }); +}); diff --git a/umtool/lib/library/presses.mjs b/umtool/lib/library/presses.mjs @@ -8,7 +8,7 @@ // agent's hand is `pnpm ops` or `umtool library`, which say "agent". // // Plain ESM. -import { JUDGE_STATES, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, purge, watch } from "./client.mjs"; +import { JUDGE_STATES, archiveAccount, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, organise, publish, purge, watch } from "./client.mjs"; import { listingParamsOf, parseLibraryView } from "./filters.mjs"; import { pressSetOf, undoSetOf } from "./undo.mjs"; @@ -156,3 +156,101 @@ export async function purgePress(ask, body) { if (typeof body.confirm !== "string" || !/^[0-9a-f]{16}$/.test(body.confirm)) throw new PressError(`A removal carries the "confirm" its dry run answered: press Purge, read what it would remove, then confirm.`); return purge(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); } + +// ── lane x-trending-publish: organise, publish, archive an account ───────── + +const topicOf = (body, key, what) => { + if (typeof body[key] !== "string" || !body[key].trim()) throw new PressError(`"${key}" is ${what}`); + return body[key].trim(); +}; + +/** + * POST /api/library/organise — the editor's organise-trending, the operator's: + * { lib, op: "rename", topic, title } + * { lib, op: "move", to, ids: [..] | thread, create? } + * { lib, op: "merge", into, from: [topic, …] } no unmerge: the page asks before it sends this + * Answers the editor's answer. After a MERGE umtool's own Mark seen state follows (`deps.mergeSeen(lib, into, + * from)`: the earliest mark stands), and the answer says so in `seen`. + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {any} body + * @param {{ mergeSeen?: (lib: string, into: string, from: string[]) => Promise<any> }} [deps] + */ +export async function organisePress(ask, body, deps = {}) { + const lib = libOf(body); + if (body.op === "rename") { + return organise(ask, { slug: lib, op: "rename", topic: topicOf(body, "topic", "the topic's id"), title: topicOf(body, "title", "the topic's new name"), by: OPERATOR }); + } + if (body.op === "move") { + const hasIds = body.ids !== undefined; + const hasThread = body.thread !== undefined; + if (hasIds === hasThread) throw new PressError(`a move names posts ("ids") or one thread ("thread"), one of them`); + if (hasIds && (!Array.isArray(body.ids) || body.ids.length === 0 || !body.ids.every((id) => typeof id === "string" && ID.test(id)))) throw new PressError(`"ids" is a list of post ids`); + if (hasThread && (typeof body.thread !== "string" || !ID.test(body.thread))) throw new PressError(`"thread" is a thread's root post id`); + return organise(ask, { + slug: lib, + op: "move", + to: topicOf(body, "to", "the topic the posts go to"), + ...(hasIds ? { ids: [...new Set(body.ids)] } : { thread: body.thread }), + ...(body.create === true ? { create: true } : {}), + by: OPERATOR, + }); + } + if (body.op === "merge") { + const into = topicOf(body, "into", "the topic that stays"); + if (!Array.isArray(body.from) || body.from.length === 0 || !body.from.every((t) => typeof t === "string" && t.trim())) throw new PressError(`"from" is the list of topics merged into it`); + const out = await organise(ask, { slug: lib, op: "merge", into, from: body.from.map((t) => t.trim()), by: OPERATOR }); + // The editor's ids, not the names asked with. + const merged = Array.isArray(out.merged) ? out.merged.map((m) => m.id) : []; + let seen = null; + if (deps.mergeSeen && out.into?.id && merged.length) { + try { + seen = await deps.mergeSeen(lib, out.into.id, merged); + } catch (err) { + // The merge is done and cannot be undone: the mark not following is said, never thrown. + seen = { error: err instanceof Error ? err.message : String(err) }; + } + } + return { ...out, ...(seen ? { seen } : {}) }; + } + throw new PressError(`"op" is "rename", "move" or "merge"`); +} + +/** + * POST /api/library/publish: { lib, topic, dryRun: true, channel? } says what would be written; { lib, topic, + * confirm, channel? } publishes what that dry run showed. The operator's, in two steps. Answers the editor's + * publish-trending answer. + */ +export async function publishPress(ask, body) { + const lib = libOf(body); + const topic = topicOf(body, "topic", "the topic's id"); + if (body.channel !== undefined && body.channel !== null && body.channel !== "" && (typeof body.channel !== "string" || !SLUG.test(body.channel))) { + throw new PressError(`"channel" is the channel's slug: letters, digits, ".", "_" and "-"`); + } + const scope = { slug: lib, topic, ...(body.channel ? { channel: body.channel } : {}) }; + if (body.dryRun === true) return publish(ask, { ...scope, dryRun: true, by: OPERATOR }); + if (typeof body.confirm !== "string" || !/^[0-9a-f]{24}$/.test(body.confirm)) throw new PressError(`A publish carries the "confirm" its dry run answered: press Publish, read what it would write, then confirm.`); + return publish(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); +} + +/** + * POST /api/library/archive: { lib, handle, name?, dryRun? } — "Archive this account": the editor's + * x-search-lead (action "archive") for an account of the library. It makes `<handle>-x` on NO site, WITH SYNC OFF, + * and ASKS X NOTHING, now or at the scheduler's next tick: this route never sends "fetch". Answers + * { ok, slug, jobIds?, dryRun?, fields?, sentence }. + */ +export async function archivePress(ask, body) { + const lib = libOf(body); + if (typeof body.handle !== "string" || !/^@?[A-Za-z0-9_]{1,30}$/.test(body.handle)) throw new PressError(`"handle" is the account's handle`); + if (body.name !== undefined && typeof body.name !== "string") throw new PressError(`"name" is the account's display name`); + const handle = body.handle.replace(/^@/, ""); + const out = await archiveAccount(ask, { slug: lib, handle, ...(body.name ? { name: body.name } : {}), ...(body.dryRun === true ? { dryRun: true } : {}) }); + return { + ...out, + // The made channel's sentence is the EDITOR's (sync off, nothing asked of X, how to turn sync on and run the + // first fetch): nothing is added to it here. + sentence: + body.dryRun === true + ? `Would make the channel "${out.slug}" for @${handle}, on no site, with sync off. Nothing is asked of X.` + : String(out.sentence ?? `Made the channel "${out.slug}" for @${handle}, on no site.`), + }; +} diff --git a/umtool/lib/library/seen.mjs b/umtool/lib/library/seen.mjs @@ -107,27 +107,13 @@ async function locked(file, fn) { } } -/** - * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and - * a file that is there and does not parse. - * @param {string} reportsRoot - * @param {{ slug: string, topics: string[], now?: number }} o - * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} - */ -export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { - if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); - if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); +/** One read-modify-write of the state file, under its lock and in turn. `change(lib)` edits the library's entry and answers the result. */ +function mutate(reportsRoot, slug, change) { const run = () => locked(seenFile(reportsRoot), async () => { const current = await readSeen(reportsRoot); if (current.error) throw new Error(current.error); const lib = current.libraries[slug] ?? { topics: {} }; - const seenAt = new Date(now).toISOString(); - const marked = {}; - for (const t of topics) { - const was = lib.topics[t]?.seenAt; - lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; - marked[t] = lib.topics[t]; - } + const result = change(lib); current.libraries[slug] = lib; const file = seenFile(reportsRoot); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); @@ -139,9 +125,54 @@ export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw err; } - return { slug, topics: marked }; + return result; }); const p = chain.then(run, run); chain = p.catch(() => {}); return p; } + +/** + * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and + * a file that is there and does not parse. + * @param {string} reportsRoot + * @param {{ slug: string, topics: string[], now?: number }} o + * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} + */ +export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { + if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); + if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); + return mutate(reportsRoot, slug, (lib) => { + const seenAt = new Date(now).toISOString(); + const marked = {}; + for (const t of topics) { + const was = lib.topics[t]?.seenAt; + lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; + marked[t] = lib.topics[t]; + } + return { slug, topics: marked }; + }); +} + +/** + * TOPICS WERE MERGED IN THE EDITOR (lane x-trending-publish): their marks become one. The topic that stays keeps + * the EARLIEST of the marks the merged topics had, so nothing a mark had not covered is hidden as seen; a topic + * that stays and was never marked stays unmarked (all of it new). The merged topics' marks are dropped. Writes + * nothing when there is nothing to change. + * @param {string} reportsRoot + * @param {{ slug: string, into: string, from: string[] }} o + * @returns {Promise<{ slug: string, into: string, seenAt: string | null, changed: boolean }>} + */ +export async function mergeSeen(reportsRoot, { slug, into, from }) { + if (!SLUG.test(String(slug))) throw new Error(`"${slug}" is not a library's slug`); + if (!TOPIC.test(String(into)) || !Array.isArray(from) || !from.every((t) => TOPIC.test(String(t)))) throw new Error("a merge names the topic that stays and the topics merged into it"); + const current = (await seenOf(reportsRoot, slug)) ?? {}; + if (!from.some((t) => current[t]) ) return { slug, into, seenAt: current[into] ?? null, changed: false }; + return mutate(reportsRoot, slug, (lib) => { + const mine = lib.topics[into]?.seenAt; + const marks = [mine, ...from.map((t) => lib.topics[t]?.seenAt)].filter(Boolean).sort(); + for (const t of from) delete lib.topics[t]; + if (mine && marks[0] !== mine) lib.topics[into] = { seenAt: marks[0], previous: mine }; + return { slug, into, seenAt: lib.topics[into]?.seenAt ?? null, changed: true }; + }); +} diff --git a/umtool/lib/report/xTrendingLibrary.test.mjs b/umtool/lib/report/xTrendingLibrary.test.mjs @@ -134,10 +134,22 @@ test("posts-library: nothing of the page, its routes or its CLI imports a way in for (const spec of imports) { for (const way of WAYS_OUT) assert.ok(!spec.includes(way), `${f.rel} imports ${spec}`); } - // The editor is asked for the listing and the three presses, and nothing else. + // The editor is asked for the listing and the presses, and nothing else. LANE x-trending-publish ADDS + // THREE, and they are the only ways out of a library there are: organising its topics (inside the + // library), PUBLISHING A TOPIC (the editor's publish-trending: the operator's, in two steps, into an + // ordinary channel on no site) and archiving an ACCOUNT (the editor's x-search-lead: `<handle>-x` on no + // site, nothing of the library in it). Still no way into a project, a report, an article, the post + // archive or a site: a site carries the PUBLISHED channel, by the operator's separate act in the editor. + const EDITOR_ROUTES = [ + "/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending", + "/api/ops/organise-trending", "/api/ops/publish-trending", "/api/ops/x-search-lead", + ]; for (const m of f.text.matchAll(/["'`](\/api\/ops\/[a-z-]+)/g)) { - assert.ok(["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"].includes(m[1]), `${f.rel} asks the editor for ${m[1]}`); + assert.ok(EDITOR_ROUTES.includes(m[1]), `${f.rel} asks the editor for ${m[1]}`); } + // The lead action is asked for "archive" only, and a site is never named to the editor from here. + if (f.text.includes("/api/ops/x-search-lead")) assert.ok(/action: "archive"/.test(f.text) && !/action: "(never|restore)"/.test(f.text), `${f.rel} asks the lead action for more than archive`); + assert.ok(!/siteMemberships|site-config|\/api\/ops\/sites|create-site/.test(f.text), `${f.rel} names a site to the editor`); // No request of X or of any outside host is built here. assert.ok(!/fetch\(\s*["'`]https?:\/\//.test(f.text), `${f.rel} fetches an outside address`); // The corpus is never written from here.