Archilyzer · Source

archilyzer

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

commit d911017d7513a488b633abe9889eee935a3cb9b0
parent 60da519815592d6dfa0e54bf50684a9c5b188e51
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 12:21:53 -0500

review 1 S2-S10 and nits: the publish proves which directory it made, says where a post goes public and who moved it in; organise is crash-safe and waits for reads

S2, S3. published.json keeps the channel DIRECTORY's inode and birth time
(not config.json's, which changes with every edit). A channel deleted and
made again by hand, even empty and of the same shape, is refused; so is a
bare directory of the slug. A publish cut between making the channel and
recording it leaves `pending`: only an empty channel is then taken up.
S4. The dry run and its sentence name the sites the channel is on; the
confirm digest includes them. S5. `movedIn`: the posts to publish that
were moved into the topic, and by whom. S8. A file whose bytes are not
what its capture recorded is not copied, is reported, and gets no digest.
S10. Pin fixtures for the three precedence cases.
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 with none, else
leaves that channel alone and names it. S9. A rename waits for a read or
a reparse of the library, as a merge does.
Nits: stale .publish-*.part swept under the lock; context posts, thread
redaction and article extraction rebuilt field by field; the plan's inputs
all read from disk inside the lock; ids are digits before they are paths;
planArchiveXLead asks the posts, not a 500-capped listing; a thread is
moved by the key the listing shows.

Found on the way: Configure refused a published channel outright, and
Configure's Sites section is how a channel is put on a site. It now sets
such a channel's name and sites (channel-config {sites} is the ops twin)
and still refuses any source.

Docs, COMMANDS.md and umtool docs regenerated; plans/x-trending.md,
OPERATING and the changelog say what changed.

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

Diffstat:
MCOMMANDS.md | 6+++---
MOPERATING.md | 46++++++++++++++++++++++++++++++++--------------
Mcommon/controller/publishXTrending.test.ts | 240++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/publishXTrending.ts | 322++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/controller/xSearchLeads.test.ts | 21+++++++++++++++++++++
Mcommon/controller/xSearchLeads.ts | 6+++---
Mcommon/lib/xTrending/accounts.ts | 7+++++++
Mcommon/lib/xTrending/organise.test.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/xTrending/organise.ts | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/xTrending/published.ts | 30++++++++++++++++++++++++++++--
Mcommon/lib/xTrending/store.ts | 10+++++++---
Meditor/CHANGELOG.md | 9+++++++--
Meditor/app/api/ops/organise-trending/route.ts | 15++++++++++-----
Meditor/app/api/ops/publish-trending/route.test.ts | 4+++-
Meditor/app/api/ops/publish-trending/route.ts | 19++++++++++++++-----
Meditor/app/channels/[slug]/xTrendingActions.ts | 7++++++-
Meditor/app/channels/actions.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/e2e/x-trending.spec.ts | 30++++++++++++++++++++++++++----
Mplans/x-trending.md | 47+++++++++++++++++++++++++++++++++++++++++++----
Mscripts/archilyzer-ops.mjs | 23++++++++++++++++++-----
Mumtool/components/tools/library/OrganisePanel.tsx | 11+++++++++++
Mumtool/docs/cli.md | 6+++---
Mumtool/docs/tools.md | 10+++++++---
Mumtool/e2e/fixtures/editor-stub-trending.mjs | 15++++++++++++---
Mumtool/e2e/library.spec.ts | 13+++++++++++++
Mumtool/lib/cli/groups.mjs | 6+++---
26 files changed, 1004 insertions(+), 145 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -217,13 +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. An X TRENDING LIBRARY's accounts (get trending &lt;slug&gt; --accounts) are leads too: with "slug" a library, "archive" creates &lt;handle&gt;-x for an account that wrote a post the library holds, on no site, naming nothing of the library, and ASKS X NOTHING: there the first fetch is not started unless "fetch": true (it is its own step: fetch-posts). "never" and "restore" are a search channel's only. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'`<br>`pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action":"archive","dryRun":true}'` | +| `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. {"slug", "op": "move", "to", "ids": \[..\] \| "thread", "create"?} moves posts (or every post of one thread, by its root post's id) into the topic "to" (an id or a name; "create": true makes a topic of that name, with no trending page, when there is none) -&gt; {to, moved, skipped}; judgements and captures are untouched, a later read never moves a post back, and it is not refused beside a read or a capture. {"slug", "op": "merge", "into", "from": \[..\], "by": "operator"} puts every post, page and read of the "from" topics into "into" and removes them -&gt; {into, merged, posts, pages, watch}. THERE IS NO UNMERGE, so a merge is the operator's (an agent's is refused), and it is refused while a read or a reparse of the library is queued or running. The merged topics' ids keep meaning "into"; judgements are untouched; ONE watch stands (the target's live watch with its own terms, else the first merged topic's moves to it), and "sentence" says which. | `pnpm ops organise-trending --json '{"slug":"trending","op":"rename","topic":"kettle-festival","title":"Kettle festival 2026"}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"move","to":"kettle-festival","ids":["1900000000000001001"]}'`<br>`pnpm ops organise-trending --json '{"slug":"trending","op":"merge","into":"kettle-festival","from":["teapots"],"by":"operator"}'` | -| `publish-trending` | publish-trending publishes a topic of an X trending library, in two steps. {"slug", "topic", "dryRun": true, "channel"?} writes nothing: it says what would be written (channel, creates, posts, ids, already, files, bytes, textOnly, noLongerKept) and answers "confirm", a digest of exactly that. {"slug", "topic", "confirm", "by": "operator"} publishes: the topic's posts whose judgement in force is keep BY THE OPERATOR (their own entry, or their thread's) go into an ORDINARY posts channel ("channel": a slug of the topic's name unless given, fixed at the first publish) with their captured media and screenshots, COPIED (the library keeps its own; a purge of the library and a delete of the channel do not reach each other). An agent's keep is not published. The channel is on NO site (adding it to one is a separate step: site-config, /sites), names nothing of the library (no judgement, note, read, watch or gone mark) and is never fetched. It is the operator's press: an agent's publish is refused (an agent may ask for the dry run), and a confirm that no longer matches is refused with nothing written. Re-publishing adds newly kept posts and files and removes nothing: a post published before and since dropped is listed in noLongerKept and left; textOnly lists kept posts with no capture yet (published as their words; a later publish adds the files). Refused while a read, a reparse or a capture of the library is queued or running (a dry run then says inFlight), and when a channel of that slug exists that this publish did not make. | `pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}'`<br>`pnpm ops publish-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}'` | +| `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` | diff --git a/OPERATING.md b/OPERATING.md @@ -814,8 +814,9 @@ pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action ``` - **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, their judgements and a queued read are - untouched. A name another topic answers to is refused. + - `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 @@ -824,11 +825,19 @@ pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action 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. + 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. @@ -837,29 +846,38 @@ pnpm ops x-search-lead --json '{"slug":"trending","handle":"example","action 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 (`pnpm ops site-config`, /sites). `social.x.visibility` applies to it as to - any X channel. + 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`, the availability check and - an X run refuse it with one sentence, Sync all and an X run's list leave it out, and Configure says what it is. + - **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, and it holds no post the record does not name. 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; one that was renamed is left alone, and the next publish makes a new channel under the - recorded slug. + 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**: the first fetch is started only with - `"fetch": true`, or later with `fetch-posts`. After that the channel is an account channel like any other, - synced by the scheduler when its interval says so. + 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 diff --git a/common/controller/publishXTrending.test.ts b/common/controller/publishXTrending.test.ts @@ -8,7 +8,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +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"; @@ -28,6 +29,8 @@ 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, @@ -54,6 +57,8 @@ function post(lib: string, id: string, text: string, extra: Partial<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 }); @@ -67,9 +72,10 @@ function capture(libRoot: string, id: string, files: Record<string, string>, rec url: `https://x.com/i/status/${id}`, capturedAt: "2026-11-18T10:05:00.000Z", state: "captured", - ...(files["shot.png"] ? { shot: { name: "shot.png", bytes: 1, sha256: "0".repeat(64) } } : {}), + // 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: 1, sha256: "0".repeat(64), url: `https://pbs.twimg.com/media/${name}` })), + media: media.map((name) => ({ name, bytes: files[name].length, sha256: sha(files[name]), url: `https://pbs.twimg.com/media/${name}` })), ...record, }), ); @@ -152,7 +158,7 @@ test("the allowlists: a post's unknown field, its library slug and its index-tim 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, files: [{ name: "article.json", bytes: 1, sha256: "e" }], error: "ae" }, + 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" } }; @@ -164,6 +170,40 @@ test("the allowlists: a post's unknown field, its library slug and its index-tim 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 () => { @@ -280,8 +320,14 @@ test("THE PIN: the published channel holds the operator's keeps and nothing that // 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" } }, + "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 }, + }, }); }); @@ -296,7 +342,7 @@ test("re-publishing adds the newly kept and removes nothing: a post since droppe 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, { topic: "kettle-festival", title: "Teapots", by: "operator" }); + 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)); @@ -323,7 +369,7 @@ test("a purge of the library after a publish frees exactly what it would have fr 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, { topic: "kettle-festival", title: "Teapots", by: "operator" }); + 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 }); @@ -405,3 +451,183 @@ test("the three-part proof: a slug a stranger holds is refused — never recorde 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 @@ -31,14 +31,17 @@ // 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's own content — a THREE-PART PROOF, asked before a byte is +// 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. -// A channel deleted and made again by hand, or one another hand wrote posts -// into, fails it and is refused; a slug that is free is simply made (again). +// 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 @@ -61,7 +64,7 @@ import { createHash, randomBytes } from "node:crypto"; import { constants as FS } from "node:fs"; -import { copyFile, lstat, mkdir, realpath, rename, rm, stat } from "node:fs/promises"; +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"; @@ -70,9 +73,13 @@ import { readPostAvailability, readSeenPostIds, writePostAvailability, writePost 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 } from "../lib/xTrending/published"; +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, @@ -88,6 +95,8 @@ import { type ArticleCaptureRecord, type CapturedFile, type PostCaptureRecord, + type PostContextPost, + type ThreadCaptureRecord, } from "../social/postCapture"; import { channelExists, createChannel, isValidChannelSlug, readChannelConfig } from "./channels"; @@ -192,12 +201,16 @@ export function publishedCaptureOf(record: PostCaptureRecord, has: (name: string state: a.state, ...(typeof a.title === "string" ? { title: a.title } : {}), blocks: Number(a.blocks) || 0, - ...(a.extraction ? { extraction: a.extraction } : {}), + ...(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, @@ -206,32 +219,76 @@ export function publishedCaptureOf(record: PostCaptureRecord, has: (name: string state: record.state, ...(record.sensitive ? { sensitive: true } : {}), ...(shot ? { shot } : {}), - ...(shot && record.shotScope ? { shotScope: record.shotScope } : {}), + ...(shot && (record.shotScope === "item" || record.shotScope === "page") ? { shotScope: record.shotScope } : {}), ...(shot && record.trimmed ? { trimmed: true } : {}), mediaState: record.mediaState, media, ...(article ? { article } : {}), - ...(threadFile && record.thread + ...(threadFile && record.thread && redaction ? { thread: { ...threadFile, - parentId: record.thread.parentId, - ...(record.thread.parentHandle ? { parentHandle: record.thread.parentHandle } : {}), - ...(record.thread.parentAuthor ? { parentAuthor: record.thread.parentAuthor } : {}), + 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, - ...(record.thread.parentBadge ? { parentBadge: record.thread.parentBadge } : {}), - parentFrom: record.thread.parentFrom, - redaction: record.thread.redaction, + ...(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, ...(ctx.quoted ? { quoted: ctx.quoted } : {}), ...(ctx.parent ? { parent: ctx.parent } : {}) } } + ? { + 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 = { @@ -258,15 +315,24 @@ export type PublishXTrendingResult = { // 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[]; @@ -284,7 +350,7 @@ export const PUBLISH_IS_THE_OPERATORS = 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): nothing was written. Ask for the dry run again."; + "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.`; @@ -298,9 +364,18 @@ export function formatPublishBytes(b: number): string { return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`; } -export function xTrendingPublishConfirm(o: { library: string; topic: string; channel: string; ids: ReadonlyArray<string>; files: ReadonlyArray<string> }): string { +// 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()])) + .update(JSON.stringify([o.library, o.topic, o.channel, [...o.ids].sort(), [...o.files].sort(), [...(o.sites ?? [])].sort()])) .digest("hex") .slice(0, 24); } @@ -308,35 +383,53 @@ export function xTrendingPublishConfirm(o: { library: string; topic: string; cha export function publishSentence(r: Omit<PublishXTrendingResult, "sentence">): string { const would = r.dryRun; const where = r.creates - ? `${would ? "would make" : "made"} the channel "${r.channel}", on no site,` + ? `${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 ? " Adding the channel to a site is a separate step." : ""; + 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}${text}${gone}${copies}${site}${waits}`; + return `${head}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; } // ── the plan ─────────────────────────────────────────────────────────────── -type PlannedFile = { id: string; name: string; from: string; to: string; bytes: number }; +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[]; @@ -345,42 +438,109 @@ type Plan = { type Fail = { ok: false; error: string }; -async function isRegularFileInside(file: string, root: string): Promise<number | null> { +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) ? st.size : null; + 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; recorded: Record<string, string> | undefined }, + 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 THREE-PART PROOF. - if (!o.recorded) return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "this library has no record of publishing into it") }; + // 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) => !o.recorded![id]); + 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] = await Promise.all([ + 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])); - const kept = [...(listing.ids ?? [])].sort(); + // 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; @@ -390,7 +550,11 @@ async function plan( const built = post ? publishedPostOf(post, o.channel) : null; if (!built) continue; if (have.has(id)) already++; - else fresh.push(built); + 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) { @@ -398,27 +562,48 @@ async function plan( 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 bytes = await isRegularFileInside(path.join(from, name), o.libRoot); - if (bytes === null) continue; - files.push({ id, name, from: path.join(from, name), to: path.join(to, name), bytes }); + 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(o.recorded ?? {}).filter((id) => have.has(id) && !keptSet.has(id)).sort(); - return { ok: true, plan: { channelRoot, creates: !exists, kept, fresh, already, files, captured, textOnly, noLongerKept } }; + 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 }, + }; } -// One file, copied: to a temp name beside its place, checked against its -// source, then renamed. Never a link. +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 [a, b] = await Promise.all([fileDigest(f.from), fileDigest(tmp)]); - if (a.sha256 !== b.sha256 || a.bytes !== b.bytes) throw new Error(`the copy of ${f.name} (post ${f.id}) does not match its source`); + 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 }); @@ -426,6 +611,14 @@ async function copyChecked(f: PlannedFile): Promise<void> { } } +// 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( @@ -446,19 +639,21 @@ export async function publishXTrendingTopic( 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 record = (await readXTrendingPublished(libRoot))[topic.id]; - if (record && ask.channel !== undefined && ask.channel !== record.slug) { - return { ok: false, error: `"${topic.title}" is published into the channel "${record.slug}": a topic has one channel, fixed at its first publish.` }; + 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 = record?.slug ?? ask.channel ?? ask.deriveSlug(topic.title); + 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 look = () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, recorded: record?.posts }); + 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}`) }); + 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, @@ -466,12 +661,15 @@ export async function publishXTrendingTopic( 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 } : {}), @@ -493,25 +691,47 @@ export async function publishXTrendingTopic( // 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. + // 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 = all[topic.id] ?? { slug: channel, firstAt: at, lastAt: at, posts: {} }; + 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. + // 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, then each capture's record. + // 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); diff --git a/common/controller/xSearchLeads.test.ts b/common/controller/xSearchLeads.test.ts @@ -203,3 +203,24 @@ test("an X trending library's accounts: handle, posts, kept, topics, who archive // "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 @@ -23,7 +23,7 @@ import { } from "../lib/xSearch/leads"; import { handleFromAccountUrl } from "../social/fetchers"; import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "../lib/xTrending/config"; -import { listXTrendingAccounts, X_TRENDING_ACCOUNTS_MAX, type XTrendingAccounts } from "../lib/xTrending/accounts"; +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) => @@ -127,8 +127,8 @@ export async function planArchiveXLead( // the same plan, for an account that wrote a post the library holds. The // channel made names nothing of the library. if (isXTrendingChannel(config)) { - const { accounts } = await listXTrendingAccounts(path.join(paths.channelsDir, slug), { limit: X_TRENDING_ACCOUNTS_MAX }); - if (!accounts.some((a) => a.key === key)) { + // 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) }; diff --git a/common/lib/xTrending/accounts.ts b/common/lib/xTrending/accounts.ts @@ -82,3 +82,10 @@ export async function listXTrendingAccounts( 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 @@ -4,7 +4,8 @@ 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, mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } from "./organise"; +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"; @@ -15,6 +16,7 @@ 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 { @@ -60,7 +62,7 @@ const watchOn = async (dir: string, topic: string, by: "agent" | "operator", int 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, { topic: "kettles", title: " Teapots of the week ", by: "agent", now: NOW }); + 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/); @@ -70,17 +72,17 @@ test("rename: the title changes, the id stays, and who renamed is recorded; a na 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, { topic: "kettles", title: "Teapots of the week", by: "agent" }); + 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, { topic: "kettles", title: taken, by: "operator" }); + 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, { topic: "spoons", title: "x", by: "operator" }); + 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, { topic: "kettles", title: "x".repeat(121), by: "operator" }); + 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, { topic: "kettles", title: "x", by: "somebody" as never }); + const who = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "x", by: "somebody" as never }); assert.ok(!who.ok && /"by" is/.test(who.error)); }); @@ -221,3 +223,85 @@ test("merge, only the merged topic watched: its watch becomes the target's; none 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 @@ -2,7 +2,10 @@ // 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, addresses and a queued read keep meaning it. +// 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 @@ -23,6 +26,11 @@ // 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 @@ -30,7 +38,7 @@ // over); pages X answered "gone" for stay unread. // // Written in an order a second run completes: the membership, the watches, -// then topics.json — all inside the topics file's lock, so no read records +// 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"; @@ -47,6 +55,7 @@ import { 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; @@ -73,9 +82,21 @@ export type Refused = { ok: false; error: string }; 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; now?: number }, + 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 }; @@ -84,9 +105,12 @@ export async function renameXTrendingTopic( if (problem) return { ok: false, error: problem }; const title = ask.title.trim(); const at = new Date(ask.now ?? Date.now()).toISOString(); - return mutateXTrendingTopics<XTrendingRenameResult>(channelRoot, (topics) => { + 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); @@ -130,6 +154,9 @@ export async function moveXTrendingPosts( 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); @@ -149,12 +176,18 @@ export async function moveXTrendingPosts( let wanted: string[] = hasIds ? [...new Set(ask.ids)] : []; if (hasThread) { const [membership, posts] = await Promise.all([readXTrendingMembership(channelRoot), ask.posts ?? readXTrendingPosts(channelRoot)]); - const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); - wanted = [...byId.values()].filter((p) => xTrendingThreadOf(p, membership, byId) === ask.thread).map((p) => p.id); + // 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) => { + return mutateXTrendingTopics<XTrendingMoveResult>(channelRoot, async (topics, save) => { let target = resolveXTrendingTopic(topics, ask.to); let created = false; if (!target) { @@ -168,6 +201,11 @@ export async function moveXTrendingPosts( 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) => { @@ -185,11 +223,12 @@ export async function moveXTrendingPosts( } return { write: moved.length > 0, result: { moved, skipped } }; }); - // A topic made for a move that moved nothing is not made. - if (created && out.moved.length === 0) topics.pop(); + // 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: created && out.moved.length > 0, + write: unmade, result: { ok: true, op: "move", @@ -216,6 +255,10 @@ export type XTrendingMergeResult = 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; @@ -310,7 +353,28 @@ export async function mergeXTrendingTopics( return { write: true, result: { dropped, ...(stands ? { stands } : {}) } }; }); - // 3. the topics + // 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); @@ -342,9 +406,14 @@ export async function mergeXTrendingTopics( 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}`, + `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 @@ -1,7 +1,8 @@ // 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}} +// 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 @@ -22,11 +23,24 @@ import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-ser 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> }; @@ -49,7 +63,19 @@ export async function readXTrendingPublished(channelRoot: string): Promise<Recor 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; } - out[id] = { slug: raw.slug, firstAt: str(raw.firstAt) ? raw.firstAt : "", lastAt: str(raw.lastAt) ? raw.lastAt : "", posts }; + 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; } diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -487,14 +487,18 @@ export function resolveXTrendingTopic<T extends { id: string; title: string; ali // 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[]) => Promise<{ write: boolean; result: T }> | { write: boolean; result: T }, + 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 { write, result } = await change(topics); - if (write) await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); + 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; }); } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -11,9 +11,14 @@ - 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. From a library it asks X - nothing; the first fetch is a separate step. + 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.** diff --git a/editor/app/api/ops/organise-trending/route.ts b/editor/app/api/ops/organise-trending/route.ts @@ -12,15 +12,16 @@ export const dynamic = "force-dynamic"; // POST { slug, op: "merge", into, from: [topic, …], by: "operator" } // -> { ok: true, slug, op, into: {id, title}, merged: [{id, title, posts, // pages}], posts, pages, watch: {stands?: {from, sentence}, dropped}, -// sentence } +// 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, their -// judgements and a queued read are untouched. Refused: a name another topic -// answers to. +// 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 @@ -34,7 +35,11 @@ export const dynamic = "force-dynamic"; // 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. +// 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) { diff --git a/editor/app/api/ops/publish-trending/route.test.ts b/editor/app/api/ops/publish-trending/route.test.ts @@ -48,7 +48,7 @@ await writeFile( ); await mkdir(path.join(lib, "trending", "posts-media", A), { recursive: true }); await writeFile(path.join(lib, "trending", "posts-media", A, "shot.png"), "12345"); -await writeFile(path.join(lib, "trending", "posts-media", A, "capture.json"), JSON.stringify({ version: 1, id: A, url: `https://x.com/i/status/${A}`, capturedAt: "2026-11-18T10:00:00.000Z", state: "captured", shot: { name: "shot.png", bytes: 5, sha256: "0".repeat(64) }, mediaState: "none", media: [] })); +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; @@ -75,6 +75,8 @@ test("publish-trending: the dry run writes nothing; the publish is the operator' { 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" }]) { diff --git a/editor/app/api/ops/publish-trending/route.ts b/editor/app/api/ops/publish-trending/route.ts @@ -6,8 +6,9 @@ export const dynamic = "force-dynamic"; // POST { slug, topic, dryRun: true, channel? } // -> { ok: true, slug, dryRun: true, library, topic: {id, title}, channel, -// creates, kept, posts, ids, already, files, bytes, textOnly: [ids], -// noLongerKept: [ids], inFlight?, confirm, sentence } +// 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 // @@ -29,7 +30,13 @@ export const dynamic = "force-dynamic"; // made, `posts` to add (`ids`), `files` and `bytes` to copy, `textOnly` (kept // posts with no capture yet: published as their words; a later publish adds // the files) and `noLongerKept` (published before, since dropped: reported, -// never removed). The publish carries the dry run's `confirm` and `by: +// 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. @@ -42,8 +49,10 @@ export const dynamic = "force-dynamic"; // CAPTURE OF THE LIBRARY QUEUED OR RUNNING (a dry run then says `inFlight: // true`), a `channel` other than the one the topic was published into, and A // CHANNEL OF THAT SLUG THIS PUBLISH DID NOT MAKE (one the library has no -// record of, one with a source of its own, or one holding a post this topic -// never published). +// 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"); diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -456,7 +456,12 @@ export async function organiseXTrendingAction(ask: OrganiseXTrendingAsk): Promis 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 }); + 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, diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -371,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, @@ -391,10 +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): the - // channel has no account, and the form's "a social source needs an account - // handle" would be the wrong thing to say of it. - if (isSourcelessPostsChannel(existing)) return { error: `${SOURCELESS_POSTS_CHANNEL(slug)} Configure has nothing to set for it; sites carry it like any channel (/sites).`, 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 }); diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -391,6 +391,10 @@ test("an X trending library: rename, move, merge; a topic published into an ordi 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"); @@ -419,13 +423,13 @@ test("an X trending library: rename, move, merge; a topic published into an ordi 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: "0".repeat(64) }, mediaState: "skipped", mediaOwed: "kept", media: [] }), + 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, kept: 1, posts: 1, ids: [A], already: 0, files: 1, bytes: 18, textOnly: [], noLongerKept: [] }); + 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. @@ -469,7 +473,9 @@ test("an X trending library: rename, move, merge; a topic published into an ordi ["capture-posts", { slug: "kettles-2026", ids: [A] }], ["check-post-availability", { slug: "kettles-2026" }], ["x-run", { channels: ["kettles-2026"] }], - ["channel-config", { slug: "kettles-2026", patch: { name: "Renamed by hand" } }], + // 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); @@ -483,7 +489,23 @@ test("an X trending library: rename, move, merge; a topic published into an ordi // 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, kept: 1, posts: 1, ids: [B], already: 0, files: 0, textOnly: [B], noLongerKept: [A] }); + 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)."); diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -228,9 +228,11 @@ again by the watch; keeping the post asks again. 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's content. +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`). +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. @@ -293,13 +295,50 @@ again by the watch; keeping the post asks again. 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" has a URL, so the sync scheduler treats it like any account channel once - its interval comes round. The press itself asks X nothing. +- 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 @@ -2024,7 +2024,9 @@ export function usage() { '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.", + " 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,', @@ -2038,13 +2040,21 @@ export function usage() { " 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.", + " 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 answers \"confirm\", a digest of", - ' exactly that. {"slug", "topic", "confirm", "by": "operator"} publishes:', + " 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', @@ -2061,7 +2071,10 @@ export function usage() { " 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.", + " 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"?}.', diff --git a/umtool/components/tools/library/OrganisePanel.tsx b/umtool/components/tools/library/OrganisePanel.tsx @@ -47,6 +47,10 @@ type PublishPlan = { 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; @@ -164,7 +168,14 @@ export function TopicOrganise({ lib, topic, topics, off, run, go, when }: { lib: {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"> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -100,10 +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). **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 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; 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**: the first fetch is started only with `--fetch`; `--dry-run` creates nothing | +| `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)) | diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md @@ -73,7 +73,7 @@ on no site. With the editor down, or no library in it, the page says so in a sen 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); **Move** the posts a press would judge (the selection, else the post, or its thread) into + 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. @@ -82,9 +82,13 @@ on no site. With the editor down, or no library in it, the page says so in a sen (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, and **asks X nothing**: its first fetch is a separate press - in the editor. An account an X channel already archives says so. + 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 @@ -146,6 +146,8 @@ function organise(body) { 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; @@ -169,6 +171,8 @@ function organise(body) { 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); } @@ -223,10 +227,12 @@ function publish(body) { 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()])).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, confirm }; + 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 say = (would) => + 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).` : ""}`; @@ -360,6 +366,9 @@ export function trendingControl(req, res, url, { json, readBody }) { 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; diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -622,6 +622,14 @@ test("organise: rename a topic, move the selection to another, merge behind a co // 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"); @@ -724,7 +732,12 @@ test("publish: the first press says exactly what would be written and writes not 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. diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -732,13 +732,13 @@ export const GROUPS = [ ["`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). **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"], + "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; 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"], + "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**: the first fetch is started only with `--fetch`; `--dry-run` creates nothing"], + "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"], ], }, {