Archilyzer · Source

archilyzer

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

commit 9a4990136abff0fdfe3fa01dfe9c7fb402fe49f7
parent b059c992f34ea8426f12267c509787df2f069705
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 09:46:41 -0500

Merge lane/posts-library: the trending library is judged in umtool, slice 3 -- a project-less Posts library page (/tools/library) shows the library by topic with the export's post viewer, media and captures, and takes Keep / Drop / Later per post or thread, notes, bulk presses over a filter, undo, a watch switch per topic and a mark for what is new; every press is the editor's action written as the operator's, taken from umtool's own page in a browser only, and umtool writes none of the library's files; `purge-trending` removes the captures of posts the operator dropped, in two steps, saying how many are gone from the page and leaving an agent's drops alone; the listing takes filters, paging and detail, and lists the libraries; `umtool library` is the page's CLI twin; media is served from the library's own media folder and nothing else; the library stays behind every publishing door

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

Diffstat:
MCOMMANDS.md | 7+++++--
Mcommon/bin/xTrendingPrivacy.test.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/PostBody.test.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/PostBody.tsx | 267+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/components/PostModal.tsx | 260++-----------------------------------------------------------------------------
Mcommon/controller/xTrendingWatch.test.ts | 4++--
Mcommon/controller/xTrendingWatch.ts | 2+-
Mcommon/lib/xTrending/mediaStore.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Acommon/lib/xTrending/purge.test.ts | 241+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/purge.ts | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.test.ts | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/xTrending/watch.ts | 2+-
Mcommon/publish/xTrendingReportDoor.test.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 21++++++++++++++++++++-
Aeditor/app/api/ops/purge-trending/route.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/purge-trending/route.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/trending/route.test.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/trending/route.ts | 114++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/xTrendingActions.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/x-trending.spec.ts | 39+++++++++++++++++++++++++++++++++++++++
Mmcp/src/xTrendingPrivacy.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackage.json | 2+-
Mplans/x-trending.md | 45+++++++++++++++++++++++++++++++++++++++++----
Mscripts/archilyzer-ops.mjs | 35+++++++++++++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 16+++++++++++++++-
Aumtool/app/api/library/judge/route.ts | 20++++++++++++++++++++
Aumtool/app/api/library/media/[lib]/[id]/[name]/route.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/library/purge/route.ts | 15+++++++++++++++
Aumtool/app/api/library/route.ts | 25+++++++++++++++++++++++++
Aumtool/app/api/library/seen/route.ts | 18++++++++++++++++++
Aumtool/app/api/library/watch/route.ts | 14++++++++++++++
Mumtool/app/globals.css | 3+++
Aumtool/app/tools/library/page.tsx | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/tools/page.tsx | 3++-
Mumtool/bin/umtool.mjs | 2++
Mumtool/components/AppNav.tsx | 2++
Mumtool/components/shell/JumpPalette.tsx | 2++
Aumtool/components/tools/library/LibraryView.tsx | 877+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 13+++++++++++++
Mumtool/docs/tools.md | 52++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/e2e/fixtures/editor-stub-trending.mjs | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 5+++++
Aumtool/e2e/fixtures/library-fixture.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/library.spec.ts | 626+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 24++++++++++++++++++++++++
Mumtool/lib/cli/verbs.mjs | 8++++++++
Mumtool/lib/cli/verbs.test.mjs | 1+
Mumtool/lib/hrefs.ts | 6++++++
Aumtool/lib/library/caller.mjs | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/library/caller.test.mjs | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/cli.mjs | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/cli.test.mjs | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/client.mjs | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/client.test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/filters.mjs | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/keys.mjs | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/load.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/media.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/media.test.mjs | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/mediaSrc.mjs | 12++++++++++++
Aumtool/lib/library/presses.mjs | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/presses.test.mjs | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/route.ts | 37+++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/seen.mjs | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/seen.test.mjs | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/undo.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/view.test.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/xTrendingLibrary.test.mjs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
69 files changed, 6069 insertions(+), 311 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -220,7 +220,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` | | `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 someone switches it on again. A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) is recorded gone from the page at that time (get trending: gone) - never "deleted". A page X no longer has is not read again, and ends the watch when it was the topic's last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?, "hours"?, "maxTopics"?}} changes the library's defaults; {"slug", "tick": true} runs one scan now (refused on an idle boot; two asks at once are one scan). get trending shows each topic's watch and what it is doing (watch.sentence). | `pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'`<br>`pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'` | +| `watch-trending` | watch-trending watches a topic of an X trending library: {"slug", "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}. While a topic is watched its trending page is read again every intervalMinutes (15-1440; default the library's, else 30) until hours from now (1-168; else 48), each tick the SAME single read-x-trending job on X's queue, started by the editor's own scan (once a minute, at most one read per scan, none while a trending read or capture of ANY library waits its turn: every library's ticks are one stream). A topic of several pages reads one page per tick, in turn. At most 4 topics of a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN, no page opened; "shots": true also screenshots every new post. "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"}'` | | `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` | @@ -390,7 +391,9 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending (mediaOwed "next": a later capture asks again; "kept": once the post is kept). A topic carries watch {on, intervalMinutes, until, shots, ticks, paused?, ended?, sentence} once it has been watched. Never the - raw capture, a cookie or a token. + raw capture, a cookie or a token. The route takes more for a judge + view (offset, state, by, gone, media, author, q, since, seen, ids, detail; no + slug lists the libraries): `umtool library` asks with them. get x-run [<run id>] is the X run as /review's X run console shows it: the latest run (or the one named) — each channel's status (queued, running, done with its new posts, deferred, failed), "summary" ("N diff --git a/common/bin/xTrendingPrivacy.test.ts b/common/bin/xTrendingPrivacy.test.ts @@ -251,3 +251,99 @@ test("the search itself catches a leak", () => { assert.throws(() => assertNoLeak([{ rel: "corpus.json", text: `{"slug":"${LIB}"}` }], "x")); assert.doesNotThrow(() => assertNoLeak([{ rel: "page-0001.json", text: PUBLIC_POST }], "x")); }); + +// ── lane posts-library: what the judge view added stays behind the same doors ── + +const JUDGE_VIEW_ONLY = ["xTrending/purge", "purgeXTrendingDropped", "removeXTrendingPostCapture", "summarizeXTrending", "xTrendingCaptureFiles", "purge-trending"]; + + +// Every call of `fn` in a source, with its WHOLE argument text (parentheses balanced, so a call whose +// first argument is itself a call — `listXTrending(path.join(a, b), { detail: true })` — is read to its end). +function callsOf(text: string, fn: string): string[] { + const out: string[] = []; + for (let at = text.indexOf(`${fn}(`); at >= 0; at = text.indexOf(`${fn}(`, at + 1)) { + let depth = 0; + let end = -1; + for (let i = at + fn.length; i < text.length; i++) { + if (text[i] === "(") depth++; + else if (text[i] === ")" && --depth === 0) { + end = i; + break; + } + } + out.push(text.slice(at + fn.length + 1, end < 0 ? text.length : end)); + } + return out; +} + +// The judge view's asks of the listing: no publishing source may make one. +const JUDGE_VIEW_ASKS = /\b(detail|ids|filter|offset|seen)\b\s*[:,}]/; +function judgeViewAsk(text: string): string | null { + for (const args of callsOf(text, "listXTrending")) { + // The options are everything after the first argument (the library's root). + if (JUDGE_VIEW_ASKS.test(args)) return `listXTrending(${args.replace(/\s+/g, " ").slice(0, 120)})`; + } + return null; +} + +function sourcesUnder(dir: string): { rel: string; text: string }[] { + const out: { rel: string; text: string }[] = []; + const walk = (d: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + if (e.name === "node_modules" || e.name.startsWith(".")) continue; + const p = path.join(d, e.name); + if (e.isDirectory()) walk(p); + else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\.|\.unit\./.test(e.name)) out.push({ rel: p, text: readFileSync(p, "utf8") }); + } + }; + if (existsSync(dir)) walk(dir); + return out; +} + +test("the judge view's listing carries the kept post's note and its capture's context; no build wrote them, and it gives no address or path", async () => { + const { SLICE2_MARKS } = await import("../lib/xTrending/__fixtures__/slice2Library"); + const { purgeXTrendingDropped } = await import("../lib/xTrending/purge"); + const { summarizeXTrending } = await import("../lib/xTrending/store"); + const detail = JSON.stringify(await listXTrending(libRoot, { detail: true })); + // It IS there for the one door that asks (so the search below watches the right words). + assert.ok(detail.includes(SLICE2_MARKS.note), "the detail listing carries the judgement's note"); + assert.ok(detail.includes(SLICE2_MARKS.context), "the detail listing carries the capture's context"); + // Names only: no media address, no bytes, no path on disk. + assert.ok(!detail.includes(SLICE2_MARKS.address) && !detail.includes(SLICE2_MARKS.media) && !detail.includes(SLICE2_MARKS.shot)); + assert.ok(!detail.includes(libRoot) && !detail.includes("responses.jsonl")); + // The ids listing, the one-line summary and a purge's dry run say nothing of a post's words. + const idsOnly = await listXTrending(libRoot, { ids: true }); + assert.deepEqual(idsOnly.posts, []); + for (const answer of [idsOnly.ids, await summarizeXTrending(libRoot), await purgeXTrendingDropped(libRoot, { slug: LIB, dryRun: true, captureInFlight: () => false })]) { + const text = JSON.stringify(answer); + for (const mark of [...MARKS, ...SLICE2_MARK_LIST]) assert.ok(!text.includes(mark), `an answer carries ${mark}`); + assert.ok(!text.includes(libRoot)); + } + // And still nothing of it in what the builds above wrote. + assertNoLeak([...filesUnder(paths.exportIndexDir), ...filesUnder(paths.exportPublicDir)], "index and public dirs, after the judge view's reads"); +}); + +test("no build, publisher, export, homepage or MCP module reaches the judge view's reads or the purge", () => { + const repo = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", ".."); + const dirs = ["common/bin", "common/publish", "common/views", "export/app", "export/lib", "homepage/app", "homepage/lib", "mcp/src"].map((d) => path.join(repo, d)); + const files = [...dirs.flatMap(sourcesUnder), ...sourcesUnder(path.join(repo, "common", "controller")).filter((f) => /buildIndex|compose|report/i.test(path.basename(f.rel)))]; + assert.ok(files.length > 50, "the sweep read the publishing sources"); + for (const f of files) { + for (const word of JUDGE_VIEW_ONLY) assert.ok(!f.text.includes(word), `${path.relative(repo, f.rel)} names ${word}`); + // The listing is asked there with a topic and a limit at most: never the judge view's detail, ids, filter or marks. + assert.equal(judgeViewAsk(f.text), null, `${path.relative(repo, f.rel)} asks the listing for the judge view's fields`); + } +}); + +test("the sweep catches the call shapes it guards against", () => { + // The shape a real caller has: the root built by a call, the options after it, over several lines. + assert.match(judgeViewAsk('const l = await listXTrending(path.join(paths.channelsDir, slug), { detail: true });') ?? "", /detail: true/); + assert.ok(judgeViewAsk("await listXTrending(\n path.join(a, b),\n {\n ...(topic ? { topic } : {}),\n ids: true,\n },\n);")); + assert.ok(judgeViewAsk("listXTrending(root(x), { filter: { state: \"drop\" } })")); + assert.ok(judgeViewAsk("listXTrending(root(x), { limit: 5, offset })")); + assert.ok(judgeViewAsk("listXTrending(root(x), { topic, seen })")); + // What a publishing source may ask: a root, a topic, a limit. + assert.equal(judgeViewAsk("listXTrending(path.join(a, b), { ...(topic ? { topic } : {}), ...(limit !== undefined ? { limit } : {}) })"), null); + assert.equal(judgeViewAsk("listXTrending(libRoot)"), null); + assert.equal(judgeViewAsk("// a comment about detail and ids\nfoo(detail)"), null); +}); diff --git a/common/components/PostBody.test.ts b/common/components/PostBody.test.ts @@ -0,0 +1,55 @@ +// PostBody on its own (lane posts-library): the post viewer's body drawn with +// no modal and no query client, and PostModal still exporting it. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test components/PostBody.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { PostBody, PostCapturePanel } from "./PostBody"; +import * as modal from "./PostModal"; +import type { Post } from "../lib/posts"; + +(globalThis as { React?: typeof React }).React = React; + +const POST: Post = { + id: "1900000000000001001", + slug: "lib/1900000000000001001", + channelSlug: "lib", + author: "teapot_news", + authorName: "Teapot News", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: "The kettle festival opens today.", + url: "https://x.com/teapot_news/status/1900000000000001001", + platform: "twitter", + isReply: false, + isRepost: false, + links: ["https://example.org/a"], + mediaCount: 2, +}; + +test("a post is drawn with its author, words, links and footer; its captured media in the capture panel", () => { + const html = renderToStaticMarkup( + React.createElement(PostBody, { + post: POST, + capture: { capturedAt: "2026-11-17T10:00:00.000Z", state: "captured", shot: { src: "/m/shot.png" }, media: [{ src: "/m/a.jpg", name: "a.jpg" }, { src: "/m/b.mp4", name: "b.mp4" }] }, + }), + ); + assert.match(html, /data-post-id="1900000000000001001"/); + assert.match(html, /Teapot News/); + assert.match(html, /@teapot_news/); + assert.match(html, /The kettle festival opens today\./); + assert.match(html, /data-post-capture-shot=""/); + assert.match(html, /<video src="\/m\/b\.mp4"/); + assert.match(html, /2 media \(captured\)/); + assert.match(html, /Open original/); + // Not marked deleted: the word is nowhere. + assert.doesNotMatch(html, /deleted/i); +}); + +test("PostModal exports the same PostBody and capture panel", () => { + assert.equal(modal.PostBody, PostBody); + assert.equal(modal.PostCapturePanel, PostCapturePanel); +}); diff --git a/common/components/PostBody.tsx b/common/components/PostBody.tsx @@ -0,0 +1,267 @@ +"use client"; + +// ONE POST, DRAWN: its author and time, its words, its captured screenshot +// and media, its links and its footer. The body of the post viewer +// (PostModal.tsx, which re-exports everything here), in a file of its own so +// a page that shows posts with no modal and no query client around them +// (umtool's Posts library) draws a post exactly as the viewer does. + +import { useMemo } from "react"; +import type { Post } from "../lib/posts"; +import { pageCaptureView } from "../lib/waybackPages/view"; +import { PageCaptureFacts } from "./PageCaptureFacts"; + +export function formatWhen(iso: string): string { + const ms = Date.parse(iso); + if (!Number.isFinite(ms)) return iso; + const d = new Date(ms); + return d.toLocaleString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }); +} + +// A post's capture (a screenshot and its attached media, taken by the +// editor's capture-posts job), as the page that renders this modal serves it. +// EDITOR-ONLY: the files live beside the channel (`posts-media/<id>/`) and are +// never published, so the export never passes `loadCapture` and never shows +// any of this. +export type PostCaptureView = { + capturedAt: string; + // The capture's state ("captured", "deleted", …), as recorded. + state: string; + // The post sat behind a sensitive-media cover when it was shot. + sensitive?: boolean; + shot?: { src: string }; + media: { src: string; name: string }[]; + // The X Article the post links to, when the capture opened it: its title, + // how that went, and its markdown when saved. + article?: { state: string; title?: string; md?: { src: string } }; +}; + +export function PostBody({ + post, + primary = false, + compact = false, + capture, +}: { + post: Post; + primary?: boolean; + compact?: boolean; + capture?: PostCaptureView | null; +}) { + const links = useMemo(() => post.links ?? [], [post.links]); + const capturedMedia = capture?.media.length ?? 0; + // A page record (a Wayback capture, release 37 S4): what the capture is, + // and the original named as possibly gone beside the Wayback copy. + const page = useMemo(() => pageCaptureView(post), [post]); + return ( + <article + data-post-id={post.id} + className={ + "rounded-md " + + (primary && compact ? "bg-warning-soft " : "") + + (compact ? "px-2 py-1.5" : "") + } + > + <header className="flex flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground"> + <span className="font-medium text-foreground"> + {post.authorName || post.author} + </span> + {post.authorName && <span>@{post.author}</span>} + <span>·</span> + <time dateTime={post.createdAt}>{formatWhen(post.createdAt)}</time> + {post.isRepost && <Badge>repost</Badge>} + {/* Every forum post after the first answers the thread; the badge + would be on all of them. Its place in the thread says more. */} + {post.isReply && !post.forum && <Badge>reply</Badge>} + {post.forum?.position && <Badge>#{post.forum.position}</Badge>} + {post.forum?.editedAt && ( + <span title={`Last edited ${formatWhen(post.forum.editedAt)}`}> + <Badge>edited</Badge> + </span> + )} + {/* The whole point of archiving: this post no longer exists upstream. */} + {post.isDeleted && ( + <span + title={ + post.availabilityCheckedAt + ? `Confirmed removed from the source (checked ${new Date(post.availabilityCheckedAt).toLocaleString()})` + : "Removed from the source platform" + } + className="rounded bg-rose-100 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-rose-800 dark:bg-rose-900/40 dark:text-rose-200" + > + deleted + </span> + )} + </header> + + <p className={"whitespace-pre-wrap " + (compact ? "text-sm" : "text-base mt-2")}> + {post.text} + </p> + + {capture && <PostCapturePanel capture={capture} />} + + {page && !compact && <PageCaptureFacts view={page} links={false} className="mt-2" />} + + {post.forum?.threadTitle && !compact && ( + <p className="mt-1 text-xs text-muted-foreground"> + In thread: {post.forum.threadTitle} + {post.forum.page ? ` · page ${post.forum.page}` : ""} + </p> + )} + + {post.media && post.media.length > 0 && !capturedMedia && ( + <ul data-post-media="" className="mt-2 flex flex-col gap-1"> + {post.media.map((m) => ( + <li key={`${m.kind}:${m.url}`} className="text-xs text-muted-foreground"> + {m.kind} + {m.provider ? ` (${m.provider})` : ""}:{" "} + {/^https?:\/\//.test(m.url) ? ( + <a + href={m.url} + target="_blank" + rel="noopener noreferrer" + className="text-primary underline break-all" + > + {m.name || m.url} + </a> + ) : ( + <span className="break-all">{m.name || m.url}</span> + )} + </li> + ))} + </ul> + )} + + {links.length > 0 && ( + <ul className="mt-2 flex flex-col gap-1"> + {links.map((href) => ( + <li key={href}> + <a + href={href} + target="_blank" + rel="noopener noreferrer" + className="text-xs text-primary underline break-all" + > + {href} + </a> + </li> + ))} + </ul> + )} + + <footer className="mt-2 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground"> + {page ? ( + <> + <a href={page.links.original.url} target="_blank" rel="noopener noreferrer" className="underline"> + {post.isDeleted ? "Original (deleted)" : page.links.original.label} + </a> + <a href={page.links.copy.url} target="_blank" rel="noopener noreferrer" className="underline"> + {page.links.copy.label} + </a> + </> + ) : ( + <a + href={post.url} + target="_blank" + rel="noopener noreferrer" + className="underline" + > + {post.isDeleted ? "Original (deleted)" : "Open original"} + </a> + )} + {post.engagement?.likes != null && ( + <span>{post.engagement.likes} likes</span> + )} + {post.engagement?.reposts != null && ( + <span>{post.engagement.reposts} reposts</span> + )} + {post.engagement?.replies != null && ( + <span>{post.engagement.replies} replies</span> + )} + {capturedMedia > 0 ? ( + <span>{capturedMedia} media (captured)</span> + ) : post.mediaCount ? ( + <span>{post.mediaCount} media (not archived)</span> + ) : null} + </footer> + </article> + ); +} + +function Badge({ children }: { children: React.ReactNode }) { + return ( + <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide"> + {children} + </span> + ); +} + +// What a captured file is, by its extension. +export function captureMediaKind(name: string): "image" | "video" | "other" { + const ext = name.toLowerCase().split(".").pop() ?? ""; + if (["jpg", "jpeg", "png", "gif", "webp", "avif"].includes(ext)) return "image"; + if (["mp4", "webm", "mov", "m4v"].includes(ext)) return "video"; + return "other"; +} + +// The captured screenshot and media of one post, and a line for its article. +// Nothing when the capture holds none of them (a deleted post's record, say). +export function PostCapturePanel({ capture }: { capture: PostCaptureView }) { + const { article } = capture; + if (!capture.shot && capture.media.length === 0 && !article) return null; + return ( + <section data-post-capture="" className="mt-3 flex flex-col gap-2"> + <h3 className="text-xs uppercase tracking-wide text-muted-foreground"> + Captured {formatWhen(capture.capturedAt)} + {capture.sensitive ? " · behind a sensitive-media cover" : ""} + </h3> + {article && ( + <p data-post-capture-article="" className="text-xs text-muted-foreground"> + Article: {article.title ?? "untitled"} + {article.state !== "captured" ? ` (${article.state})` : ""} + {article.md && ( + <> + {" · "} + <a href={article.md.src} className="text-primary underline"> + article.md + </a> + </> + )} + </p> + )} + {capture.shot && ( + <img + src={capture.shot.src} + alt="Screenshot of the post as captured" + data-post-capture-shot="" + className="max-w-full rounded-md border border-border" + /> + )} + {capture.media.length > 0 && ( + <ul className="flex flex-col gap-2"> + {capture.media.map((m) => { + const kind = captureMediaKind(m.name); + return ( + <li key={m.src} data-post-capture-media={kind}> + {kind === "image" ? ( + <img src={m.src} alt={m.name} className="max-w-full rounded-md" /> + ) : kind === "video" ? ( + <video src={m.src} controls preload="metadata" className="max-w-full rounded-md" /> + ) : ( + <a href={m.src} className="text-xs text-primary underline break-all"> + {m.name} + </a> + )} + </li> + ); + })} + </ul> + )} + </section> + ); +} diff --git a/common/components/PostModal.tsx b/common/components/PostModal.tsx @@ -8,51 +8,22 @@ // that applies to a post. This renders the post, its thread context and its // outbound links, and nothing else. -import { useEffect, useMemo } from "react"; +import { useEffect } from "react"; import { useQuery } from "@tanstack/react-query"; import { XIcon } from "lucide-react"; import { Button } from "./ui/button"; import { useUrlParams, writeUrlParams } from "./urlState"; import { fetchPost, fetchThread } from "./postsCache"; import { postPlatformLabel, type Post } from "../lib/posts"; -import { pageCaptureView } from "../lib/waybackPages/view"; -import { PageCaptureFacts } from "./PageCaptureFacts"; +import { PostBody, type PostCaptureView } from "./PostBody"; -function formatWhen(iso: string): string { - const ms = Date.parse(iso); - if (!Number.isFinite(ms)) return iso; - const d = new Date(ms); - return d.toLocaleString(undefined, { - year: "numeric", - month: "short", - day: "numeric", - hour: "2-digit", - minute: "2-digit", - }); -} +// The post itself is drawn by PostBody.tsx; its exports are this module's too. +export { captureMediaKind, PostBody, PostCapturePanel, type PostCaptureView } from "./PostBody"; function platformLabel(platform: Post["platform"]): string { return postPlatformLabel(platform); } -// A post's capture (a screenshot and its attached media, taken by the -// editor's capture-posts job), as the page that renders this modal serves it. -// EDITOR-ONLY: the files live beside the channel (`posts-media/<id>/`) and are -// never published, so the export never passes `loadCapture` and never shows -// any of this. -export type PostCaptureView = { - capturedAt: string; - // The capture's state ("captured", "deleted", …), as recorded. - state: string; - // The post sat behind a sensitive-media cover when it was shot. - sensitive?: boolean; - shot?: { src: string }; - media: { src: string; name: string }[]; - // The X Article the post links to, when the capture opened it: its title, - // how that went, and its markdown when saved. - article?: { state: string; title?: string; md?: { src: string } }; -}; - export type PostModalProps = { // Where the editor reads a post's capture from. Absent (the export): no // capture is looked for or shown. @@ -157,226 +128,3 @@ export default function PostModal({ loadCapture }: PostModalProps = {}) { ); } -function PostBody({ - post, - primary = false, - compact = false, - capture, -}: { - post: Post; - primary?: boolean; - compact?: boolean; - capture?: PostCaptureView | null; -}) { - const links = useMemo(() => post.links ?? [], [post.links]); - const capturedMedia = capture?.media.length ?? 0; - // A page record (a Wayback capture, release 37 S4): what the capture is, - // and the original named as possibly gone beside the Wayback copy. - const page = useMemo(() => pageCaptureView(post), [post]); - return ( - <article - data-post-id={post.id} - className={ - "rounded-md " + - (primary && compact ? "bg-warning-soft " : "") + - (compact ? "px-2 py-1.5" : "") - } - > - <header className="flex flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground"> - <span className="font-medium text-foreground"> - {post.authorName || post.author} - </span> - {post.authorName && <span>@{post.author}</span>} - <span>·</span> - <time dateTime={post.createdAt}>{formatWhen(post.createdAt)}</time> - {post.isRepost && <Badge>repost</Badge>} - {/* Every forum post after the first answers the thread; the badge - would be on all of them. Its place in the thread says more. */} - {post.isReply && !post.forum && <Badge>reply</Badge>} - {post.forum?.position && <Badge>#{post.forum.position}</Badge>} - {post.forum?.editedAt && ( - <span title={`Last edited ${formatWhen(post.forum.editedAt)}`}> - <Badge>edited</Badge> - </span> - )} - {/* The whole point of archiving: this post no longer exists upstream. */} - {post.isDeleted && ( - <span - title={ - post.availabilityCheckedAt - ? `Confirmed removed from the source (checked ${new Date(post.availabilityCheckedAt).toLocaleString()})` - : "Removed from the source platform" - } - className="rounded bg-rose-100 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-rose-800 dark:bg-rose-900/40 dark:text-rose-200" - > - deleted - </span> - )} - </header> - - <p className={"whitespace-pre-wrap " + (compact ? "text-sm" : "text-base mt-2")}> - {post.text} - </p> - - {capture && <PostCapturePanel capture={capture} />} - - {page && !compact && <PageCaptureFacts view={page} links={false} className="mt-2" />} - - {post.forum?.threadTitle && !compact && ( - <p className="mt-1 text-xs text-muted-foreground"> - In thread: {post.forum.threadTitle} - {post.forum.page ? ` · page ${post.forum.page}` : ""} - </p> - )} - - {post.media && post.media.length > 0 && !capturedMedia && ( - <ul data-post-media="" className="mt-2 flex flex-col gap-1"> - {post.media.map((m) => ( - <li key={`${m.kind}:${m.url}`} className="text-xs text-muted-foreground"> - {m.kind} - {m.provider ? ` (${m.provider})` : ""}:{" "} - {/^https?:\/\//.test(m.url) ? ( - <a - href={m.url} - target="_blank" - rel="noopener noreferrer" - className="text-primary underline break-all" - > - {m.name || m.url} - </a> - ) : ( - <span className="break-all">{m.name || m.url}</span> - )} - </li> - ))} - </ul> - )} - - {links.length > 0 && ( - <ul className="mt-2 flex flex-col gap-1"> - {links.map((href) => ( - <li key={href}> - <a - href={href} - target="_blank" - rel="noopener noreferrer" - className="text-xs text-primary underline break-all" - > - {href} - </a> - </li> - ))} - </ul> - )} - - <footer className="mt-2 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground"> - {page ? ( - <> - <a href={page.links.original.url} target="_blank" rel="noopener noreferrer" className="underline"> - {post.isDeleted ? "Original (deleted)" : page.links.original.label} - </a> - <a href={page.links.copy.url} target="_blank" rel="noopener noreferrer" className="underline"> - {page.links.copy.label} - </a> - </> - ) : ( - <a - href={post.url} - target="_blank" - rel="noopener noreferrer" - className="underline" - > - {post.isDeleted ? "Original (deleted)" : "Open original"} - </a> - )} - {post.engagement?.likes != null && ( - <span>{post.engagement.likes} likes</span> - )} - {post.engagement?.reposts != null && ( - <span>{post.engagement.reposts} reposts</span> - )} - {post.engagement?.replies != null && ( - <span>{post.engagement.replies} replies</span> - )} - {capturedMedia > 0 ? ( - <span>{capturedMedia} media (captured)</span> - ) : post.mediaCount ? ( - <span>{post.mediaCount} media (not archived)</span> - ) : null} - </footer> - </article> - ); -} - -function Badge({ children }: { children: React.ReactNode }) { - return ( - <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide"> - {children} - </span> - ); -} - -// What a captured file is, by its extension. -export function captureMediaKind(name: string): "image" | "video" | "other" { - const ext = name.toLowerCase().split(".").pop() ?? ""; - if (["jpg", "jpeg", "png", "gif", "webp", "avif"].includes(ext)) return "image"; - if (["mp4", "webm", "mov", "m4v"].includes(ext)) return "video"; - return "other"; -} - -// The captured screenshot and media of one post, and a line for its article. -// Nothing when the capture holds none of them (a deleted post's record, say). -export function PostCapturePanel({ capture }: { capture: PostCaptureView }) { - const { article } = capture; - if (!capture.shot && capture.media.length === 0 && !article) return null; - return ( - <section data-post-capture="" className="mt-3 flex flex-col gap-2"> - <h3 className="text-xs uppercase tracking-wide text-muted-foreground"> - Captured {formatWhen(capture.capturedAt)} - {capture.sensitive ? " · behind a sensitive-media cover" : ""} - </h3> - {article && ( - <p data-post-capture-article="" className="text-xs text-muted-foreground"> - Article: {article.title ?? "untitled"} - {article.state !== "captured" ? ` (${article.state})` : ""} - {article.md && ( - <> - {" · "} - <a href={article.md.src} className="text-primary underline"> - article.md - </a> - </> - )} - </p> - )} - {capture.shot && ( - <img - src={capture.shot.src} - alt="Screenshot of the post as captured" - data-post-capture-shot="" - className="max-w-full rounded-md border border-border" - /> - )} - {capture.media.length > 0 && ( - <ul className="flex flex-col gap-2"> - {capture.media.map((m) => { - const kind = captureMediaKind(m.name); - return ( - <li key={m.src} data-post-capture-media={kind}> - {kind === "image" ? ( - <img src={m.src} alt={m.name} className="max-w-full rounded-md" /> - ) : kind === "video" ? ( - <video src={m.src} controls preload="metadata" className="max-w-full rounded-md" /> - ) : ( - <a href={m.src} className="text-xs text-primary underline break-all"> - {m.name} - </a> - )} - </li> - ); - })} - </ul> - )} - </section> - ); -} diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts @@ -467,10 +467,10 @@ test("S1: three reads in a row that do not end \"read\" pause the watch until a // A probe is nobody's failure. assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "probe" }), null); const third = await fail("rate-limit"); - assert.match(third ?? "", /^The last 3 reads of "Kettles" failed \(the last: rate-limit — X answered 429 \(rate limit\)\.\): its watch is paused until someone switches it on again/); + assert.match(third ?? "", /^The last 3 reads of "Kettles" failed \(the last: rate-limit — X answered 429 \(rate limit\)\.\): its watch is paused until the operator switches it on again/); let w = (await readXTrendingWatches(dir)).kettles; assert.deepEqual([w.on, w.paused?.reason, w.failures], [true, "failing", 3]); - assert.match(describeXTrendingWatch(w, T0), /PAUSED since .* UTC, until someone switches it on again: The last 3 reads/); + assert.match(describeXTrendingWatch(w, T0), /PAUSED since .* UTC, until the operator switches it on again: The last 3 reads/); // No scan resumes it — not with X fine, not an interval later — and none ticks it. for (const at of [T0 + MIN, T0 + 31 * MIN, T0 + 5 * 60 * MIN]) { h.state.now = at; diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -412,7 +412,7 @@ export async function noteXTrendingWatchRead( if (w.failures >= X_TRENDING_WATCH_MAX_FAILURES && w.paused?.reason !== "failing") { sentence = `The last ${w.failures} reads of "${topic.title}" failed (the last: ${read.outcome}` + - `${read.sentence ? ` — ${read.sentence}` : ""}): its watch is paused until someone switches it on again ` + + `${read.sentence ? ` — ${read.sentence}` : ""}): its watch is paused until the operator switches it on again ` + `(Watch on its page, or watch-trending {"topic": "${topic.id}", "on": true}).`; w.paused = { reason: "failing", since: at, sentence }; } diff --git a/common/lib/xTrending/mediaStore.ts b/common/lib/xTrending/mediaStore.ts @@ -315,8 +315,7 @@ export type RemovedCapture = { // and the directory; and each blob it carried, ONLY when no other post carries // it and nothing else links to it. Media another post still uses is never // deleted: its bytes stay under that post's name and in the store. -// (No door calls this in this slice; the purge button and its ops twin are a -// later one's.) +// (Its door is the purge of dropped posts: lib/xTrending/purge.ts.) // // REFUSED WHILE A CAPTURE OF THE LIBRARY IS QUEUED OR RUNNING (`captureInFlight`, // which the caller answers from its job registry — required, so no door can @@ -329,28 +328,78 @@ export async function removeXTrendingPostCapture( postId: string, o: { captureInFlight: () => boolean | Promise<boolean> }, ): Promise<RemovedCapture> { - if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); - if (await o.captureInFlight()) throw new Error(CAPTURE_IN_FLIGHT); - const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId); + const { files, blobsFreed, bytesFreed, blobsKept } = await removeXTrendingPostCaptures(channelRoot, [postId], o); + return { files, blobsFreed, bytesFreed, blobsKept }; +} + +// SEVERAL POSTS' CAPTURES, REMOVED TOGETHER (lane posts-library: the purge of +// dropped posts) — or, with `dryRun`, COUNTED AND NOT TOUCHED, by the same +// walk, so what a dry run says is what the removal does. Taken together +// because a blob two of these posts share, and no other, goes with them: one +// post at a time would call it kept twice. +// +// posts of the ids, those with a capture directory +// ownBytes the bytes of their files that are no blob's link (a shot, the +// record): freed with the directory +// bytesFreed the blobs no other post carries and nothing else links to +export type RemovedCaptures = RemovedCapture & { posts: number; ownBytes: number }; + +export async function removeXTrendingPostCaptures( + channelRoot: string, + postIds: ReadonlyArray<string>, + o: { + captureInFlight: () => boolean | Promise<boolean>; + dryRun?: boolean; + // Asked INSIDE the index's lock, immediately before the first file goes + // (never on a dry run): a sentence refuses the removal, and nothing is + // touched. The purge re-reads the judgements here, so a post kept between + // the count and the removal is not removed. + guard?: () => Promise<string | null>; + }, +): Promise<RemovedCaptures> { + for (const postId of postIds) if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); + const dry = o.dryRun === true; + if (!dry && (await o.captureInFlight())) throw new Error(CAPTURE_IN_FLIGHT); + const ids = new Set(postIds); return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { - const out: RemovedCapture = { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }; + const out: RemovedCaptures = { posts: 0, files: 0, ownBytes: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }; // The index FIRST: one that cannot be read stops this before a file goes. const index = await readXTrendingMediaIndex(channelRoot); - const names = await readdir(dir).catch(() => [] as string[]); - for (const name of names) { - const st = await lstat(path.join(dir, name)).catch(() => null); - if (!st) continue; - if (st.isDirectory()) await rm(path.join(dir, name), { recursive: true, force: true }); - else await removeMediaFile(dir, name); - out.files++; + if (!dry && o.guard) { + const refused = await o.guard(); + if (refused) throw new Error(refused); + } + // How many names of these captures link to each inode (a dry run takes + // them off a blob's link count, as the removal would). + const links = new Map<number, number>(); + for (const postId of ids) { + const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId); + const names = await readdir(dir).catch(() => null); + if (names === null) continue; + out.posts++; + for (const name of names) { + const st = await lstat(path.join(dir, name)).catch(() => null); + if (!st) continue; + if (st.isDirectory()) { + if (!dry) await rm(path.join(dir, name), { recursive: true, force: true }); + } else { + links.set(st.ino, (links.get(st.ino) ?? 0) + 1); + if (st.nlink <= 1) out.ownBytes += st.size; + if (!dry) await removeMediaFile(dir, name); + } + out.files++; + } + if (!dry) await rmdir(dir).catch(() => {}); } - await rmdir(dir).catch(() => {}); let changed = false; for (const [sha, entry] of Object.entries(index.blobs)) { - if (!entry.posts[postId]) continue; - delete entry.posts[postId]; - changed = true; - if (Object.keys(entry.posts).length > 0) { + if (!Object.keys(entry.posts).some((p) => ids.has(p))) continue; + const others = Object.keys(entry.posts).filter((p) => !ids.has(p)).length; + if (!dry) { + for (const p of Object.keys(entry.posts)) if (ids.has(p)) delete entry.posts[p]; + changed = true; + } + if (others > 0) { out.blobsKept++; continue; } @@ -358,16 +407,19 @@ export async function removeXTrendingPostCapture( const st = await stat(blob).catch(() => null); // A link the index does not know of (a name copied by hand, an index // that lost a post): the bytes are still somebody's, so the blob stays. - if (st && st.nlink > 1) { + const left = st ? (dry ? st.nlink - (links.get(st.ino) ?? 0) : st.nlink) : 0; + if (st && left > 1) { out.blobsKept++; continue; } if (st) { - await rm(blob, { force: true }); - await rmdir(path.dirname(blob)).catch(() => {}); + if (!dry) { + await rm(blob, { force: true }); + await rmdir(path.dirname(blob)).catch(() => {}); + } out.bytesFreed += st.size; } - delete index.blobs[sha]; + if (!dry) delete index.blobs[sha]; out.blobsFreed++; } if (changed) await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); diff --git a/common/lib/xTrending/purge.test.ts b/common/lib/xTrending/purge.test.ts @@ -0,0 +1,241 @@ +// The purge of dropped posts' captures (lane posts-library): dropped posts +// only, two steps held together by a digest, shared media left, judgements +// kept, refused while a capture is in flight. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xTrending/purge.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Post } from "../posts"; +import { judgeXTrending } from "./judgements"; +import { adoptXTrendingMedia, CAPTURE_IN_FLIGHT, readXTrendingMediaIndex, removeXTrendingPostCaptures } from "./mediaStore"; +import { purgeSentence, purgeXTrendingDropped, xTrendingPurgeConfirm } from "./purge"; +import { recordXTrendingRead, writeXTrendingPosts } from "./store"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-purge-")); +after(() => rmSync(TMP, { recursive: true, force: true })); +const IDLE = () => false; +const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }; +const REF_2 = { trendId: "1900000000000000002", url: "https://x.com/i/trending/1900000000000000002" }; + +function post(id: string, extra: Partial<Post> = {}): Post { + return { id, slug: `lib/${id}`, channelSlug: "lib", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: `post ${id}`, url: `https://x.com/teapot_news/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra }; +} +const cap = (dir: string, id: string) => path.join(dir, "trending", "posts-media", id); + +async function put(dir: string, id: string, files: Record<string, string>) { + mkdirSync(cap(dir, id), { recursive: true }); + for (const [name, bytes] of Object.entries(files)) { + writeFileSync(path.join(cap(dir, id), name), bytes); + if (/_\d+\.(jpg|mp4)$/.test(name)) await adoptXTrendingMedia(dir, { postId: id, name }); + } +} + +// 701 dropped (own), 702+703 a dropped THREAD, 704 kept, 705 later, 706 +// undecided, 707 dropped with no capture, 708 dropped in another topic. +async function library(name: string): Promise<string> { + const dir = path.join(TMP, name); + mkdirSync(dir, { recursive: true }); + await writeXTrendingPosts(dir, [post("701"), post("702"), post("703", { isReply: true, threadId: "702", replyTo: { platform: "twitter", id: "702" } }), post("704"), post("705"), post("706"), post("707"), post("708")]); + await recordXTrendingRead(dir, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["701", "702", "703", "704", "705", "706", "707"], added: 7, threads: { "703": "702" } }); + await recordXTrendingRead(dir, { readId: "tr-01JB0000000000000000000000", at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["708"], added: 1 }); + await put(dir, "701", { "shot.png": "SHOT701", "701_1.jpg": "ONLY-701", "701_2.jpg": "SHARED-DROPPED", "capture.json": "{}" }); + await put(dir, "702", { "702_1.jpg": "SHARED-DROPPED" }); + await put(dir, "703", { "703_1.jpg": "SHARED-WITH-KEPT" }); + await put(dir, "704", { "704_1.jpg": "SHARED-WITH-KEPT", "shot.png": "SHOT704" }); + await put(dir, "705", { "705_1.jpg": "LATER" }); + await put(dir, "706", { "706_1.jpg": "UNDECIDED" }); + await put(dir, "708", { "708_1.jpg": "OTHER-TOPIC" }); + await judgeXTrending(dir, { + by: "operator", + set: [{ id: "701", state: "drop" }, { thread: "702", state: "drop" }, { id: "704", state: "keep" }, { id: "705", state: "later" }, { id: "707", state: "drop" }, { id: "708", state: "drop" }], + }); + return dir; +} + +test("a dry run counts what would go and touches nothing; a blob two dropped posts share goes with them, one a kept post carries stays", async () => { + const dir = await library("dry"); + const before = readFileSync(path.join(dir, "trending", "media-index.json"), "utf8"); + const out = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: true, captureInFlight: IDLE }); + assert.ok(out.ok); + const r = out.result; + // 707 is dropped and has no capture; 708 is another topic's. + assert.deepEqual(r.ids, ["701", "702", "703"]); + assert.equal(r.posts, 3); + assert.equal(r.files, 6); + // ONLY-701 and SHARED-DROPPED are freed; SHARED-WITH-KEPT is 704's too. + assert.equal(r.blobsFreed, 2); + assert.equal(r.blobsKept, 1); + assert.equal(r.bytes, "ONLY-701".length + "SHARED-DROPPED".length + "SHOT701".length + "{}".length); + assert.equal(r.confirm, xTrendingPurgeConfirm("lib", ["701", "702", "703"])); + assert.equal(r.sentence, "Would remove the captures of 3 dropped posts: 6 files, 31 B. 1 media file another post still uses is left. The judgements stay. Keeping one of them again captures it again."); + assert.deepEqual(r.gone, []); + assert.equal(r.agentDropped, 0); + for (const id of ["701", "702", "703"]) assert.equal(existsSync(cap(dir, id)), true); + assert.equal(readFileSync(path.join(dir, "trending", "media-index.json"), "utf8"), before); +}); + +test("the removal does what the dry run said, needs its digest, and leaves the judgements and everyone else's media", async () => { + const dir = await library("real"); + const dry = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + // No digest, a wrong one, another library's: refused, nothing removed. + for (const confirm of [undefined, "0000000000000000", xTrendingPurgeConfirm("other", dry.result.ids)]) { + const no = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: false, ...(confirm ? { confirm } : {}), captureInFlight: IDLE }); + assert.equal(no.ok, false); + assert.match(no.ok ? "" : no.error, /have changed since the dry run \(3 now\): nothing was removed/); + } + assert.equal(existsSync(cap(dir, "701")), true); + const judgements = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); + const done = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: false, confirm: dry.result.confirm, captureInFlight: IDLE }); + assert.ok(done.ok); + const { sentence: _a, dryRun: _b, ...said } = dry.result; + const { sentence, dryRun: _c, ...did } = done.result; + assert.deepEqual(did, said); + assert.match(sentence, /^Removed the captures of 3 dropped posts/); + for (const id of ["701", "702", "703"]) assert.equal(existsSync(cap(dir, id)), false); + // The kept post, the later one, the undecided one and the other topic's are whole. + assert.equal(readFileSync(path.join(cap(dir, "704"), "704_1.jpg"), "utf8"), "SHARED-WITH-KEPT"); + for (const id of ["705", "706", "708"]) assert.equal(existsSync(cap(dir, id)), true); + const index = await readXTrendingMediaIndex(dir); + assert.deepEqual(Object.values(index.blobs).map((b) => Object.keys(b.posts).join()).sort(), ["704", "705", "706", "708"]); + assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgements); + // Again: nothing left to remove. + const again = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: true, captureInFlight: IDLE }); + assert.ok(again.ok); + assert.equal(again.result.posts, 0); + assert.equal(again.result.sentence, "No post the operator dropped has a capture: nothing to remove."); +}); + +test("a set that changed between the two steps is refused", async () => { + const dir = await library("changed"); + const dry = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.ids, ["701", "702", "703", "708"]); + await judgeXTrending(dir, { by: "operator", set: [{ id: "701", state: "keep" }] }); + const no = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: false, confirm: dry.result.confirm, captureInFlight: IDLE }); + assert.equal(no.ok, false); + assert.equal(existsSync(cap(dir, "702")), true); +}); + +test("ids: only dropped ones are taken, the rest named; never a kept, later or undecided post", async () => { + const dir = await library("ids"); + const dry = await purgeXTrendingDropped(dir, { slug: "lib", ids: ["701", "704", "705", "706", "999"], dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.ids, ["701"]); + assert.deepEqual(dry.result.skipped.map((s) => s.id), ["704", "705", "706", "999"]); + const bad = await purgeXTrendingDropped(dir, { slug: "lib", ids: ["../x"], dryRun: true, captureInFlight: IDLE }); + assert.equal(bad.ok, false); +}); + +test("while a capture is queued or running: a dry run says so, the removal is refused", async () => { + const dir = await library("in-flight"); + const dry = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: () => true }); + assert.ok(dry.ok); + assert.equal(dry.result.captureInFlight, true); + assert.match(dry.result.sentence, /the removal waits for it/); + const no = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: false, confirm: dry.result.confirm, captureInFlight: () => true }); + assert.deepEqual(no, { ok: false, error: CAPTURE_IN_FLIGHT }); + assert.equal(existsSync(cap(dir, "701")), true); +}); + +test("removeXTrendingPostCaptures: a dry run of the walk equals the walk", async () => { + const dir = await library("walk"); + const dry = await removeXTrendingPostCaptures(dir, ["701", "702"], { captureInFlight: IDLE, dryRun: true }); + assert.deepEqual(await removeXTrendingPostCaptures(dir, ["701", "702"], { captureInFlight: IDLE }), dry); + assert.deepEqual(dry, { posts: 2, files: 5, ownBytes: 9, blobsFreed: 2, bytesFreed: 22, blobsKept: 0 }); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +test("S1: only the OPERATOR's drops are purged: an agent's drop (a post's own, or through its thread) is counted and left alone", async () => { + const dir = path.join(TMP, "agent-drops"); + mkdirSync(dir, { recursive: true }); + await writeXTrendingPosts(dir, [post("801"), post("802"), post("803"), post("804", { isReply: true, threadId: "803", replyTo: { platform: "twitter", id: "803" } }), post("805")]); + await recordXTrendingRead(dir, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["801", "802", "803", "804", "805"], added: 5, threads: { "804": "803" } }); + for (const id of ["801", "802", "803", "804", "805"]) await put(dir, id, { "shot.png": `SHOT${id}` }); + await judgeXTrending(dir, { by: "operator", set: [{ id: "801", state: "drop" }] }); + // 802: the agent's own drop. 803+804: a thread the agent dropped. 805: dropped by the agent, then by the operator's hand. + await judgeXTrending(dir, { by: "agent", set: [{ id: "802", state: "drop" }, { thread: "803", state: "drop" }, { id: "805", state: "drop" }] }); + await judgeXTrending(dir, { by: "operator", set: [{ id: "805", state: "drop" }] }); + + const dry = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.ids, ["801", "805"]); + assert.equal(dry.result.agentDropped, 3); + assert.match(dry.result.sentence, / 3 posts an agent dropped are left alone: a purge takes the operator's drops only\.$/); + // Named by id, an agent's drop is skipped with that reason, never removed. + const named = await purgeXTrendingDropped(dir, { slug: "lib", ids: ["801", "802", "804"], dryRun: true, captureInFlight: IDLE }); + assert.ok(named.ok); + assert.deepEqual(named.result.ids, ["801"]); + assert.deepEqual(named.result.skipped, [ + { id: "802", reason: "an agent dropped it: a purge takes the operator's drops only" }, + { id: "804", reason: "an agent dropped it: a purge takes the operator's drops only" }, + ]); + assert.equal(named.result.agentDropped, 2); + + const done = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: false, confirm: dry.result.confirm, captureInFlight: IDLE }); + assert.ok(done.ok); + for (const id of ["801", "805"]) assert.equal(existsSync(cap(dir, id)), false); + for (const id of ["802", "803", "804"]) assert.equal(existsSync(cap(dir, id)), true, `${id}: an agent's drop is left`); + assert.match(done.result.sentence, /^Removed the captures of 2 dropped posts: .* 3 posts an agent dropped are left alone/); + // Only agents' drops left: nothing to remove, and it says why. + const none = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: IDLE }); + assert.ok(none.ok); + assert.equal(none.result.sentence, "No post the operator dropped has a capture: nothing to remove. 3 posts an agent dropped are left alone: a purge takes the operator's drops only."); +}); + +test("S1: posts gone from the page are named, and the sentence is true of them: the only copy, which keeping again may not bring back", async () => { + const dir = path.join(TMP, "gone"); + mkdirSync(dir, { recursive: true }); + await writeXTrendingPosts(dir, [post("811"), post("812"), post("813")]); + await recordXTrendingRead(dir, { readId: "tr-01JA0000000000000000000000", at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["811", "812", "813"], added: 3, complete: true }); + // The page's end was reached at 11:00 and showed only 812: the others are gone from it. + await recordXTrendingRead(dir, { readId: "tr-01JB0000000000000000000000", at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["812"], added: 0, complete: true }); + for (const id of ["811", "812", "813"]) await put(dir, id, { "shot.png": `SHOT${id}` }); + await judgeXTrending(dir, { by: "operator", set: [{ id: "811", state: "drop" }, { id: "812", state: "drop" }] }); + const two = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: IDLE }); + assert.ok(two.ok); + assert.deepEqual(two.result.gone, [{ id: "811", at: "2026-11-17T11:00:00.000Z" }]); + assert.match(two.result.sentence, / The judgements stay\. 1 of them is gone from the page: this is the only copy: X no longer showed this post at 2026-11-17 11:00 UTC; removing it cannot be undone\. Keeping the other one again captures it again\.$/); + // Only the gone one: nothing is promised about keeping it again. + const one = await purgeXTrendingDropped(dir, { slug: "lib", ids: ["811"], dryRun: true, captureInFlight: IDLE }); + assert.ok(one.ok); + assert.match(one.result.sentence, / It is gone from the page: this is the only copy: X no longer showed this post at 2026-11-17 11:00 UTC; removing it cannot be undone\.$/); + assert.doesNotMatch(one.result.sentence, /captures it again/); + // Several gone. + await judgeXTrending(dir, { by: "operator", set: [{ id: "813", state: "drop" }] }); + const three = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: true, captureInFlight: IDLE }); + assert.ok(three.ok); + assert.match(three.result.sentence, / 2 of them are gone from the page: these are the only copies: X no longer showed these posts \(the first at 2026-11-17 11:00 UTC\); removing them cannot be undone\. Keeping the other one again captures it again\.$/); + const done = await purgeXTrendingDropped(dir, { slug: "lib", dryRun: false, confirm: three.result.confirm, captureInFlight: IDLE }); + assert.ok(done.ok); + assert.match(done.result.sentence, / The judgements stay\. 2 of them were gone from the page: those copies cannot be had again\.$/); + assert.equal(purgeSentence({ dryRun: true, posts: 2, files: 2, bytes: 10, blobsKept: 0, gone: [], agentDropped: 1, captureInFlight: true }), "Would remove the captures of 2 dropped posts: 2 files, 10 B. The judgements stay. Keeping one of them again captures it again. 1 post an agent dropped is left alone: a purge takes the operator's drops only. A capture of this library is queued or running: the removal waits for it."); +}); + +test("S3: the set is read again inside the media index's lock: a post kept after the digest was checked is not removed, and nothing else is either", async () => { + const dir = await library("toctou"); + const dry = await purgeXTrendingDropped(dir, { slug: "lib", topic: "kettles", dryRun: true, captureInFlight: IDLE }); + assert.ok(dry.ok); + assert.deepEqual(dry.result.ids, ["701", "702", "703"]); + const index = readFileSync(path.join(dir, "trending", "media-index.json"), "utf8"); + // captureInFlight is asked AFTER the purge checked the digest and before the lock is taken: a keep lands there. + const no = await purgeXTrendingDropped(dir, { + slug: "lib", + topic: "kettles", + dryRun: false, + confirm: dry.result.confirm, + captureInFlight: async () => { + await judgeXTrending(dir, { by: "operator", set: [{ id: "701", state: "keep" }] }); + return false; + }, + }); + assert.equal(no.ok, false); + assert.match(no.ok ? "" : no.error, /have changed since the dry run \(2 now\): nothing was removed/); + for (const id of ["701", "702", "703"]) assert.equal(existsSync(cap(dir, id)), true, `${id} is whole`); + assert.equal(readFileSync(path.join(dir, "trending", "media-index.json"), "utf8"), index); +}); diff --git a/common/lib/xTrending/purge.ts b/common/lib/xTrending/purge.ts @@ -0,0 +1,183 @@ +// THE PURGE OF DROPPED POSTS' CAPTURES (lane posts-library): the one door to +// removeXTrendingPostCaptures (lib/xTrending/mediaStore.ts). +// +// WHAT IS TAKEN: the captures (trending/posts-media/<id>/) of posts whose +// judgement IN FORCE is drop BY THE OPERATOR — their own entry, or their +// thread's — in one topic or the whole library, or of the ids named among +// them. AN AGENT'S DROP IS A SUGGESTION AND IS NEVER PURGED: those posts are +// counted (`agentDropped`) and left alone. Never a post marked later, kept or +// undecided. A blob another post still carries is left; the judgements, the +// posts and the reads stay; what a media address was found over the cap is +// not forgotten. +// +// A POST GONE FROM THE PAGE IS SAID SO. For a post a trending page no longer +// shows, the capture is the only copy the library has, and keeping the post +// again may capture nothing: the answer names those posts (`gone`) and its +// sentence says the removal cannot be undone. "Keeping it again captures it +// again" is said only of the others. +// +// TWO STEPS. A dry run counts what would go and answers `confirm`, a digest of +// the library's slug and the exact ids. The removal must carry that digest: if +// the set has changed since (a post dropped or kept, a capture added), it is +// refused and nothing is removed, so what goes is what was shown. THE SET IS +// READ AGAIN INSIDE THE MEDIA INDEX'S LOCK, immediately before the first file +// goes: a judgement written between the check and the removal refuses it too. +// +// Refused while a capture of the library is queued or running (the caller +// answers that from its job registry). SERVER-ONLY (node:fs). + +import { createHash } from "node:crypto"; +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { removeXTrendingPostCaptures } from "./mediaStore"; +import { listXTrending, readXTrendingMembership, xTrendingPostsMediaDir } from "./store"; + +export const X_TRENDING_PURGE_MAX_IDS = 5000; + +export type XTrendingPurgeAsk = { + slug: string; + topic?: string; + ids?: ReadonlyArray<string>; + dryRun: boolean; + confirm?: string; + captureInFlight: () => boolean | Promise<boolean>; +}; + +export type XTrendingPurgeResult = { + dryRun: boolean; + // The posts the operator dropped that have a capture: what is (or would be) removed. + posts: number; + ids: string[]; + files: number; + // Everything freed: the blobs no other post carries, and the captures' own + // files (shots, records). + bytes: number; + blobsFreed: number; + // Blobs another post still carries: left alone. + blobsKept: number; + // Of `ids`, the posts gone from the page, with when a page stopped showing + // each: their capture is the only copy. + gone: Array<{ id: string; at: string }>; + // Posts of the scope an AGENT dropped that have a capture: never removed. + agentDropped: number; + // Ids named that are not posts the operator dropped, in the scope. + skipped: Array<{ id: string; reason: string }>; + confirm: string; + // A dry run only: a capture of the library is queued or running, so the + // removal would be refused now. + captureInFlight?: boolean; + sentence: string; +}; + +export function xTrendingPurgeConfirm(slug: string, ids: ReadonlyArray<string>): string { + return createHash("sha256").update(JSON.stringify([slug, [...ids].sort()])).digest("hex").slice(0, 16); +} + +export function formatPurgeBytes(n: number): string { + if (n < 1024) return `${n} B`; + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; + if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`; + return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +export const PURGE_SET_CHANGED = (now: number) => + `The dropped posts with a capture have changed since the dry run (${now} now): nothing was removed. Run the dry run again and confirm what it shows.`; + +const when = (iso: string) => { + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? iso : `${d.toISOString().slice(0, 10)} ${d.toISOString().slice(11, 16)} UTC`; +}; +const n = (k: number, one: string, many = `${one}s`) => `${k} ${k === 1 ? one : many}`; + +// What the answer says, in one place: the page, `pnpm ops` and `umtool +// library` print it as it is. +export function purgeSentence(r: Pick<XTrendingPurgeResult, "dryRun" | "posts" | "files" | "bytes" | "blobsKept" | "gone" | "agentDropped" | "captureInFlight">): string { + const agent = r.agentDropped ? ` ${n(r.agentDropped, "post")} an agent dropped ${r.agentDropped === 1 ? "is" : "are"} left alone: a purge takes the operator's drops only.` : ""; + if (r.posts === 0) return `No post the operator dropped has a capture: nothing to remove.${agent}`; + const what = `the capture${r.posts === 1 ? "" : "s"} of ${n(r.posts, "dropped post")}: ${n(r.files, "file")}, ${formatPurgeBytes(r.bytes)}`; + const kept = r.blobsKept ? ` ${n(r.blobsKept, "media file")} another post still uses ${r.blobsKept === 1 ? "is" : "are"} left.` : ""; + const g = r.gone.length; + const others = r.posts - g; + if (!r.dryRun) { + const lost = g ? ` ${g === r.posts ? (g === 1 ? "It was" : "They were") : `${g} of them ${g === 1 ? "was" : "were"}`} gone from the page: ${g === 1 ? "that copy" : "those copies"} cannot be had again.` : ""; + return `Removed ${what}.${kept} The judgements stay.${lost}${agent}`; + } + const first = [...r.gone].sort((a, b) => (a.at < b.at ? -1 : 1))[0]; + const only = + g === 0 + ? "" + : g === 1 + ? ` ${r.posts === 1 ? "It is" : "1 of them is"} gone from the page: this is the only copy: X no longer showed this post at ${when(first.at)}; removing it cannot be undone.` + : ` ${g === r.posts ? "They are" : `${g} of them are`} gone from the page: these are the only copies: X no longer showed these posts (the first at ${when(first.at)}); removing them cannot be undone.`; + const again = others === 0 ? "" : g === 0 ? ` Keeping ${r.posts === 1 ? "it" : "one of them"} again captures it again.` : ` Keeping ${others === 1 ? "the other one" : `one of the other ${others}`} again captures it again.`; + const waits = r.captureInFlight ? " A capture of this library is queued or running: the removal waits for it." : ""; + return `Would remove ${what}.${kept} The judgements stay.${only}${again}${agent}${waits}`; +} + +export async function purgeXTrendingDropped(channelRoot: string, ask: XTrendingPurgeAsk): Promise<{ ok: true; result: XTrendingPurgeResult } | { ok: false; error: string }> { + if (ask.ids && ask.ids.length > X_TRENDING_PURGE_MAX_IDS) return { ok: false, error: `"ids" holds at most ${X_TRENDING_PURGE_MAX_IDS} post ids` }; + if (ask.ids && !ask.ids.every((id) => typeof id === "string" && /^\d+$/.test(id))) return { ok: false, error: `"ids" is a list of post ids` }; + const scope = ask.topic ? { topic: ask.topic } : {}; + const captured = async (id: string) => (await stat(path.join(xTrendingPostsMediaDir(channelRoot), id)).catch(() => null))?.isDirectory() === true; + + // THE SET, read from the judgements as they stand: asked for the count, and + // again inside the lock before a file goes. + const read = async () => { + const [mine, agents, membership] = await Promise.all([ + listXTrending(channelRoot, { ...scope, ids: true, filter: { state: "drop", by: "operator" } }), + listXTrending(channelRoot, { ...scope, ids: true, filter: { state: "drop", by: "agent" } }), + readXTrendingMembership(channelRoot), + ]); + const dropped = new Set(mine.ids ?? []); + const byAgent = new Set(agents.ids ?? []); + const skipped: XTrendingPurgeResult["skipped"] = []; + let wanted = [...dropped]; + if (ask.ids) { + wanted = []; + for (const id of new Set(ask.ids)) { + if (dropped.has(id)) wanted.push(id); + else skipped.push({ id, reason: byAgent.has(id) ? "an agent dropped it: a purge takes the operator's drops only" : ask.topic ? "not a post the operator dropped in that topic" : "not a post the operator dropped" }); + } + } + const ids: string[] = []; + for (const id of wanted) if (await captured(id)) ids.push(id); + ids.sort(); + let agentDropped = 0; + for (const id of byAgent) if ((!ask.ids || ask.ids.includes(id)) && (await captured(id))) agentDropped++; + const gone = ids.flatMap((id) => (membership[id]?.gone ? [{ id, at: membership[id].gone!.at }] : [])); + return { ids, skipped, agentDropped, gone }; + }; + + const set = await read(); + const confirm = xTrendingPurgeConfirm(ask.slug, set.ids); + if (!ask.dryRun && ask.confirm !== confirm) return { ok: false, error: PURGE_SET_CHANGED(set.ids.length) }; + const inFlight = ask.dryRun ? await ask.captureInFlight() : false; + let removed; + try { + removed = await removeXTrendingPostCaptures(channelRoot, set.ids, { + captureInFlight: ask.captureInFlight, + dryRun: ask.dryRun, + guard: async () => { + const now = await read(); + return xTrendingPurgeConfirm(ask.slug, now.ids) === confirm ? null : PURGE_SET_CHANGED(now.ids.length); + }, + }); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const result: Omit<XTrendingPurgeResult, "sentence"> = { + dryRun: ask.dryRun, + posts: set.ids.length, + ids: set.ids, + files: removed.files, + bytes: removed.bytesFreed + removed.ownBytes, + blobsFreed: removed.blobsFreed, + blobsKept: removed.blobsKept, + gone: set.gone, + agentDropped: set.agentDropped, + skipped: set.skipped, + confirm, + ...(ask.dryRun && inFlight ? { captureInFlight: true as const } : {}), + }; + return { ok: true, result: { ...result, sentence: purgeSentence(result) } }; +} diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -6,6 +6,7 @@ import path from "node:path"; import { xTrendingThreadKey, listXTrending, + summarizeXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, @@ -369,3 +370,146 @@ test("a thread's key ignores a threadId that only repeats the post's id, and doe assert.deepEqual(rows, { "902": "901", "903": "902" }); assert.equal((await readXTrendingMembership(dir))["903"].thread, "902"); }); + +// ── lane posts-library: what the judge view asks of the listing ───────────── + +async function judgeLibrary(name: string): Promise<string> { + const dir = root(name); + const reply: Post = { ...post("903", "saucer_fan", "A reply about spouts."), isReply: true, replyTo: { platform: "twitter", id: "901", author: "teapot_news" }, threadId: "901" }; + await writeXTrendingPosts(dir, [ + { ...post("901", "teapot_news", "The Kettle festival opens."), authorName: "Teapot News", mediaCount: 1, links: ["https://example.org/a"], engagement: { likes: 4 } }, + post("902", "saucer_fan", "Saucers are underrated."), + reply, + post("904", "Lid_Watch", "A lid fell off a kettle."), + post("905", "cup_other", "Other topic."), + ]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "902", "903"], added: 3, media: { "901": { count: 1, kinds: ["image"] } }, threads: { "903": "901" }, complete: true }); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "903", "904"], added: 1, complete: true }); + await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["905"], added: 1 }); + writeFileSync( + path.join(dir, "trending", "judgements.json"), + JSON.stringify({ + version: 1, + posts: { "902": { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" }, "904": { state: "later", by: "agent", at: "2026-11-17T12:30:00.000Z" } }, + threads: { "901": { state: "keep", note: "the opening", by: "operator", at: "2026-11-17T12:31:00.000Z" } }, + }), + ); + const cap = path.join(dir, "trending", "posts-media", "901"); + mkdirSync(cap, { recursive: true }); + for (const [f, body] of [["shot.png", "s"], ["shot-thread.png", "st"], ["901_1.jpg", "abc"], ["901_2.mp4", "abcde"], ["article.png", "a"], ["notes.txt", "n"]] as const) writeFileSync(path.join(cap, f), body); + writeFileSync( + path.join(cap, "capture.json"), + JSON.stringify({ version: 1, id: "901", capturedAt: "2026-11-17T12:40:00.000Z", state: "captured", mediaState: "ok", media: [], context: { readAt: "x", quoted: { text: "a quoted line", handle: "spout_co", media: [{ kind: "image", url: "https://example.org/p.jpg" }] } } }), + ); + return dir; +} + +test("with no new option the listing is what it was: no detail, no counts, no authors, no ids", async () => { + const dir = await judgeLibrary("judge-plain"); + const plain = await listXTrending(dir); + assert.deepEqual(Object.keys(plain).sort(), ["posts", "reads", "topics", "total"]); + assert.ok(plain.topics.every((t) => !("counts" in t))); + assert.ok(plain.posts.every((p) => !("detail" in p))); +}); + +test("the filters: the judgement in force, gone, media, author, words, first seen since; offset pages them", async () => { + const dir = await judgeLibrary("judge-filters"); + const ids = async (filter: Parameters<typeof listXTrending>[1]) => (await listXTrending(dir, filter)).posts.map((p) => p.id).sort(); + assert.deepEqual(await ids({ topic: "kettles" }), ["901", "902", "903", "904"]); + // 903 has no judgement of its own: its thread's (keep) is in force. + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep" } }), ["901", "903"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "drop" } }), ["902"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "later" } }), ["904"]); + assert.deepEqual(await ids({ filter: { state: "unjudged" } }), ["905"]); + // 902 was on the page at the first read and not at the second, which reached its end. + assert.deepEqual(await ids({ filter: { gone: true } }), ["902"]); + assert.deepEqual(await ids({ filter: { media: true } }), ["901"]); + assert.deepEqual(await ids({ filter: { author: "@LID_watch" } }), ["904"]); + assert.deepEqual(await ids({ filter: { author: "saucer_fan" } }), ["902", "903"]); + // Every word, any case, over the words, the handle and the display name. + assert.deepEqual(await ids({ filter: { q: "KETTLE" } }), ["901", "904"]); + assert.deepEqual(await ids({ filter: { q: "kettle lid" } }), ["904"]); + assert.deepEqual(await ids({ filter: { q: "teapot news" } }), ["901"]); + assert.deepEqual(await ids({ filter: { q: "nothinghere" } }), []); + assert.deepEqual(await ids({ filter: { since: "2026-11-17T10:30:00.000Z" } }), ["904", "905"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep", q: "spouts" } }), ["903"]); + // By the hand whose judgement is in force: the operator's drops, the agent's later. + assert.deepEqual(await ids({ filter: { state: "drop", by: "operator" } }), ["902"]); + assert.deepEqual(await ids({ filter: { state: "drop", by: "agent" } }), []); + assert.deepEqual(await ids({ filter: { by: "agent" } }), ["904"]); + assert.deepEqual(await ids({ filter: { by: "operator" } }), ["901", "902", "903"]); + // Pages: the same order, cut. + const all = (await listXTrending(dir)).posts.map((p) => p.id); + const two = await listXTrending(dir, { limit: 2, offset: 2 }); + assert.deepEqual(two.posts.map((p) => p.id), all.slice(2, 4)); + assert.equal(two.total, 5); + assert.deepEqual((await listXTrending(dir, { offset: 99 })).posts, []); +}); + +test("ids: every matching id in listing order, uncapped, and no rows", async () => { + const dir = await judgeLibrary("judge-ids"); + const all = (await listXTrending(dir, { topic: "kettles" })).posts.map((p) => p.id); + const out = await listXTrending(dir, { topic: "kettles", ids: true, limit: 1 }); + assert.deepEqual(out.ids, all); + assert.deepEqual(out.posts, []); + assert.equal(out.total, 4); + assert.deepEqual((await listXTrending(dir, { ids: true, filter: { state: "drop" } })).ids, ["902"]); +}); + +test("detail: a topic's counts, the accounts, the rest of the record, the first sighting, the own judgement and the capture's files by name", async () => { + const dir = await judgeLibrary("judge-detail"); + const out = await listXTrending(dir, { topic: "kettles", detail: true }); + const topics = Object.fromEntries(out.topics.map((t) => [t.id, t.counts])); + assert.deepEqual(topics.kettles, { unjudged: 0, keep: 2, drop: 1, later: 1, gone: 1 }); + assert.deepEqual(topics.cups, { unjudged: 1, keep: 0, drop: 0, later: 0, gone: 0 }); + assert.deepEqual(out.authors, [ + { author: "saucer_fan", posts: 2 }, + { author: "Lid_Watch", posts: 1 }, + { author: "teapot_news", posts: 1 }, + ]); + const by = Object.fromEntries(out.posts.map((p) => [p.id, p])); + assert.deepEqual(by["901"].detail?.post, { isReply: false, isRepost: false, links: ["https://example.org/a"], engagement: { likes: 4 }, mediaCount: 1 }); + assert.deepEqual(by["903"].detail?.post.replyTo, { platform: "twitter", id: "901", author: "teapot_news" }); + assert.equal(by["901"].detail?.firstSeenAt, "2026-11-17T10:00:00.000Z"); + assert.equal(by["904"].detail?.firstSeenAt, "2026-11-17T11:00:00.000Z"); + // 903: the thread's judgement is in force, and it has none of its own. + assert.equal(by["903"].judgement?.from, "thread"); + assert.equal(by["903"].detail?.ownJudgement, undefined); + assert.equal(by["902"].detail?.ownJudgement?.state, "drop"); + assert.equal(by["903"].detail?.threadJudgement?.note, "the opening"); + assert.equal(by["902"].detail?.threadJudgement, undefined); + // The capture: names and sizes, pictures and videos only; the context without its media addresses. + assert.deepEqual(by["901"].detail?.capture, { + shot: "shot.png", + threadShot: "shot-thread.png", + media: [ + { name: "901_1.jpg", kind: "image", bytes: 3 }, + { name: "901_2.mp4", kind: "video", bytes: 5 }, + ], + context: { quoted: { text: "a quoted line", handle: "spout_co" } }, + }); + assert.equal(by["902"].detail?.capture, undefined); + assert.doesNotMatch(JSON.stringify(out), /example\.org\/p\.jpg|notes\.txt|capture\.json/); +}); + +test("detail with the topics' seen marks: each topic's new posts in the same pass; a topic never marked is new in full", async () => { + const dir = await judgeLibrary("judge-fresh"); + const fresh = async (seen?: Record<string, string>) => Object.fromEntries((await listXTrending(dir, { detail: true, limit: 1, ...(seen ? { seen } : {}) })).topics.map((t) => [t.id, t.fresh])); + // No marks handed in: no `fresh` at all. + assert.deepEqual(await fresh(), { kettles: undefined, cups: undefined }); + assert.deepEqual(await fresh({}), { kettles: 4, cups: 1 }); + // 904 was first shown at 11:00, the rest of kettles at 10:00; cups' post at 12:00. + assert.deepEqual(await fresh({ kettles: "2026-11-17T10:30:00.000Z" }), { kettles: 1, cups: 1 }); + assert.deepEqual(await fresh({ kettles: "2026-11-17T11:00:00.000Z", cups: "2026-11-17T12:00:00.000Z" }), { kettles: 0, cups: 0 }); + // The count is of the whole topic, whatever the posts asked for. + const narrowed = await listXTrending(dir, { detail: true, topic: "cups", filter: { state: "keep" }, seen: { kettles: "2026-11-17T10:30:00.000Z" } }); + assert.equal(narrowed.topics.find((t) => t.id === "kettles")?.fresh, 1); + // A mark that is no time counts nothing as seen; and never without detail. + assert.deepEqual(await fresh({ kettles: "soon" }), { kettles: 4, cups: 1 }); + assert.ok((await listXTrending(dir, { seen: {} })).topics.every((t) => !("fresh" in t))); +}); + +test("a library in one line: its topics, its posts and how many are undecided", async () => { + assert.deepEqual(await summarizeXTrending(await judgeLibrary("judge-summary")), { topics: 2, posts: 5, unjudged: 1 }); + assert.deepEqual(await summarizeXTrending(root("judge-summary-empty")), { topics: 0, posts: 0, unjudged: 0 }); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -43,10 +43,10 @@ // SERVER-ONLY (node:fs). import path from "node:path"; -import { mkdir, readFile, readdir } from "node:fs/promises"; +import { mkdir, readFile, readdir, stat } from "node:fs/promises"; import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; -import type { Post } from "../posts"; +import type { Post, PostEngagement, PostRef } from "../posts"; import type { XTrendingRef } from "./config"; // (./watch imports only TYPES of this module: no cycle.) import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch"; @@ -658,6 +658,54 @@ export async function readXTrendingReadRecord( return r as XTrendingReadRecord; } +const VIDEO_FILE = /\.(mp4|webm|mov|m4v)$/i; + +function contextPost(raw: unknown): XTrendingContextPost | undefined { + if (!raw || typeof raw !== "object") return undefined; + const r = raw as Record<string, unknown>; + if (typeof r.text !== "string") return undefined; + const out: XTrendingContextPost = { text: r.text }; + for (const k of ["id", "url", "handle", "author", "date"] as const) { + if (typeof r[k] === "string" && r[k]) out[k] = r[k] as string; + } + return out; +} + +// The files of a captured post BY NAME, as its directory holds them: the +// shot, the thread shot, and each picture and video with its size; and the +// context its capture read. Undefined while the post has no capture +// directory. Names only: a file that is neither a picture nor a video (the +// record, an article's files) is not listed. +export async function xTrendingCaptureFiles(channelRoot: string, id: string): Promise<XTrendingPostDetail["capture"] | undefined> { + if (!/^\d+$/.test(id)) return undefined; + const dir = path.join(xTrendingPostsMediaDir(channelRoot), id); + let names: string[]; + try { + names = (await readdir(dir)).sort(); + } catch { + return undefined; + } + const media: XTrendingCaptureFile[] = []; + for (const name of names) { + if (name.startsWith("shot") || name.startsWith("article") || name.startsWith(".")) continue; + const kind = IMAGE_FILE.test(name) ? "image" : VIDEO_FILE.test(name) ? "video" : null; + if (!kind) continue; + const st = await stat(path.join(dir, name)).catch(() => null); + if (!st?.isFile()) continue; + media.push({ name, kind, bytes: st.size }); + } + const read = await readJsonFile(path.join(dir, "capture.json")); + const ctx = read.ok && read.value && typeof read.value === "object" ? (read.value as { context?: { parent?: unknown; quoted?: unknown } }).context : undefined; + const parent = contextPost(ctx?.parent); + const quoted = contextPost(ctx?.quoted); + return { + ...(names.includes(LIBRARY_SHOT_FILENAME) ? { shot: LIBRARY_SHOT_FILENAME } : {}), + ...(names.includes("shot-thread.png") ? { threadShot: "shot-thread.png" } : {}), + media, + ...(parent || quoted ? { context: { ...(parent ? { parent } : {}), ...(quoted ? { quoted } : {}) } } : {}), + }; +} + // ── the listing ──────────────────────────────────────────────────────────── export type XTrendingTopicRow = { @@ -667,6 +715,12 @@ export type XTrendingTopicRow = { // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it // is doing as one sentence. watch?: XTrendingWatch & { sentence: string }; + // With `detail`: its posts by the judgement in force, and how many are gone + // from the page. + counts?: XTrendingCounts; + // With `detail` and `seen`: its posts a read FIRST showed after the topic's + // mark (`seen[<topicId>]`, ISO); every post of a topic with no mark. + fresh?: number; sources: Array<{ trendId: string; url: string; @@ -701,7 +755,44 @@ export type XTrendingPostRow = { // The judgement in force (xTrendingEffectiveJudgement): its own, or its // thread's (`from: "thread"`). Absent: undecided. judgement?: XTrendingJudgement & { from?: "thread" }; + // Only when the listing is asked with `detail` (the Posts library page). + detail?: XTrendingPostDetail; +}; + +// What a judge view needs beyond a list row (lane posts-library), given only +// when asked for (`detail`): the rest of the post's record, when a read first +// showed it, its OWN judgement beside the one in force, and the files of its +// capture BY NAME (never a path: the names are served from +// trending/posts-media/<id>/ by the door that shows them). +export type XTrendingCaptureFile = { name: string; kind: "image" | "video"; bytes: number }; +export type XTrendingPostDetail = { + post: { + isReply: boolean; + isRepost: boolean; + replyTo?: PostRef; + quoted?: PostRef; + links: string[]; + engagement?: PostEngagement; + mediaCount?: number; + }; + firstSeenAt: string; + ownJudgement?: XTrendingJudgement; + // Its thread's own entry (what an undo of a thread press restores). + threadJudgement?: XTrendingJudgement; + capture?: { + shot?: string; + threadShot?: string; + media: XTrendingCaptureFile[]; + // The capture's reading of the post's page: the post it answers and the + // post it quotes ({handle?, author?, date?, text, url?}), as recorded. + context?: { parent?: XTrendingContextPost; quoted?: XTrendingContextPost }; + }; }; +export type XTrendingContextPost = { id?: string; url?: string; handle?: string; author?: string; date?: string; text: string }; + +export type XTrendingListState = "unjudged" | XTrendingJudgementState; +export const X_TRENDING_LIST_STATES: readonly XTrendingListState[] = ["unjudged", "keep", "drop", "later"]; +export type XTrendingCounts = { unjudged: number; keep: number; drop: number; later: number; gone: number }; export type XTrendingListing = { topics: XTrendingTopicRow[]; @@ -710,8 +801,38 @@ export type XTrendingListing = { total: number; // Reads on disk (probes included), newest first. reads: string[]; + // With `detail`: the accounts of the posts the topic narrowing leaves, most + // posts first (before any other filter). + authors?: Array<{ author: string; posts: number }>; + // With `ids`: every matching post's id, uncapped, in listing order (and + // `posts` is empty): what a bulk press over a filter judges. + ids?: string[]; +}; + +// What narrows a listing beyond its topic (lane posts-library). Every one is +// optional, and with none of them the listing is what it always was. +export type XTrendingListFilter = { + // The judgement in force, or none. + state?: XTrendingListState; + // Only posts gone from the page. + gone?: boolean; + // Only posts carrying media. + media?: boolean; + // One account's posts (its handle, any case, with or without "@"). + author?: string; + // Every word, any case, in the post's words, handle or display name. + q?: string; + // Only posts a read FIRST showed after this time (ISO). + since?: string; + // Only posts whose judgement IN FORCE was written by this hand (with + // `state`: "the operator's drops"). + by?: "agent" | "operator"; }; +export function xTrendingSearchWords(q: string | undefined): string[] { + return String(q ?? "").toLowerCase().split(/\s+/).filter(Boolean); +} + export const X_TRENDING_LIST_DEFAULT = 100; export const X_TRENDING_LIST_MAX = 500; @@ -730,7 +851,19 @@ const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.a // id); `limit` caps them (the newest read's first, in page order). export async function listXTrending( channelRoot: string, - opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post>; now?: number } = {}, + opts: { + topic?: string; + limit?: number; + posts?: ReadonlyArray<Post>; + now?: number; + offset?: number; + filter?: XTrendingListFilter; + detail?: boolean; + ids?: boolean; + // Per topic, the time its posts were last marked seen (the judge view's + // own state, handed in): with `detail`, each topic answers `fresh`. + seen?: Readonly<Record<string, string>>; + } = {}, ): Promise<XTrendingListing> { const now = opts.now ?? Date.now(); const watches = await readXTrendingWatches(channelRoot); @@ -745,12 +878,43 @@ export async function listXTrending( for (const [id, m] of Object.entries(membership)) { if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1); } + const filter = opts.filter ?? {}; + const words = xTrendingSearchWords(filter.q); + const wantAuthor = filter.author ? filter.author.replace(/^@/, "").toLowerCase() : null; + const sinceMs = filter.since ? Date.parse(filter.since) : NaN; + const counts = new Map<string, XTrendingCounts>(); + const fresh = new Map<string, number>(); + const authors = new Map<string, number>(); const rows: XTrendingPostRow[] = []; for (const [id, m] of Object.entries(membership)) { - if (opts.topic && m.topic !== opts.topic) continue; const post = archived.get(id); if (!post) continue; const thread = xTrendingThreadOf(post, membership, archived); + const effective = xTrendingEffectiveJudgement(judgements.posts[id], judgements.threads[thread]); + const firstSeenAt = m.seen.reduce((a, s) => (a === "" || s.at < a ? s.at : a), ""); + if (opts.detail) { + const c = counts.get(m.topic) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 }; + c[effective?.state ?? "unjudged"]++; + if (m.gone) c.gone++; + counts.set(m.topic, c); + if (opts.seen) { + const mark = Date.parse(opts.seen[m.topic] ?? ""); + if (!Number.isFinite(mark) || Date.parse(firstSeenAt) > mark) fresh.set(m.topic, (fresh.get(m.topic) ?? 0) + 1); + } + } + if (opts.topic && m.topic !== opts.topic) continue; + if (opts.detail) authors.set(post.author, (authors.get(post.author) ?? 0) + 1); + const media = m.media ?? { count: post.mediaCount ?? 0, kinds: [] }; + if (filter.state && (effective?.state ?? "unjudged") !== filter.state) continue; + if (filter.by && effective?.by !== filter.by) continue; + if (filter.gone && !m.gone) continue; + if (filter.media && !(media.count > 0)) continue; + if (wantAuthor !== null && post.author.toLowerCase() !== wantAuthor) continue; + if (Number.isFinite(sinceMs) && !(Date.parse(firstSeenAt) > sinceMs)) continue; + if (words.length) { + const hay = `${post.text} ${post.author} ${post.authorName ?? ""}`.toLowerCase(); + if (!words.every((w) => hay.includes(w))) continue; + } rows.push({ id, author: post.author, @@ -758,15 +922,30 @@ export async function listXTrending( createdAt: post.createdAt, url: post.url, text: post.text, - media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] }, + media, topic: m.topic, reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })), ...(m.gone ? { gone: m.gone } : {}), thread, - ...(() => { - const judgement = xTrendingEffectiveJudgement(judgements.posts[id], judgements.threads[thread]); - return judgement ? { judgement } : {}; - })(), + ...(effective ? { judgement: effective } : {}), + ...(opts.detail + ? { + detail: { + post: { + isReply: post.isReply, + isRepost: post.isRepost, + ...(post.replyTo ? { replyTo: post.replyTo } : {}), + ...(post.quoted ? { quoted: post.quoted } : {}), + links: post.links, + ...(post.engagement ? { engagement: post.engagement } : {}), + ...(post.mediaCount !== undefined ? { mediaCount: post.mediaCount } : {}), + }, + firstSeenAt, + ...(judgements.posts[id] ? { ownJudgement: judgements.posts[id] } : {}), + ...(judgements.threads[thread] ? { threadJudgement: judgements.threads[thread] } : {}), + }, + } + : {}), }); } const rank = (id: string) => { @@ -780,12 +959,16 @@ export async function listXTrending( return rank(a.id) - rank(b.id) || (a.id < b.id ? -1 : 1); }); const limit = Math.min(Math.max(1, opts.limit ?? X_TRENDING_LIST_DEFAULT), X_TRENDING_LIST_MAX); + const offset = Math.max(0, Math.floor(opts.offset ?? 0)); + const page = opts.ids ? [] : rows.slice(offset, offset + limit); return { topics: topics.map((t) => ({ id: t.id, title: t.title, posts: count.get(t.id) ?? 0, ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}), + ...(opts.detail ? { counts: counts.get(t.id) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 } } : {}), + ...(opts.detail && opts.seen ? { fresh: fresh.get(t.id) ?? 0 } : {}), sources: t.sources.map((s) => ({ trendId: s.trendId, url: s.url, @@ -797,19 +980,33 @@ export async function listXTrending( })), // The thumbnail is looked up for the rows returned only (one readdir each). posts: await Promise.all( - rows.slice(0, limit).map(async (row) => { - const [thumbnail, capture] = await Promise.all([ + page.map(async (row) => { + const [thumbnail, capture, files] = await Promise.all([ firstCapturedThumbnail(channelRoot, row.id), xTrendingCaptureSummary(channelRoot, row.id), + opts.detail ? xTrendingCaptureFiles(channelRoot, row.id) : undefined, ]); return { ...row, ...(thumbnail ? { media: { ...row.media, thumbnail } } : {}), ...(capture ? { capture } : {}), + ...(row.detail && files ? { detail: { ...row.detail, capture: files } } : {}), }; }), ), total: rows.length, reads, + ...(opts.detail ? { authors: [...authors].map(([author, posts]) => ({ author, posts })).sort((a, b) => b.posts - a.posts || (a.author < b.author ? -1 : 1)) } : {}), + ...(opts.ids ? { ids: rows.map((r) => r.id) } : {}), + }; +} + +// A library in one line, for the list of libraries (lane posts-library). +export async function summarizeXTrending(channelRoot: string): Promise<{ topics: number; posts: number; unjudged: number }> { + const listing = await listXTrending(channelRoot, { detail: true, ids: true }); + return { + topics: listing.topics.length, + posts: listing.total, + unjudged: listing.topics.reduce((n, t) => n + (t.counts?.unjudged ?? 0), 0), }; } diff --git a/common/lib/xTrending/watch.ts b/common/lib/xTrending/watch.ts @@ -233,7 +233,7 @@ export function describeXTrendingWatch(w: XTrendingWatch, now: number): string { if (w.ended) return w.ended.sentence; if (!w.on) return "Not watched."; const every = `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}`; - if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until someone switches it on again: ${w.paused.sentence}`; + if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until the operator switches it on again: ${w.paused.sentence}`; if (w.paused) return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC: ${w.paused.sentence}`; const next = w.nextTickAt ? Date.parse(w.nextTickAt) : now; return `Watched ${every}; ${w.ticks} tick${w.ticks === 1 ? "" : "s"} so far, next ${next <= now ? "at the next scan" : `at ${hhmm(next)} UTC`}.`; diff --git a/common/publish/xTrendingReportDoor.test.ts b/common/publish/xTrendingReportDoor.test.ts @@ -267,3 +267,57 @@ test("N8a: behind such a host, preparing media refuses a library's post, and no [[LIB, "vid00000001", "not-in-site", X_TRENDING_NOT_CITABLE(LIB)]], ); }); + +// Every call of `fn` in a source, with its WHOLE argument text (parentheses balanced, so a call whose +// first argument is itself a call — `listXTrending(path.join(a, b), { detail: true })` — is read to its end). +function callsOf(text: string, fn: string): string[] { + const out: string[] = []; + for (let at = text.indexOf(`${fn}(`); at >= 0; at = text.indexOf(`${fn}(`, at + 1)) { + let depth = 0; + let end = -1; + for (let i = at + fn.length; i < text.length; i++) { + if (text[i] === "(") depth++; + else if (text[i] === ")" && --depth === 0) { + end = i; + break; + } + } + out.push(text.slice(at + fn.length + 1, end < 0 ? text.length : end)); + } + return out; +} + +// The judge view's asks of the listing: no publishing source may make one. +const JUDGE_VIEW_ASKS = /\b(detail|ids|filter|offset|seen)\b\s*[:,}]/; +function judgeViewAsk(text: string): string | null { + for (const args of callsOf(text, "listXTrending")) { + // The options are everything after the first argument (the library's root). + if (JUDGE_VIEW_ASKS.test(args)) return `listXTrending(${args.replace(/\s+/g, " ").slice(0, 120)})`; + } + return null; +} + +// Lane posts-library: the judge view's reads (the detail listing) are the one +// place a kept post's note and its capture's context are given out. No report +// door wrote them, and no report module can ask for them or for the purge. +test("posts-library: the detail listing holds the note and the context; what the report doors wrote holds neither, and no report source names the judge view's reads or the purge", async () => { + const { listXTrending } = await import("../lib/xTrending/store"); + const { SLICE2_MARKS } = await import("../lib/xTrending/__fixtures__/slice2Library"); + const detail = JSON.stringify(await listXTrending(libRoot, { detail: true })); + assert.ok(detail.includes(SLICE2_MARKS.note) && detail.includes(SLICE2_MARKS.context), "the judge view's listing carries them"); + assert.ok(!detail.includes(SLICE2_MARKS.address), "and never a media address"); + assertNoSlice2(filesUnder(paths.exportPublicDir), "the public dir, after the judge view's read"); + const here = path.dirname(new URL(import.meta.url).pathname); + const sources = filesUnder(here).filter((f) => /\.(ts|mjs)$/.test(f.rel) && !f.rel.includes(".test.")); + assert.ok(sources.length > 5, "the publish sources were read"); + for (const f of sources) { + for (const word of ["xTrending/purge", "purgeXTrendingDropped", "removeXTrendingPostCapture", "summarizeXTrending", "xTrendingCaptureFiles"]) { + assert.ok(!f.text.includes(word), `publish/${f.rel} names ${word}`); + } + assert.equal(judgeViewAsk(f.text), null, `publish/${f.rel} asks the listing for the judge view's fields`); + } + // The sweep catches the shape a real caller has (the root built by a call, the options after it). + assert.ok(judgeViewAsk("await listXTrending(path.join(paths.channelsDir, slug), {\n detail: true,\n});")); + assert.ok(judgeViewAsk("listXTrending(root(x), { topic, ids: true })")); + assert.equal(judgeViewAsk("listXTrending(path.join(a, b), { topic, limit })"), null); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,25 @@ # Changelog ## [Unreleased] +- **The Posts library: a trending library is browsed and judged in umtool.** + - **`/tools/library`** in umtool (Tools → posts library): topics on the left with their post, unjudged and new + counts and what each watch is doing; each post drawn as the archive's viewer draws one, with its captured + screenshot, pictures and video. A post a trending page no longer shows reads **Gone from the page at <time>**. + - **Keep / Drop / Later / Clear** per post or per thread, a note, a selection, and bulk over the filter behind a + confirm that states the count. **Undo** puts back what the last press replaced; it does not cancel a capture + already queued. Keys: `j` `k`, `a` `d` `l` `c`, `t`, `n`, `x`, `u`, `/`, `g`, `m`, `?`, Shift for bulk. + - Filters by judgement, new since **Mark seen**, gone from the page, has media, author and words; a **Watch** + switch per topic; it works on a phone. + - **Purge dropped posts' captures**, in two presses: the first says what would be removed (posts, files, bytes). + `pnpm ops purge-trending` is the same: a dry run answers `confirm`, and the removal carries it with + `"by": "operator"`. Only the captures of posts the operator dropped go: an agent's drop is counted and left + alone. For a dropped post that is gone from the page, the confirm says its capture is the only copy and that + removing it cannot be undone. Judgements stay; media another post uses is left. + - Every press is the editor's action, written as the operator's, and umtool takes a press from its own page in + a browser only. `umtool library` is the same from a shell, where `--by` is `agent` unless told. The library stays private: nothing here puts a post into a project or on a site. + - `GET /api/ops/trending` takes the judge view's asks (filters, `offset`, `ids`, `detail`; no `slug` lists the + libraries). Asked as before, it answers as before. + - A failing watch says it waits until the operator switches it on again, in its own sentence and in the help. - **A trending library can be judged, archived and watched.** - **Keep / Drop / Later** under each post on a library's page, or `pnpm ops judge-trending`. A thread can be judged by its root post. An agent's judgement never replaces the operator's: it is skipped for that post and @@ -19,7 +38,7 @@ cover a night nobody refreshes in. /review lists paused watches. The limit is the watch's own: it holds whatever the login source, and with the cookie-age setting at 0. - All libraries share one stream of ticks: no tick starts while a trending read or capture of any library is - queued or running. Three failed reads in a row pause a watch until someone switches it on again. + queued or running. Three failed reads in a row pause a watch until the operator switches it on again. - A post a trending page stops showing is marked "Gone from the page at …", and only when the saved capture shows the page's end. That is not a claim it was deleted. - A browser that will not close is now killed by its process id, checked against the profile it holds. diff --git a/editor/app/api/ops/purge-trending/route.test.ts b/editor/app/api/ops/purge-trending/route.test.ts @@ -0,0 +1,87 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/purge-trending/route.test.ts" +// +// purge-trending over ops (lane posts-library), against a temp corpus: the +// dry run that removes nothing, the removal that is the operator's and +// carries the dry run's digest, and what stays. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-purge-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const READ = "tr-01JA0000000000000000000000"; +const A = "1900000000000001001"; +const B = "1900000000000001002"; + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} }); +await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" }); +const row = (id: string) => + JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: `post ${id}`, url: `https://x.com/teapot_news/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] }); +await writeFile(path.join(lib, "trending", "posts", "2026-11.jsonl"), `${row(A)}\n${row(B)}\n`); +await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\n`); +const seen = [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }]; +await writeFile(path.join(lib, "trending", "topics.json"), JSON.stringify({ version: 1, topics: [{ id: "kettles", title: "Kettles", createdAt: "2026-11-17T10:00:00.000Z", sources: [] }] })); +await writeFile(path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen }, [B]: { topic: "kettles", seen } } })); +await writeFile(path.join(lib, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { [A]: { state: "drop", by: "operator", at: "2026-11-17T12:00:00.000Z" }, [B]: { state: "keep", by: "operator", at: "2026-11-17T12:00:00.000Z" } }, threads: {} })); +for (const id of [A, B]) { + await mkdir(path.join(lib, "trending", "posts-media", id), { recursive: true }); + await writeFile(path.join(lib, "trending", "posts-media", id, "shot.png"), "12345"); +} + +const POST = (await import("./route")).POST; +test.after(() => rm(ROOT, { recursive: true, force: true })); +const exists = (p: string) => access(p).then(() => true, () => false); + +async function call(body: Record<string, unknown>, token = "test-token") { + const res = await POST(new Request("http://localhost/api/ops/purge-trending", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) })); + return { status: res.status, json: (await res.json()) as Record<string, any> }; +} + +test("the dry run counts and removes nothing; the removal is the operator's, with the dry run's digest", async () => { + assert.equal((await call({ slug: "trending", dryRun: true }, "wrong")).status, 401); + const dry = await call({ slug: "trending", dryRun: true, topic: "kettles" }); + assert.equal(dry.status, 200); + assert.deepEqual({ posts: dry.json.posts, ids: dry.json.ids, files: dry.json.files, bytes: dry.json.bytes, dryRun: dry.json.dryRun }, { posts: 1, ids: [A], files: 1, bytes: 5, dryRun: true }); + assert.equal(dry.json.sentence, "Would remove the capture of 1 dropped post: 1 file, 5 B. The judgements stay. Keeping it again captures it again."); + assert.deepEqual({ gone: dry.json.gone, agentDropped: dry.json.agentDropped }, { gone: [], agentDropped: 0 }); + assert.equal(await exists(path.join(lib, "trending", "posts-media", A)), true); + + // An agent, a missing digest, a wrong one: refused, nothing removed. + assert.match((await call({ slug: "trending", confirm: dry.json.confirm })).json.error, /the operator's press/); + assert.match((await call({ slug: "trending", confirm: dry.json.confirm, by: "agent" })).json.error, /the operator's press/); + assert.match((await call({ slug: "trending", by: "operator" })).json.error, /"dryRun": true first/); + assert.match((await call({ slug: "trending", by: "operator", confirm: "0000000000000000" })).json.error, /have changed since the dry run/); + assert.equal(await exists(path.join(lib, "trending", "posts-media", A)), true); + + const judgements = await readFile(path.join(lib, "trending", "judgements.json"), "utf8"); + const done = await call({ slug: "trending", by: "operator", confirm: dry.json.confirm, topic: "kettles" }); + assert.equal(done.status, 200); + assert.equal(done.json.dryRun, false); + assert.match(done.json.sentence, /^Removed the capture of 1 dropped post/); + assert.equal(await exists(path.join(lib, "trending", "posts-media", A)), false); + // The kept post's capture and every judgement stay. + assert.equal(await exists(path.join(lib, "trending", "posts-media", B, "shot.png")), true); + assert.equal(await readFile(path.join(lib, "trending", "judgements.json"), "utf8"), judgements); +}); + +test("refused with a sentence: not a library, no such topic, ill-shaped ids, an unknown key", async () => { + assert.match((await call({ slug: "account-x", dryRun: true })).json.error, /library/i); + assert.match((await call({ slug: "trending", dryRun: true, topic: "nope" })).json.error, /has no topic "nope"/); + assert.match((await call({ slug: "trending", dryRun: true, ids: "x" })).json.error, /"ids" is a list/); + assert.match((await call({ slug: "trending", dryRun: true, ids: ["../x"] })).json.error, /"ids" is a list of post ids/); + assert.equal((await call({ slug: "trending", dryRun: true, force: true })).status, 400); +}); diff --git a/editor/app/api/ops/purge-trending/route.ts b/editor/app/api/ops/purge-trending/route.ts @@ -0,0 +1,58 @@ +import { NextResponse } from "next/server"; +import { purgeXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun: true, topic?, ids? } +// -> { ok: true, slug, dryRun: true, posts, ids, files, bytes, blobsFreed, +// blobsKept, gone: [{id, at}], agentDropped, skipped: [{id, reason}], +// confirm, captureInFlight?, sentence } +// POST { slug, confirm, by: "operator", topic?, ids? } +// -> the same, dryRun: false: removed +// +// PURGE THE CAPTURES OF DROPPED POSTS OF AN X TRENDING LIBRARY (lane +// posts-library): the screenshot, the record and the media under +// `channels/<slug>/trending/posts-media/<id>/` of every post whose judgement +// IN FORCE is drop BY THE OPERATOR (its own entry, or its thread's) — in one +// `topic`, the whole library, or the `ids` named among them (an id that is +// not such a post is named in `skipped`, never removed). AN AGENT'S DROP IS A +// SUGGESTION AND IS NEVER PURGED: `agentDropped` counts the posts an agent +// dropped that have a capture, left alone. `gone` names the posts to be +// removed that are gone from the page: their capture is the only copy, and +// `sentence` says that removing it cannot be undone. +// +// WHAT STAYS: the judgements, the posts, the reads; a post marked later, kept +// or undecided; and every media file another post still uses (media is kept +// once, by content: `blobsKept`). Addresses remembered as over the size cap +// are not forgotten. A later keep captures the post again. +// +// TWO STEPS, AND THE SECOND IS THE OPERATOR'S. `dryRun: true` removes nothing: +// it counts (`posts`, `files`, `bytes`) and answers `confirm`, a digest of the +// exact posts. The removal carries that `confirm` and `by: "operator"`; if the +// set changed in between (a post dropped or kept, a capture added) it is +// refused and nothing is removed — checked again inside the media index's +// lock, immediately before the first file goes. An agent's removal is refused: an agent may +// ask for the dry run. +// +// Refused with a sentence: no such channel, not a library, no such topic, a +// removal with no `confirm` or not by the operator, a `confirm` that no +// longer matches, and A CAPTURE OF THE LIBRARY QUEUED OR RUNNING (it writes +// these directories; a dry run then says `captureInFlight: true`). +export async function POST(request: Request) { + return ops(request, ["slug", "topic", "ids", "dryRun", "confirm", "by"], async (body) => { + const dryRun = optBool(body, "dryRun"); + const topic = optString(body, "topic"); + const confirm = optString(body, "confirm"); + const result = await purgeXTrendingAction({ + slug: reqSlug(body, "slug"), + ...(topic !== undefined ? { topic } : {}), + ...(body.ids !== undefined ? { ids: body.ids } : {}), + ...(dryRun !== undefined ? { dryRun } : {}), + ...(confirm !== undefined ? { confirm } : {}), + ...(body.by !== undefined ? { by: body.by } : {}), + }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/api/ops/trending/route.test.ts b/editor/app/api/ops/trending/route.test.ts @@ -0,0 +1,102 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/trending/route.test.ts" +// +// The library's listing over ops, as the judge view asks it (lane +// posts-library), against a temp corpus: the libraries by their marker, the +// filters and pages, ids, detail — and the answer unchanged when none of +// them is asked. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-list-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const READ = "tr-01JA0000000000000000000000"; +const A = "1900000000000001001"; +const B = "1900000000000001002"; + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {}, name: "Trending" }); +await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" }); +const row = (id: string, author: string, text: string) => + JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] }); +await writeFile(path.join(lib, "trending", "posts", "2026-11.jsonl"), `${row(A, "teapot_news", "The kettle festival opens.")}\n${row(B, "saucer_fan", "Saucers.")}\n`); +await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\n`); +const seen = (rank: number) => [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank }]; +await writeFile(path.join(lib, "trending", "topics.json"), JSON.stringify({ version: 1, topics: [{ id: "kettles", title: "Kettles", createdAt: "2026-11-17T10:00:00.000Z", sources: [] }] })); +await writeFile(path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen: seen(1) }, [B]: { topic: "kettles", seen: seen(2) } } })); +await writeFile(path.join(lib, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { [B]: { state: "drop", by: "operator", at: "2026-11-17T12:00:00.000Z" } }, threads: {} })); + +const GET = (await import("./route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function get(query: string, token = "test-token") { + const res = await GET(new Request(`http://localhost/api/ops/trending${query}`, { headers: { authorization: `Bearer ${token}` } })); + return { status: res.status, body: (await res.json()) as Record<string, any> }; +} + +test("without a slug: the libraries, by their marker, each in one line; and no other parameter", async () => { + const all = await get(""); + assert.equal(all.status, 200); + assert.deepEqual(all.body, { ok: true, libraries: [{ slug: "trending", name: "Trending", topics: 1, posts: 2, unjudged: 1 }] }); + assert.match((await get("?detail=1")).body.error, /lists the libraries/); + assert.equal((await get("", "wrong")).status, 401); +}); + +test("asked as before, the answer is as before", async () => { + const plain = await get("?slug=trending"); + assert.deepEqual(Object.keys(plain.body).sort(), ["name", "ok", "posts", "reads", "slug", "topics", "total"]); + assert.ok(plain.body.posts.every((p: object) => !("detail" in p))); + assert.ok(plain.body.topics.every((t: object) => !("counts" in t))); +}); + +test("filters, pages, ids and detail", async () => { + assert.deepEqual((await get("?slug=trending&state=drop")).body.posts.map((p: { id: string }) => p.id), [B]); + assert.deepEqual((await get("?slug=trending&state=unjudged")).body.posts.map((p: { id: string }) => p.id), [A]); + assert.deepEqual((await get("?slug=trending&q=KETTLE+festival")).body.posts.map((p: { id: string }) => p.id), [A]); + assert.deepEqual((await get("?slug=trending&author=%40Saucer_Fan")).body.posts.map((p: { id: string }) => p.id), [B]); + assert.deepEqual((await get("?slug=trending&limit=1&offset=1")).body.posts.map((p: { id: string }) => p.id), [B]); + const ids = await get("?slug=trending&ids=1"); + assert.deepEqual(ids.body.ids, [A, B]); + assert.deepEqual(ids.body.posts, []); + const detail = await get("?slug=trending&detail=1"); + assert.deepEqual(detail.body.topics[0].counts, { unjudged: 1, keep: 0, drop: 1, later: 0, gone: 0 }); + assert.equal(detail.body.posts[0].detail.firstSeenAt, "2026-11-17T10:00:00.000Z"); + assert.deepEqual(detail.body.authors, [{ author: "saucer_fan", posts: 1 }, { author: "teapot_news", posts: 1 }]); + assert.equal("fresh" in detail.body.topics[0], false); + // Every topic's new posts in the one read, from the marks handed in. + const seen = (marks: object) => get(`?slug=trending&detail=1&limit=1&seen=${encodeURIComponent(JSON.stringify(marks))}`); + assert.equal((await seen({})).body.topics[0].fresh, 2); + assert.equal((await seen({ kettles: "2026-11-17T10:00:00.000Z" })).body.topics[0].fresh, 0); + assert.equal((await seen({ kettles: "2026-11-17T09:00:00.000Z" })).body.topics[0].fresh, 2); + // The hand whose judgement is in force. + assert.deepEqual((await get("?slug=trending&state=drop&by=operator&ids=1")).body.ids, [B]); + assert.deepEqual((await get("?slug=trending&state=drop&by=agent&ids=1")).body.ids, []); +}); + +test("refused with a sentence: an unknown parameter, a state, a flag, an author, a time, an offset, a channel that is no library", async () => { + assert.match((await get("?slug=trending&nope=1")).body.error, /unknown parameter "nope"/); + assert.match((await get("?slug=trending&state=maybe")).body.error, /"state" is one of unjudged, keep, drop, later/); + assert.match((await get("?slug=trending&gone=yes")).body.error, /"gone" is 1/); + assert.match((await get("?slug=trending&author=a/b")).body.error, /handle/); + assert.match((await get("?slug=trending&since=soon")).body.error, /"since" is a time/); + assert.match((await get("?slug=trending&offset=-1")).body.error, /"offset"/); + assert.match((await get("?slug=trending&by=me")).body.error, /"by" is "agent" or "operator"/); + assert.match((await get("?slug=trending&seen=%7B%7D")).body.error, /"seen" goes with detail=1/); + assert.match((await get("?slug=trending&detail=1&seen=nope")).body.error, /"seen" is a JSON object/); + assert.match((await get(`?slug=trending&detail=1&seen=${encodeURIComponent('{"kettles":"soon"}')}`)).body.error, /"seen" is a JSON object/); + assert.match((await get("?slug=account-x")).body.error, /library/i); + assert.equal((await get("?slug=nope")).status, 404); +}); diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -1,9 +1,16 @@ import path from "node:path"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { isValidChannelSlug, listChannelConfigs, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config"; -import { listXTrending, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { + listXTrending, + summarizeXTrending, + X_TRENDING_LIST_MAX, + X_TRENDING_LIST_STATES, + type XTrendingListFilter, + type XTrendingListState, +} from "yt-dlp-transcript-common/lib/xTrending/store"; import { opsAuth, opsFail } from "../_lib"; export const dynamic = "force-dynamic"; @@ -40,12 +47,54 @@ export const dynamic = "force-dynamic"; // nextTickAt?, ticks, paused?: {reason, since, sentence}, ended?, sentence}) is // there once it has been watched (`watch-trending`); `sentence` says what it // is doing. NEVER the raw capture, a cookie or a token. +// +// THE JUDGE VIEW'S ASKS (lane posts-library: umtool's Posts library page and +// `umtool library`). With none of them the answer above is unchanged. +// +// (no slug) -> { ok, libraries: [{slug, name, topics, posts, unjudged}] } +// every library, by its marker +// offset=<n> the posts after the first n (pages with `limit`) +// state= unjudged | keep | drop | later: the judgement IN FORCE +// gone=1 only posts gone from the page +// media=1 only posts carrying media +// author=<h> one account's posts (any case, with or without "@") +// q=<words> every word, any case, in the words, handle or display name +// since=<ISO> only posts a read FIRST showed after that time +// by= agent | operator: the hand whose judgement is in force +// seen=<JSON> with detail=1: {"<topicId>": "<ISO>", …}, when each topic +// was last marked seen (the judge view's own state); each +// topic then answers `fresh`, its posts a read first showed +// after its mark (all of them for a topic with no mark) — +// every topic's count in this one read +// ids=1 -> `ids`: every matching post's id in listing order, +// uncapped, and no rows (what a bulk press judges) +// detail=1 each topic gains `counts` {unjudged, keep, drop, later, +// gone}; the answer gains `authors` [{author, posts}] (of the +// topic asked for); each row gains `detail` {post: {isReply, +// isRepost, replyTo?, quoted?, links, engagement?, +// mediaCount?}, firstSeenAt, ownJudgement?, threadJudgement?, capture?: {shot?, +// threadShot?, media: [{name, kind, bytes}], context?: +// {parent?, quoted?}}}. A capture's files are NAMES under +// trending/posts-media/<id>/: this route serves no bytes. +const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail"]; +const FLAGS = new Set(["1", "true"]); + export async function GET(request: Request) { const denied = opsAuth(request); if (denied) return denied; const sp = new URL(request.url).searchParams; for (const key of sp.keys()) { - if (!["slug", "topic", "limit"].includes(key)) return opsFail(`unknown parameter "${key}" (slug, topic, limit)`); + if (!PARAMS.includes(key)) return opsFail(`unknown parameter "${key}" (${PARAMS.join(", ")})`); + } + const paths = getPaths(); + if (sp.get("slug") === null) { + if ([...sp.keys()].length) return opsFail(`without "slug" this lists the libraries and takes no other parameter`); + const libraries = []; + for (const { slug, config } of await listChannelConfigs(paths)) { + if (!isXTrendingChannel(config)) continue; + libraries.push({ slug, name: config.name ?? slug, ...(await summarizeXTrending(path.join(paths.channelsDir, slug))) }); + } + return NextResponse.json({ ok: true, libraries }); } const slug = sp.get("slug") ?? ""; if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); @@ -57,13 +106,70 @@ export async function GET(request: Request) { return opsFail(`"limit" is a whole number, 1–${X_TRENDING_LIST_MAX}`); } } - const paths = getPaths(); + let offset: number | undefined; + if (sp.get("offset") !== null) { + offset = Number(sp.get("offset")); + if (!Number.isInteger(offset) || offset < 0) return opsFail(`"offset" is a whole number, 0 or more`); + } + const filter: XTrendingListFilter = {}; + const state = sp.get("state"); + if (state !== null) { + if (!X_TRENDING_LIST_STATES.includes(state as XTrendingListState)) return opsFail(`"state" is one of ${X_TRENDING_LIST_STATES.join(", ")}`); + filter.state = state as XTrendingListState; + } + const flags: Record<string, boolean> = {}; + for (const key of ["gone", "media", "ids", "detail"]) { + const v = sp.get(key); + if (v !== null && !FLAGS.has(v)) return opsFail(`"${key}" is 1 when given`); + flags[key] = v !== null; + } + if (flags.gone) filter.gone = true; + if (flags.media) filter.media = true; + const author = sp.get("author"); + if (author !== null) { + if (!/^@?[A-Za-z0-9_]{1,30}$/.test(author)) return opsFail(`"author" is an account's handle`); + filter.author = author; + } + const q = sp.get("q"); + if (q !== null) { + if (q.length > 200) return opsFail(`"q" is at most 200 characters`); + filter.q = q; + } + const since = sp.get("since"); + if (since !== null) { + if (!Number.isFinite(Date.parse(since))) return opsFail(`"since" is a time (ISO)`); + filter.since = since; + } + const by = sp.get("by"); + if (by !== null) { + if (by !== "agent" && by !== "operator") return opsFail(`"by" is "agent" or "operator"`); + filter.by = by; + } + let seen: Record<string, string> | undefined; + if (sp.get("seen") !== null) { + if (!flags.detail) return opsFail(`"seen" goes with detail=1`); + let parsed: unknown; + try { + parsed = JSON.parse(sp.get("seen")!); + } catch { + parsed = null; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string" && Number.isFinite(Date.parse(v)))) { + return opsFail(`"seen" is a JSON object of topic id to time (ISO)`); + } + seen = parsed as Record<string, string>; + } const config = await readChannelConfig(paths, slug); if (!config) return opsFail(`No such channel: ${slug}`, 404); if (!isXTrendingChannel(config)) return opsFail(NOT_AN_X_TRENDING_LIBRARY(slug)); const listing = await listXTrending(path.join(paths.channelsDir, slug), { ...(topic ? { topic } : {}), ...(limit !== undefined ? { limit } : {}), + ...(offset !== undefined ? { offset } : {}), + ...(Object.keys(filter).length ? { filter } : {}), + ...(flags.detail ? { detail: true } : {}), + ...(flags.ids ? { ids: true } : {}), + ...(seen ? { seen } : {}), }); if (topic && !listing.topics.some((t) => t.id === topic)) { return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`); diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -65,6 +65,7 @@ import { type XTrendingJudgeResult, } from "yt-dlp-transcript-common/lib/xTrending/judgements"; import { isIdleBoot } from "yt-dlp-transcript-common/lib/idleBoot"; +import { purgeXTrendingDropped, type XTrendingPurgeResult } from "yt-dlp-transcript-common/lib/xTrending/purge"; import { readXTrendingTopics } from "yt-dlp-transcript-common/lib/xTrending/store"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { capturePostsAction } from "./socialActions"; @@ -350,3 +351,55 @@ export async function watchXTrendingAction(ask: WatchXTrendingAsk): Promise<Watc safeRevalidate([`/channels/${ask.slug}`, "/review"]); return { ok: true, slug: ask.slug, topic: set.topic, watch: set.watch, sentence: describeXTrendingWatch(set.watch, now) }; } + +// ── the purge ────────────────────────────────────────────────────────────── + +export type PurgeXTrendingAsk = { + slug: string; + topic?: string; + ids?: unknown; + dryRun?: boolean; + confirm?: string; + by?: unknown; +}; + +export type PurgeXTrendingActionResult = ({ ok: true; slug: string; topic?: string } & XTrendingPurgeResult) | { ok: false; error: string }; + +const PURGE_IS_THE_OPERATORS = + `Removing dropped posts' captures is the operator's press: an agent may ask for the dry run ("dryRun": true), which counts what would go and removes nothing. The operator confirms it on umtool's Posts library page (or with "by": "operator" and the dry run's "confirm").`; + +// PURGE THE CAPTURES OF DROPPED POSTS (lane posts-library): umtool's Posts +// library page and `pnpm ops purge-trending`, one body +// (lib/xTrending/purge.ts). Two steps: the dry run counts and answers +// `confirm`; the removal carries it, and is the OPERATOR's. +export async function purgeXTrendingAction(ask: PurgeXTrendingAsk): Promise<PurgeXTrendingActionResult> { + const lib = await libraryRoot(ask.slug); + if (!lib.ok) return lib; + if (ask.by !== undefined && ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` }; + const dryRun = ask.dryRun === true; + if (!dryRun && ask.by !== "operator") return { ok: false, error: PURGE_IS_THE_OPERATORS }; + if (!dryRun && (typeof ask.confirm !== "string" || !ask.confirm)) { + return { ok: false, error: `Run it with "dryRun": true first: it says what would be removed and answers "confirm", which the removal must carry.` }; + } + if (ask.ids !== undefined && (!Array.isArray(ask.ids) || ask.ids.length === 0)) return { ok: false, error: `"ids" is a list of post ids` }; + if (ask.topic !== undefined) { + const topics = await readXTrendingTopics(lib.channelRoot); + if (!topics.some((t) => t.id === ask.topic)) { + return { ok: false, error: `${ask.slug} has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"})` }; + } + } + const out = await purgeXTrendingDropped(lib.channelRoot, { + slug: ask.slug, + ...(ask.topic !== undefined ? { topic: ask.topic } : {}), + ...(ask.ids !== undefined ? { ids: ask.ids as string[] } : {}), + dryRun, + ...(ask.confirm ? { confirm: ask.confirm } : {}), + captureInFlight: () => + getRegistry() + .list() + .some((j) => j.kind === "capture-posts" && j.channelSlug === ask.slug && (j.status === "queued" || j.status === "running")), + }); + if (!out.ok) return out; + if (!dryRun) safeRevalidate([`/channels/${ask.slug}`]); + return { ok: true, slug: ask.slug, ...(ask.topic !== undefined ? { topic: ask.topic } : {}), ...out.result }; +} diff --git a/editor/e2e/x-trending.spec.ts b/editor/e2e/x-trending.spec.ts @@ -310,4 +310,43 @@ test("an X trending library: judgements, a watch tick, media kept once, gone fro // Stop watching. const off = await post("watch-trending", { slug: SLUG, topic: "kettle-festival", on: false, by: "operator" }); expect(off.json.sentence).toBe('The watch of "Kettle Festival" was switched off.'); + + // PURGE (lane posts-library): the captures of DROPPED posts, in two steps, the second the operator's. + // The watch's new post is dropped; its capture goes, the kept post's stays, and so does every judgement. + expect((await post("judge-trending", { slug: SLUG, by: "operator", archive: false, set: [{ id: NEW, state: "drop" }] })).json).toMatchObject({ written: [{ id: NEW, state: "drop" }] }); + type Plan = { ok?: boolean; error?: string; posts?: number; ids?: string[]; files?: number; bytes?: number; confirm?: string; captureInFlight?: boolean; sentence?: string }; + // (A tick resumed above may still be reading or capturing: a dry run says so, and the removal waits for it.) + let plan: Plan = {}; + await expect + .poll( + async () => { + plan = (await post("purge-trending", { slug: SLUG, dryRun: true })).json as Plan; + return plan.ok === true && plan.captureInFlight !== true && (plan.ids ?? []).includes(NEW); + }, + { timeout: 90_000 }, + ) + .toBe(true); + expect(plan.ids).toEqual([NEW]); + const had = (await readdir(dir)).sort(); + expect(had).toEqual(expect.arrayContaining([`${NEW}_1.jpg`, `${NEW}_2.jpg`, "capture.json"])); + expect(plan.files).toBe(had.length); + expect(plan.sentence).toContain(`Would remove the capture of 1 dropped post: ${had.length} files, `); + // Nothing went, and an agent may not remove. + expect((await readdir(dir)).sort()).toEqual(had); + const agent = await post("purge-trending", { slug: SLUG, confirm: plan.confirm }); + expect(agent.status).toBe(400); + expect(String(agent.json.error)).toContain("the operator's press"); + const stale = await post("purge-trending", { slug: SLUG, confirm: "0000000000000000", by: "operator" }); + expect(String(stale.json.error)).toContain("have changed since the dry run"); + expect(await pathExists(rel(`channels/${SLUG}/trending/posts-media/${NEW}`))).toBe(true); + const removed = await post("purge-trending", { slug: SLUG, confirm: plan.confirm, by: "operator" }); + expect(removed.status, JSON.stringify(removed.json)).toBe(200); + expect(removed.json).toMatchObject({ ok: true, dryRun: false, posts: 1, ids: [NEW], files: had.length }); + expect(await pathExists(rel(`channels/${SLUG}/trending/posts-media/${NEW}`))).toBe(false); + // The kept post's capture and the judgements are whole; the post is still listed, still dropped. + expect((await readdir(t(`channels/${SLUG}/trending/posts-media/${A}`))).sort()).toContain("capture.json"); + const purged = await listing(); + expect(purged.posts.find((p) => p.id === NEW)).toMatchObject({ judgement: { state: "drop", by: "operator" } }); + expect(purged.posts.find((p) => p.id === NEW)?.capture).toBeUndefined(); + expect(purged.posts.find((p) => p.id === B)).toMatchObject({ judgement: { state: "drop", by: "operator" } }); }); diff --git a/mcp/src/xTrendingPrivacy.test.ts b/mcp/src/xTrendingPrivacy.test.ts @@ -168,3 +168,56 @@ test("every read-only corpus tool over the composed site: the account's post, ne await corpus.close(); } }); + +// Lane posts-library: the judge view's asks of the editor's listing (detail, +// ids, the filters, the seen marks) and the purge are umtool's and `pnpm +// ops`'s. The MCP's two trending tools ask for a slug, a topic and a limit, and +// gain no purge. +// +// THE MCP BUILDS ITS QUERY WITH `new URLSearchParams({…})` AND `.set("…")`, so +// that is what is read: every key given to either, in a source that asks the +// listing, is one of the three. +const LISTING_KEYS = new Set(["slug", "topic", "limit"]); + +function queryKeys(text: string): string[] { + const keys: string[] = []; + // new URLSearchParams({ a: …, "b": …, c }) + for (const m of text.matchAll(/new URLSearchParams\(\s*\{([^}]*)\}/g)) { + for (const part of m[1].split(",")) { + const key = /^\s*(?:\.\.\.)?["'`]?([A-Za-z_$][\w$]*)["'`]?\s*(?::|$)/.exec(part); + if (key) keys.push(key[1]); + } + } + // q.set("a", …) / q.append("a", …) + for (const m of text.matchAll(/\.(?:set|append)\(\s*["'`]([^"'`]+)["'`]/g)) keys.push(m[1]); + // …and a key written into the address by hand: ?a=… &a=… + for (const m of text.matchAll(/\/api\/ops\/trending\?[^"'`\s]*/g)) for (const k of m[0].matchAll(/[?&]([A-Za-z_]+)=/g)) keys.push(k[1]); + return keys; +} + +test("posts-library: no MCP source asks the listing for the judge view's fields, or names the purge", async () => { + const { readdirSync, readFileSync } = await import("node:fs"); + const here = path.dirname(new URL(import.meta.url).pathname); + const sources = readdirSync(here).filter((n) => /\.ts$/.test(n) && !n.includes(".test.")); + assert.ok(sources.length > 5, "the MCP's sources were read"); + let asking = 0; + for (const name of sources) { + const text = readFileSync(path.join(here, name), "utf8"); + for (const word of ["purge-trending", "purgeXTrending", "removeXTrendingPostCapture", "/api/library", "judge-trending\"", "watch-trending\""]) { + assert.ok(!text.includes(word), `mcp/src/${name} names ${word}`); + } + if (!text.includes("/api/ops/trending")) continue; + asking++; + const keys = queryKeys(text); + assert.ok(keys.includes("slug"), `mcp/src/${name}: the query's keys were read (${keys.join(", ")})`); + for (const key of keys) assert.ok(LISTING_KEYS.has(key), `mcp/src/${name} asks the listing for "${key}"`); + } + assert.ok(asking >= 1, "a source that asks the listing was read"); +}); + +test("posts-library: the query sweep catches the shapes it guards against", () => { + assert.deepEqual(queryKeys('const q = new URLSearchParams({ slug: channel, limit: "1" });\nq.set("topic", topic);'), ["slug", "limit", "topic"]); + assert.deepEqual(queryKeys('new URLSearchParams({ slug, detail: "1" })'), ["slug", "detail"]); + assert.deepEqual(queryKeys('q.set("ids", "1"); q.append("seen", marks);'), ["ids", "seen"]); + assert.deepEqual(queryKeys("`/api/ops/trending?slug=${s}&state=drop&by=operator`"), ["slug", "state", "by"]); +}); diff --git a/package.json b/package.json @@ -25,7 +25,7 @@ "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", "test:files": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 node scripts/test-files.mjs", - "test:scripts": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", + "test:scripts": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/library/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/plans/x-trending.md b/plans/x-trending.md @@ -178,10 +178,47 @@ These are rulings, not reasons. A later ruling overturns an earlier one only whe `watch-trending {"settings"}` sets them. A watched topic's media that failed (a 403, a 404) is not asked for again by the watch; keeping the post asks again. -## Slice 3: the judge view - -umtool's Posts library page: by topic, filters by state, media type and author, bulk actions, keyboard -friendly, judgements through the editor's `judge-trending`; the purge button and its `pnpm ops` twin. +## Slice 3, as built: the judge view (lane `lane/posts-library`) + +- **The page** is umtool's `/tools/library` (`umtool/app/tools/library/page.tsx`, + `components/tools/library/LibraryView.tsx`): topics, the posts of a view drawn with the archive viewer's + body (`common/components/PostBody.tsx`, split out of `PostModal.tsx`), Keep / Drop / Later / Clear per post + or thread, a note, a selection, bulk over the filter, undo, keys, filters in the URL, a Watch switch, Mark + seen and the purge. It reads THROUGH THE EDITOR (`umtool/lib/library/load.ts`) and every press is the + editor's action with `by: "operator"` stamped on umtool's server (`umtool/lib/library/presses.mjs`; a `by` + in the body is not read). umtool writes no file of a library and asks X nothing. +- **The listing** (`listXTrending`, `GET /api/ops/trending`) takes a filter, `offset`, `ids` and `detail`, and + with no `slug` lists the libraries. With the topics' seen marks (`seen`) it answers every topic's new posts + in the same read: a view is two reads of the editor, whatever the number of topics. Asked as before it answers as before: the MCP's tools and `get trending` + are unchanged. +- **The purge** (`common/lib/xTrending/purge.ts`, `purge-trending`). RULED (review 1): IT TAKES THE + OPERATOR'S DROPS ONLY — posts whose judgement in force is drop by the operator, their own entry or their + thread's. An agent's drop is a suggestion and is never purged: the answer counts those left alone + (`agentDropped`). The posts to be removed that are gone from the page are named (`gone`), and the sentence + is true of them: the capture is the only copy and removing it cannot be undone; "keeping it again captures + it again" is said only of the others. A dry run whose walk is the removal's, a digest of the exact posts the + removal must carry, the set read again inside the media index's lock immediately before the first file goes, + the operator's, refused while a capture is queued or running. The page, `pnpm ops` and `umtool library` + print the one sentence and the same numbers. A purge clears the page's undo memory. +- **The press routes are the page's only** (review 1): `/api/library/{judge,watch,purge,seen}` write a press as + the operator's, so they take one only from umtool's own page in a browser (`umtool/lib/library/caller.mjs`: + what a browser sends and a page cannot forge, same-origin, to this machine). A request no browser sent, + with a bearer or with nothing, is a 403 naming `pnpm ops` and `umtool library`. Mark seen is the operator's + too: `umtool library seen` wants `--by operator`, and the library and topic are checked through the listing. +- **Media** is served by umtool, `/api/library/media/<lib>/<id>/<name>` (`umtool/lib/library/media.mjs`): a + picture or a video under a MARKED library's `trending/posts-media/<id>/`, its real path inside it, read + only, refusing a cross-site request, listing nothing. umtool is LAN-bound, as its other media routes are. +- **"New since last visit"** is umtool's own state, `<reports>/.umtool/posts-library.json`, moved only by + Mark seen (`umtool/lib/library/seen.mjs`). +- **`umtool library`** (`umtool/lib/library/cli.mjs`) is the same calls from a shell; there `--by` is `agent` + unless told. +- **Not offered**: any way from a library post into a project, a report, an article, the post archive or a + site. The four pins hold that, and that no build, publisher or MCP source reaches the judge view's reads. +- **Found on the way.** After a press the page reads its view again through `GET /api/library`, not + `router.refresh()`: several refreshes in a row left the last one unapplied until the next press. An undo + writes the restored entry as the operator's, whoever wrote the one it replaced (the action cannot write + another hand's entry); the bar says so. A bulk press over more than 500 posts whose later chunk fails says + how many were written and returns the undo of those. ## Slice 4: topics and publishing diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -181,6 +181,8 @@ // pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}' // pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}' // pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}' +// pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","dryRun":true}' +// pnpm ops purge-trending --json '{"slug":"trending","topic":"kettle-festival","confirm":"<the dry run's confirm>","by":"operator"}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}' // pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait // pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait @@ -715,6 +717,10 @@ const ACTIONS = [ // topic, on, intervalMinutes?, hours?, shots?}); the library's defaults // ({slug, settings}); one scan now ({slug, tick: true}). "watch-trending", + // The captures of a library's DROPPED posts removed ({slug, topic?, ids?, + // dryRun} counts and answers `confirm`; {slug, confirm, by: "operator"} + // removes): the operator's press, in two steps. + "purge-trending", // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page // ({url} or a record's {slug, id}), read only and paced; and find-copy — a // copy of every gone recording a report cites (Wayback, then archive.org), @@ -1320,7 +1326,9 @@ export function usage() { " (mediaOwed \"next\": a later capture asks again; \"kept\": once the post", " is kept). A topic carries watch {on, intervalMinutes, until, shots,", " ticks, paused?, ended?, sentence} once it has been watched. Never the", - " raw capture, a cookie or a token.", + " raw capture, a cookie or a token. The route takes more for a judge", + " view (offset, state, by, gone, media, author, q, since, seen, ids, detail; no", + " slug lists the libraries): `umtool library` asks with them.", "get x-run [<run id>] is the X run as /review's X run console shows it:", " the latest run (or the one named) — each channel's status (queued,", " running, done with its new posts, deferred, failed), \"summary\" (\"N", @@ -1951,6 +1959,28 @@ export function usage() { " 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.", "", + '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/<slug>/trending/posts-media/<id>/. 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.", + "", '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", @@ -1972,7 +2002,8 @@ export function usage() { " 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 someone switches it on again. A post a page", + " 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", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1161,6 +1161,20 @@ test("judge-trending posts its body; its help says an agent never replaces the o assert.match(usage(), /a post the operator judged through\n\s+its thread is the operator's too/); }); +test("purge-trending posts its body; its help says the removal is the operator's, after a dry run", () => { + const p = parseArgs(["purge-trending", "--json", '{"slug":"lib","topic":"kettles","dryRun":true}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/purge-trending"); + assert.deepEqual(p.body, { slug: "lib", topic: "kettles", dryRun: true }); + assert.match(usage(), /purge-trending removes the captures of DROPPED posts/); + assert.match(usage(), /It is the operator's\n\s+press: an agent's removal is refused/); + assert.match(usage(), /an agent's drop is a suggestion and is never\n\s+purged/); + assert.match(usage(), /Actions:.*watch-trending, purge-trending/); + // A failing watch waits for the operator, by name. + assert.match(usage(), /pause it until the operator switches it on again/); + assert.doesNotMatch(usage(), /until someone switches/); +}); + test("watch-trending posts its body; its help says a watch runs only on a fresh jar", () => { const p = parseArgs(["watch-trending", "--json", '{"slug":"lib","topic":"kettles","on":true,"intervalMinutes":30}']); assert.equal(p.method, "POST"); @@ -1169,5 +1183,5 @@ test("watch-trending posts its body; its help says a watch runs only on a fresh assert.match(usage(), /A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER\n\s+ITS LIMIT/); assert.match(usage(), /It does not cover a night nobody presses\n\s+Refresh in/); assert.match(usage(), /none while a trending read or capture of ANY\n\s+library waits its turn/); - assert.match(usage(), /pause it until someone switches it on again/); + assert.match(usage(), /pause it until the operator switches it on again/); }); diff --git a/umtool/app/api/library/judge/route.ts b/umtool/app/api/library/judge/route.ts @@ -0,0 +1,20 @@ +import { judgePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; +import { seenOf } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, set: [{id | thread, state, note?}], undo? } +// POST { lib, bulk: { view, state, note? }, expect } +// -> { ok, written, skipped, kept, archives, sentence, undo? } +// +// THE POSTS LIBRARY PAGE'S KEEP / DROP / LATER / CLEAR (lane posts-library): +// the editor's `judge-trending`, written as the OPERATOR's whatever the body +// says (lib/library/presses.mjs). umtool writes no file of the library and +// asks X nothing: a keep's archiving is the editor's one paced capture job. +// `bulk` judges every post the view's filters match, in chunks of at most +// 500, and refuses when the match is no longer the `expect`ed count. +export async function POST(request: Request) { + return press(request, (body) => judgePress(ask, body, { seenAt: async (lib: string, topic: string) => (await seenOf(REPORTS_ROOT, lib))[topic] ?? null })); +} diff --git a/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts b/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts @@ -0,0 +1,57 @@ +import { resolveLibraryMedia } from "@/lib/library/media.mjs"; +import { CHANNELS_DIR } from "@/lib/paths.mjs"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library/media/<lib>/<id>/<name> one captured picture or video of a library post (byte ranges) +// +// THE ONE ROUTE THAT SERVES A TRENDING LIBRARY'S MEDIA (lane posts-library), +// for the Posts library page. A library is PRIVATE, so this route is narrow +// (lib/library/media.mjs resolveLibraryMedia is the whole rule): +// +// - `lib` must carry the library marker; any other channel is a 404 +// - only `channels/<lib>/trending/posts-media/<id>/<name>`: digits for the +// id, one plain segment for the name, a picture's or a video's extension +// (never capture.json, an article, the raw reads, the judgements), and +// the file's real path inside that library's posts-media +// - it lists nothing: there is no directory answer and no index of ids +// - READ ONLY: GET and HEAD; the corpus is never written from here +// - another site's page cannot embed or fetch it: a cross-site request, or +// one naming a host that is not this machine, is refused +// (crossSiteRefusal, asked of a READ here), and the answer says +// `Cross-Origin-Resource-Policy: same-origin` +// - never cached by a shared cache: `private, no-store` +// +// umtool is bound to the LAN (the operator's phone), as every media route of +// it is: anyone on that network who knows a post's id and file name can ask. +const PRIVATE = { + "cache-control": "private, no-store", + "cross-origin-resource-policy": "same-origin", + "x-content-type-options": "nosniff", + "x-robots-tag": "noindex", +}; + +async function serve(request: Request, params: Promise<{ lib: string; id: string; name: string }>): Promise<Response> { + const refused = crossSiteRefusal(request.headers); + if (refused) return Response.json({ error: "refused: this file is served to umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const { lib, id, name } = await params; + const found = await resolveLibraryMedia({ channelsDir: CHANNELS_DIR, lib, id, name }); + if (!found.ok) return Response.json({ error: found.status === 400 ? "bad request" : "not found" }, { status: found.status, headers: PRIVATE }); + const res = rangeResponse(request, { abs: found.abs, size: found.size, headers: { ...PRIVATE, "content-type": found.type, "accept-ranges": "bytes" } }); + // A range that cannot be met is answered by the shared helper with its Content-Range alone: the + // same private headers go on it as on every other answer of this route. + if (res.status === 416) return new Response(null, { status: 416, headers: { ...PRIVATE, "content-range": res.headers.get("content-range") ?? `bytes */${found.size}` } }); + return res; +} + +export async function GET(request: Request, { params }: { params: Promise<{ lib: string; id: string; name: string }> }) { + return serve(request, params); +} + +export async function HEAD(request: Request, { params }: { params: Promise<{ lib: string; id: string; name: string }> }) { + const res = await serve(request, params); + await res.body?.cancel(); + return new Response(null, { status: res.status, headers: res.headers }); +} diff --git a/umtool/app/api/library/purge/route.ts b/umtool/app/api/library/purge/route.ts @@ -0,0 +1,15 @@ +import { purgePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic?, dryRun: true } -> what would be removed: { posts, files, bytes, confirm, sentence, … } +// POST { lib, topic?, confirm } -> removed, when the set is still the one the dry run showed +// +// THE POSTS LIBRARY PAGE'S PURGE (lane posts-library): the editor's +// `purge-trending`, the OPERATOR's, in two presses. umtool removes nothing +// itself. Only dropped posts' captures go; the judgements stay, and media +// another post still uses is left. +export async function POST(request: Request) { + return press(request, (body) => purgePress(ask, body)); +} diff --git a/umtool/app/api/library/route.ts b/umtool/app/api/library/route.ts @@ -0,0 +1,25 @@ +import { parseLibraryView } from "@/lib/library/filters.mjs"; +import { loadLibrary } from "@/lib/library/load"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library?lib=&topic=&state=&gone=1&media=1&author=&q=&new=1&offset= +// -> what the Posts library page shows for that view (lib/library/load.ts LibraryData): +// { ok: true, libraries, lib, name, view, topics, posts, total, authors, pageSize } +// or { ok: false, reason, sentence } when the editor cannot be asked or holds no such library +// +// THE PAGE'S OWN READ, ASKED AGAIN AFTER A PRESS (lane posts-library): the same read the page makes +// when it is opened, through the editor (GET /api/ops/trending), so the rows on screen are the +// editor's after every keep, drop, watch or purge. READ ONLY. It carries a private library's posts, +// so a cross-site request, or one naming a host that is not this machine, is refused, and nothing +// caches it. +const PRIVATE = { "cache-control": "private, no-store", "cross-origin-resource-policy": "same-origin" }; + +export async function GET(request: Request) { + if (crossSiteRefusal(request.headers)) return Response.json({ error: "refused: the library is read by umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const sp = new URL(request.url).searchParams; + const params: Record<string, string> = {}; + for (const [k, v] of sp) if (!(k in params)) params[k] = v; + return Response.json(await loadLibrary(parseLibraryView(params)), { headers: PRIVATE }); +} diff --git a/umtool/app/api/library/seen/route.ts b/umtool/app/api/library/seen/route.ts @@ -0,0 +1,18 @@ +import { seenPress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; +import { markSeen } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topics: [<topicId>, …] } -> { ok, slug, topics: { <id>: { seenAt, previous? } } } +// +// MARK SEEN (lane posts-library): the one thing that moves "new since last +// visit", and the operator's (the page's press only: lib/library/route.ts). +// umtool's OWN state (REPORTS_ROOT/.umtool/posts-library.json, +// lib/library/seen.mjs), never a file of the library. The library and every +// topic are checked through the editor's listing first: a name the editor +// does not hold is refused and nothing is marked. +export async function POST(request: Request) { + return press(request, (body) => seenPress(ask, body, { mark: (lib: string, topics: string[]) => markSeen(REPORTS_ROOT, { slug: lib, topics }) })); +} diff --git a/umtool/app/api/library/watch/route.ts b/umtool/app/api/library/watch/route.ts @@ -0,0 +1,14 @@ +import { watchPress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic, on, intervalMinutes?, hours?, shots? } -> the editor's { ok, topic, watch, sentence } +// +// THE POSTS LIBRARY PAGE'S WATCH SWITCH (lane posts-library): the editor's +// `watch-trending` for one topic, as the OPERATOR (so it is the press that +// restarts a watch paused as failing). umtool reads no page of X: the editor's +// own scan starts each read, on X's queue, under the watch's jar rule. +export async function POST(request: Request) { + return press(request, (body) => watchPress(ask, body)); +} diff --git a/umtool/app/globals.css b/umtool/app/globals.css @@ -19,6 +19,9 @@ (their stylesheet is the import above) and the verdict chip they draw. Named, not detected, as above. */ @source "../../common/components/report"; +/* The Posts library draws a post with the archive viewer's own body (lane + posts-library): that one file, named. */ +@source "../../common/components/PostBody.tsx"; /* =========================================================================== THE DESK AND THE READER (plans/umtool-redesign.md, "Design direction"; the diff --git a/umtool/app/tools/library/page.tsx b/umtool/app/tools/library/page.tsx @@ -0,0 +1,76 @@ +import { Suspense } from "react"; +import AppShell from "@/components/shell/AppShell"; +import LibraryView from "@/components/tools/library/LibraryView"; +import { loadLibrary } from "@/lib/library/load"; +import { parseLibraryView } from "@/lib/library/filters.mjs"; +import { e2eStreamDelay } from "@/lib/streamDelay"; +import { toolsHref } from "@/lib/hrefs"; + +export const dynamic = "force-dynamic"; + +// THE POSTS LIBRARY (plans/x-trending.md, slice 3; lane posts-library): a +// private X trending library, browsed by topic and judged — keep, drop, later +// — before anything of it is published. No project: a library is no piece's. +// +// EVERYTHING IS THE EDITOR'S. The page reads the library through the editor +// (lib/library/load.ts) and every press is the editor's action, written as +// the operator's (/api/library/*). umtool writes no file of a library and +// asks X nothing. Nothing here puts a library post into a project, a report, +// an article, the post archive or a site: publishing is a later, explicit act. +// +// IT STREAMS: the head is sent at once, and the library — the read through +// the editor, the slow part — behind a placeholder of its shape (page-level +// Suspense; no loading.tsx). + +async function LibraryBody({ view }: { view: ReturnType<typeof parseLibraryView> }) { + await e2eStreamDelay(); + const data = await loadLibrary(view); + if (!data.ok) { + return ( + <div data-stream-filled="library"> + <p role="status" data-library-unavailable={data.reason} className="m-0 max-w-[70ch] text-[13px] leading-[1.5] text-text-2"> + {data.sentence} + </p> + </div> + ); + } + return ( + <div data-stream-filled="library"> + <LibraryView data={data} /> + </div> + ); +} + +// What holds the library's place: the topics' column and a few post-shaped +// rows, at the widths the filled page has. +function LibraryPlaceholder() { + return ( + <div data-stream-skeleton="library" aria-hidden="true" className="grid gap-x-6 gap-y-4 md:grid-cols-[260px_minmax(0,1fr)]"> + <div className="space-y-2"> + {[0, 1, 2].map((n) => ( + <div key={n} className="h-[44px] animate-pulse rounded-md border border-seam bg-panel" /> + ))} + </div> + <div className="min-w-0 space-y-3"> + <div className="h-[34px] animate-pulse rounded-md border border-seam bg-panel" /> + {[0, 1, 2, 3].map((n) => ( + <div key={n} className="h-[132px] animate-pulse rounded-md border border-seam bg-panel" /> + ))} + </div> + </div> + ); +} + +export default async function PostsLibraryPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) { + const view = parseLibraryView(await searchParams); + return ( + <div className="flex h-full flex-col"> + <AppShell active="library" crumbs={[{ href: toolsHref(), label: "Tools" }, { label: "Posts library" }]} note="private: on no site" /> + <main className="deck-main flex-1 px-4 pb-6 pt-4" data-posts-library=""> + <Suspense fallback={<LibraryPlaceholder />}> + <LibraryBody view={view} /> + </Suspense> + </main> + </div> + ); +} diff --git a/umtool/app/tools/page.tsx b/umtool/app/tools/page.tsx @@ -1,6 +1,6 @@ import AppShell from "@/components/shell/AppShell"; import ToolList, { PILE_WHAT, type ToolEntry } from "@/components/tools/ToolList"; -import { benchHref, digestContextHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; +import { benchHref, digestContextHref, facesHref, findHref, mixHref, phraseFinderHref, pileHref, postsLibraryHref, songToolsHref, sourcesHref, trimHref } from "@/lib/hrefs"; import { TRIM_SETS } from "@/lib/trim"; export const dynamic = "force-dynamic"; @@ -29,6 +29,7 @@ export default function ToolsPage() { ]; const corpus: ToolEntry[] = [ { href: digestContextHref(), name: "context notes", what: "Each channel's suggested digest context note, its evidence, and your Yes or No", testid: "context" }, + { href: postsLibraryHref(), name: "posts library", what: "A private trending library's topics and posts: keep, drop or later, watch a topic, purge what was dropped", testid: "library" }, ]; const n = song.length + articles.length + montage.length + corpus.length; return ( diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -952,6 +952,8 @@ const COMMANDS = { jobs: async () => process.exit(await (await import("../lib/queue/cli.mjs")).jobsCommand(argv.slice(argv.indexOf("jobs") + 1))), // Render mode (2026-10-30): lib/report/renderMode.mjs. "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))), + // The Posts library (lane posts-library): a private trending library's topics and posts, judged through the editor. + library: async () => process.exit(await (await import("../lib/library/cli.mjs")).libraryCommand(argv.slice(argv.indexOf("library") + 1))), // The render pool (report-to-video render-pool.mjs): lib/report/poolCli.mjs. pool: async () => process.exit(await (await import("../lib/report/poolCli.mjs")).poolCommand(argv.slice(argv.indexOf("pool") + 1))), trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), diff --git a/umtool/components/AppNav.tsx b/umtool/components/AppNav.tsx @@ -3,6 +3,7 @@ import { MODES } from "@/lib/types"; import { benchHref, digestContextHref, + postsLibraryHref, findHref, facesHref, homeHref, @@ -46,6 +47,7 @@ const TOOL_ITEMS = [ { href: sourcesHref(), label: "sources" }, { href: benchHref(), label: "bench" }, { href: digestContextHref(), label: "context" }, + { href: postsLibraryHref(), label: "library" }, ]; const PLACE_OF: Record<string, string> = { diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { benchHref, digestContextHref, + postsLibraryHref, createHref, facesHref, findHref, @@ -92,6 +93,7 @@ const FIXED: Item[] = [ { id: "sources", section: "Tools", label: "Sources", hint: "where the palette comes from", href: sourcesHref() }, { id: "bench", section: "Tools", label: "Verdict bench", hint: "could a model propose a verdict", href: benchHref() }, { id: "context", section: "Tools", label: "Channel context notes", hint: "each suggested digest note, its evidence, Yes or No", href: digestContextHref() }, + { id: "library", section: "Tools", label: "Posts library", hint: "a private trending library: keep, drop, later, watch", href: postsLibraryHref() }, // Each opens one line of /create (P5), its form open. { id: "new-research", section: "Create", label: "Research a question", hint: "opens a case", href: createHref({ make: "research" }) }, { id: "new-article", section: "Create", label: "New article", hint: "from a question: a sweep", href: createHref({ make: "article" }) }, diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -0,0 +1,877 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { PostBody, type PostCaptureView } from "yt-dlp-transcript-common/components/PostBody"; +import type { Post } from "yt-dlp-transcript-common/lib/posts"; +import { Badge } from "@/components/ui/badge"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { captureSentence, filterWords, goneSentence, libraryHref } from "@/lib/library/filters.mjs"; +import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "@/lib/library/keys.mjs"; +import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; +import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; +import type { LibraryData, LibraryPost, LibraryTopic, LibraryView as View } from "@/lib/library/load"; +import { cn } from "@/lib/utils"; + +// THE POSTS LIBRARY (app/tools/library/page.tsx): topics on the left, the +// posts of the view with their captured media in the body, and the presses. +// +// EVERY PRESS IS A POST TO /api/library/*, which is the editor's action +// written as the operator's. Nothing here writes a library's file, asks X +// anything, or offers a post to a project, a report or a site. +// +// NO LINK HERE PREFETCHES: every address of this page is a read through the +// editor, and a prefetch is that read made for a view nobody opened. +// +// THE WORDS: a post a trending page no longer shows is "Gone from the page at +// <time>" (lib/library/filters.mjs goneSentence) — a ranked list dropped it, +// which says nothing about the post. A capture's own state is shown as the +// capture job recorded it ("capture: <state> at <time>"). + +type Ok = Extract<LibraryData, { ok: true }>; +type Target = { id: string } | { thread: string }; +type JudgeState = "keep" | "drop" | "later" | "undecided"; +type UndoItem = { id?: string; thread?: string; state: string; note?: string }; +type Shown = NonNullable<LibraryPost["judgement"]>; +type Entry = NonNullable<NonNullable<LibraryPost["detail"]>["ownJudgement"]>; + +/** + * The judgement in force, by the library's one rule (common's xTrendingEffectiveJudgement): the operator's + * entry outranks an agent's; between two of one hand the post's own outranks its thread's. + */ +function inForce(own: Entry | undefined, thread: Entry | undefined): Shown | undefined { + if (own && thread) return own.by === "agent" && thread.by === "operator" ? { ...thread, from: "thread" } : own; + return own ?? (thread ? { ...thread, from: "thread" } : undefined); +} + +type PurgePlan = { posts: number; files: number; bytes: number; confirm: string; sentence: string; captureInFlight?: boolean; gone?: Array<{ id: string; at: string }>; agentDropped?: number }; + +const STATE_LABEL: Record<string, string> = { keep: "kept", drop: "dropped", later: "later" }; +const STATE_TABS: Array<{ state: string | null; label: string }> = [ + { state: null, label: "All" }, + { state: "unjudged", label: "Unjudged" }, + { state: "keep", label: "Kept" }, + { state: "drop", label: "Dropped" }, + { state: "later", label: "Later" }, +]; + +// A time, said the same on the server and in the browser (no locale, no zone +// of the reader's): "17 Nov 2026, 11:00 UTC". +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +export function utc(iso: string): string { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return iso; + const p = (n: number) => String(n).padStart(2, "0"); + return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}, ${p(d.getUTCHours())}:${p(d.getUTCMinutes())} UTC`; +} + +async function send(path: string, body: unknown): Promise<Record<string, unknown>> { + const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); + return j; +} + +/** The archive row a library post is drawn from. Never marked deleted: the library records no such thing. */ +function postOf(lib: string, row: LibraryPost): Post { + const d = row.detail?.post; + return { + id: row.id, + slug: `${lib}/${row.id}`, + channelSlug: lib, + author: row.author, + ...(row.authorName ? { authorName: row.authorName } : {}), + createdAt: row.createdAt, + uploadDate: row.createdAt.slice(0, 10).replace(/-/g, ""), + text: row.text, + url: row.url, + platform: "twitter", + isReply: d?.isReply ?? false, + isRepost: d?.isRepost ?? false, + links: d?.links ?? [], + ...(d?.replyTo ? { replyTo: d.replyTo } : {}), + ...(d?.quoted ? { quoted: d.quoted } : {}), + ...(d?.engagement ? { engagement: d.engagement } : {}), + ...(row.media.count ? { mediaCount: row.media.count } : {}), + }; +} + +function captureOf(lib: string, row: LibraryPost): PostCaptureView | null { + const files = row.detail?.capture; + if (!row.capture || !files) return null; + return { + capturedAt: row.capture.at, + state: row.capture.state, + ...(files.shot ? { shot: { src: libraryMediaSrc(lib, row.id, files.shot) } } : {}), + media: files.media.map((m) => ({ src: libraryMediaSrc(lib, row.id, m.name), name: m.name })), + }; +} + +function viewParams(view: View): Record<string, string> { + return Object.fromEntries(new URL(libraryHref({ ...view, lib: null, offset: 0 }), "http://umtool.invalid").searchParams); +} + +export default function LibraryView({ data: opened }: { data: Ok }) { + // The rows on screen: the page's own when it opens (or the view changes), then the editor's again + // after every press (GET /api/library, the same read). + const [data, setData] = useState(opened); + const { lib, view, topics, total } = data; + const router = useRouter(); + const hydrated = useHydrated(); + // The view is being read again after a press. NOT router.refresh(): several in a row (a press a + // second, from the keys) were seen to leave the last one unapplied until the next press. The read + // is asked of /api/library, and only the newest ask's answer is taken. + const [refreshing, setRefreshing] = useState(false); + const asked = useRef(0); + // What the last presses wrote, shown at once and until the rows are read again: each post's own entry + // and each thread's (null: removed). The editor's answer replaces them. + const [written, setWritten] = useState<{ posts: Map<string, Entry | null>; threads: Map<string, Entry | null> }>({ posts: new Map(), threads: new Map() }); + const posts: LibraryPost[] = useMemo(() => { + if (written.posts.size === 0 && written.threads.size === 0) return data.posts; + return data.posts.map((row) => { + if (!written.posts.has(row.id) && !written.threads.has(row.thread)) return row; + const own = written.posts.has(row.id) ? (written.posts.get(row.id) ?? undefined) : row.detail?.ownJudgement; + const thread = written.threads.has(row.thread) ? (written.threads.get(row.thread) ?? undefined) : row.detail?.threadJudgement; + const { judgement: _was, ...rest } = row; + const { ownJudgement: _o, threadJudgement: _t, ...detail } = row.detail ?? { post: { isReply: false, isRepost: false, links: [] }, firstSeenAt: row.createdAt }; + const now = inForce(own, thread); + return { ...rest, ...(now ? { judgement: now } : {}), detail: { ...detail, ...(own ? { ownJudgement: own } : {}), ...(thread ? { threadJudgement: thread } : {}) } }; + }); + }, [data.posts, written]); + const wrote = useCallback((set: UndoItem[]) => { + const at = new Date().toISOString(); + setWritten((was) => { + const next = { posts: new Map(was.posts), threads: new Map(was.threads) }; + for (const item of set) { + const entry: Entry | null = item.state === "undecided" ? null : { state: item.state as Entry["state"], ...(item.note ? { note: item.note } : {}), by: "operator", at }; + if (item.thread !== undefined) next.threads.set(item.thread, entry); + else if (item.id !== undefined) next.posts.set(item.id, entry); + } + return next; + }); + }, []); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<{ text: string; error?: boolean } | null>(null); + const [focus, setFocus] = useState(0); + const [scope, setScope] = useState<"post" | "thread">("post"); + const [selected, setSelected] = useState<Set<string>>(new Set()); + const [last, setLast] = useState<{ set: UndoItem[]; label: string } | null>(null); + const [bulk, setBulk] = useState<JudgeState | null>(null); + const [noteFor, setNoteFor] = useState<string | null>(null); + const [noteText, setNoteText] = useState(""); + const [help, setHelp] = useState(false); + const searchRef = useRef<HTMLInputElement>(null); + const cards = useRef(new Map<string, HTMLElement>()); + + const topic = view.topic ? (topics.find((t) => t.id === view.topic) ?? null) : null; + const at = Math.min(focus, Math.max(0, posts.length - 1)); + const current = posts[at] ?? null; + const here = useCallback((patch: Partial<View>) => libraryHref({ ...view, offset: 0, ...patch }), [view]); + const threadSizes = useMemo(() => { + const m = new Map<string, number>(); + for (const p of posts) m.set(p.thread, (m.get(p.thread) ?? 0) + 1); + return m; + }, [posts]); + + // A selection is of the rows shown: one that left the page is not judged by a later press. + useEffect(() => { + setSelected((s) => { + const shown = new Set(posts.map((p) => p.id)); + const next = new Set([...s].filter((id) => shown.has(id))); + return next.size === s.size ? s : next; + }); + }, [posts]); + + // The page was opened on another view (a filter, a topic, a page of posts): its rows. + useEffect(() => { + asked.current++; + setData(opened); + setWritten({ posts: new Map(), threads: new Map() }); + setRefreshing(false); + }, [opened]); + + const refresh = useCallback(async () => { + const mine = ++asked.current; + setRefreshing(true); + try { + const r = await fetch(`/api/library${new URL(libraryHref(view), window.location.origin).search}`, { cache: "no-store" }); + const next = (await r.json()) as LibraryData | { error?: string }; + if (mine !== asked.current) return; + if ("ok" in next && next.ok) { + // The editor's rows: what the presses were shown as ahead of them is theirs to say now. + setData(next); + setWritten({ posts: new Map(), threads: new Map() }); + } else { + setStatus({ text: "ok" in next ? next.sentence : (next.error ?? `The library could not be read again (HTTP ${r.status}).`), error: true }); + } + } catch (err) { + if (mine === asked.current) setStatus({ text: `The library could not be read again: ${err instanceof Error ? err.message : String(err)}`, error: true }); + } finally { + if (mine === asked.current) setRefreshing(false); + } + }, [view]); + + const run = useCallback( + async (what: () => Promise<string | void>) => { + if (busy) return; + setBusy(true); + try { + const said = await what(); + if (said) setStatus({ text: said }); + void refresh(); + } catch (err) { + setStatus({ text: err instanceof Error ? err.message : String(err), error: true }); + } finally { + setBusy(false); + } + }, + [busy, refresh], + ); + + const judgeTargets = useCallback( + (targets: Target[], state: JudgeState, note = "") => + run(async () => { + if (!targets.length) return; + const undo = undoSetOf(posts, targets) as UndoItem[]; + const set = pressSetOf(targets, state, note) as UndoItem[]; + const r = await send("/api/library/judge", { lib, set }); + wrote(set); + setLast({ set: undo, label: String(r.sentence ?? "") }); + setNoteFor(null); + setNoteText(""); + return String(r.sentence ?? ""); + }), + [lib, posts, run, wrote], + ); + + /** What a press on a post judges: the selection when there is one, else the post, or its thread under the thread scope. */ + const targetsOf = useCallback( + (row: LibraryPost | null): Target[] => { + if (selected.size) return [...selected].map((id) => ({ id })); + if (!row) return []; + return scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }]; + }, + [scope, selected], + ); + + const undo = useCallback( + () => + run(async () => { + if (!last) return "Nothing to undo."; + const r = await send("/api/library/judge", { lib, set: last.set, undo: true }); + wrote(last.set); + setLast(null); + return `${String(r.sentence ?? "Undone.")} A capture already queued is not cancelled.`; + }), + [last, lib, run, wrote], + ); + + const confirmBulk = useCallback( + (state: JudgeState) => + run(async () => { + const r = await send("/api/library/judge", { lib, bulk: { view: viewParams(view), state }, expect: total }); + const undoable = (r.undo as UndoItem[]) ?? []; + setLast(undoable.length ? { set: undoable, label: String(r.sentence ?? "") } : null); + setBulk(null); + setSelected(new Set()); + // A later chunk failed: what was written is written, and the sentence says how many were not. + if (r.partial === true) { + setStatus({ text: String(r.sentence ?? ""), error: true }); + return; + } + return String(r.sentence ?? ""); + }), + [lib, run, total, view], + ); + + const move = useCallback( + (by: number) => { + const next = Math.min(Math.max(0, at + by), Math.max(0, posts.length - 1)); + setFocus(next); + const id = posts[next]?.id; + if (id) cards.current.get(id)?.scrollIntoView({ block: "nearest" }); + }, + [at, posts], + ); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + setHelp(false); + setBulk(null); + setNoteFor(null); + return; + } + const action = libraryAction({ key: e.key, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, typing: isTyping(e.target) }); + if (!action) return; + e.preventDefault(); + const state = stateOfAction(action) as JudgeState | null; + if (action === "next") move(1); + else if (action === "prev") move(-1); + else if (action.startsWith("bulk-") && state) { + if (total > 0) setBulk(state); + } else if (state) void judgeTargets(targetsOf(current), state); + else if (action === "scope") setScope((s) => (s === "post" ? "thread" : "post")); + else if (action === "note" && current) { + setNoteFor(current.id); + setNoteText(current.detail?.ownJudgement?.note ?? ""); + } else if (action === "select" && current) { + setSelected((s) => { + const next = new Set(s); + if (next.has(current.id)) next.delete(current.id); + else next.add(current.id); + return next; + }); + } else if (action === "undo") void undo(); + else if (action === "search") searchRef.current?.focus(); + else if (action === "gone") router.push(here({ gone: !view.gone })); + else if (action === "media") router.push(here({ media: !view.media })); + else if (action === "help") setHelp((h) => !h); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [current, here, judgeTargets, move, router, targetsOf, total, undo, view.gone, view.media]); + + const off = !hydrated || busy; + const words = filterWords(view); + const first = total === 0 ? 0 : view.offset + 1; + const lastShown = view.offset + posts.length; + + return ( + <div data-library={lib} data-library-busy={busy || refreshing ? "true" : "false"} className="grid gap-x-6 gap-y-4 md:grid-cols-[260px_minmax(0,1fr)]"> + {/* ── topics: a column on a desk, a fold on a phone ── */} + <aside className="min-w-0"> + {data.libraries.length > 1 && ( + <label className="mb-2 block text-[12px] text-muted"> + <span className="micro mb-1 block">library</span> + <select data-library-pick="" className="w-full max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px] text-text" value={lib} onChange={(e) => router.push(libraryHref({ lib: e.target.value }))}> + {data.libraries.map((l) => ( + <option key={l.slug} value={l.slug}> + {l.name} ({l.unjudged} unjudged) + </option> + ))} + </select> + </label> + )} + <details className="md:hidden" data-library-topics="fold"> + <summary className="cursor-pointer rounded-[3px] border border-seam-2 px-2 py-1.5 text-[12.5px] text-text"> + Topics · {topic ? topic.title : "all"} + </summary> + <TopicList topics={topics} view={view} here={here} lib={lib} /> + </details> + <div className="hidden md:block" data-library-topics="rail"> + <div className="micro mb-1">topics</div> + <TopicList topics={topics} view={view} here={here} lib={lib} /> + </div> + </aside> + + <section className="min-w-0"> + {/* A purge takes the undo memory with it: an undo must never put back a keep whose capture was just removed. */} + <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} onPurged={() => setLast(null)} /> + + {/* ── filters: links and one plain form, so they work before the page is alive ── */} + <div data-library-filters="" className="mb-3 mt-3 flex flex-wrap items-center gap-x-2 gap-y-2"> + {STATE_TABS.map((t) => ( + <Link prefetch={false} key={t.label} href={here({ state: t.state })} data-library-state={t.state ?? "all"} aria-current={view.state === t.state ? "true" : undefined} className={buttonVariants({ size: "sm", variant: view.state === t.state ? "pressed" : "outline" })}> + {t.label} + {topic?.counts && t.state ? <span className="text-muted">{t.state === "unjudged" ? topic.counts.unjudged : topic.counts[t.state as "keep" | "drop" | "later"]}</span> : null} + </Link> + ))} + <span className="mx-1 h-4 w-px bg-seam-2" aria-hidden="true" /> + {topic ? ( + <Link prefetch={false} href={here({ fresh: !view.fresh })} data-library-toggle="new" aria-pressed={view.fresh} className={buttonVariants({ size: "sm", variant: view.fresh ? "pressed" : "outline" })} title={topic.seenAt ? `First shown since Mark seen (${utc(topic.seenAt)})` : "This topic was never marked seen: every post is new"}> + New <span className="text-muted">{topic.fresh}</span> + </Link> + ) : ( + <span data-library-toggle="new" aria-disabled="true" className={cn(buttonVariants({ size: "sm", variant: "outline" }), "opacity-50")} title="Pick a topic: each topic is marked seen on its own"> + New + </span> + )} + <Link prefetch={false} href={here({ gone: !view.gone })} data-library-toggle="gone" aria-pressed={view.gone} className={buttonVariants({ size: "sm", variant: view.gone ? "pressed" : "outline" })}> + Gone from the page{topic?.counts ? <span className="text-muted">{topic.counts.gone}</span> : null} + </Link> + <Link prefetch={false} href={here({ media: !view.media })} data-library-toggle="media" aria-pressed={view.media} className={buttonVariants({ size: "sm", variant: view.media ? "pressed" : "outline" })}> + Has media + </Link> + <select + data-library-author="" + aria-label="Author" + className="max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[11.5px] text-text" + value={view.author ?? ""} + onChange={(e) => router.push(here({ author: e.target.value || null }))} + > + <option value="">Any author</option> + {view.author && !data.authors.some((a) => a.author.toLowerCase() === view.author!.toLowerCase()) && <option value={view.author}>@{view.author}</option>} + {data.authors.map((a) => ( + <option key={a.author} value={a.author}> + @{a.author} ({a.posts}) + </option> + ))} + </select> + <form action={libraryHref({})} method="get" role="search" className="flex min-w-0 items-center gap-1"> + {Object.entries(viewParams({ ...view, q: "" })).map(([k, v]) => ( + <input key={k} type="hidden" name={k} value={v} /> + ))} + <input type="hidden" name="lib" value={lib} /> + <input ref={searchRef} type="search" name="q" defaultValue={view.q} placeholder="Search words, a handle" aria-label="Search the posts" data-library-search="" className="w-[11rem] min-w-0 max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12px] text-text" /> + <button type="submit" className={buttonVariants({ size: "sm" })}> + Search + </button> + </form> + </div> + + <p className="m-0 mb-2 text-[12px] text-muted" data-library-count={total}> + {total === 0 ? `No post${words ? ` ${words}` : ""}${topic ? ` in “${topic.title}”` : ""}.` : `${first}–${lastShown} of ${total}${words ? ` · ${words}` : ""}`} + </p> + + {/* ── the posts ── */} + <ol className="m-0 list-none space-y-3 p-0" data-library-posts=""> + {posts.map((row, i) => { + const j = row.judgement; + const own = row.detail?.ownJudgement; + const cap = row.detail?.capture; + const inThread = (threadSizes.get(row.thread) ?? 1) > 1 || row.thread !== row.id; + return ( + <li + key={row.id} + ref={(el) => { + if (el) cards.current.set(row.id, el); + else cards.current.delete(row.id); + }} + data-library-post={row.id} + data-library-judgement={j?.state ?? "unjudged"} + data-library-focus={i === at ? "true" : undefined} + onClick={() => setFocus(i)} + className={cn("rounded-md border bg-panel p-3", i === at ? "border-muted" : "border-seam")} + > + <div className="mb-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11.5px] text-muted"> + <label className="inline-flex items-center gap-1"> + <input + type="checkbox" + data-library-select="" + aria-label={`Select the post by @${row.author}`} + checked={selected.has(row.id)} + disabled={!hydrated} + onChange={(e) => + setSelected((s) => { + const next = new Set(s); + if (e.target.checked) next.add(row.id); + else next.delete(row.id); + return next; + }) + } + /> + </label> + <Badge size="sm" variant={j ? (j.state === "drop" ? "blocking" : j.state === "later" ? "open" : "on") : "state"} data-library-chip=""> + {j ? STATE_LABEL[j.state] : "unjudged"} + </Badge> + {j && ( + <span data-library-by=""> + by the {j.by} + {j.from === "thread" ? ", from its thread" : ""} · {utc(j.at)} + </span> + )} + {inThread && <span data-library-thread={row.thread}>{row.thread === row.id ? "thread root" : "in a thread"}</span>} + {!view.topic && <span>{topics.find((t) => t.id === row.topic)?.title ?? row.topic}</span>} + </div> + {j?.note && ( + <p className="m-0 mb-2 text-[12.5px] text-text-2" data-library-note=""> + Note: {j.note} + </p> + )} + + {/* The post, drawn as the archive's viewer draws one (common's PostBody). It formats its + time in the reader's own zone, so it is drawn once the page is alive; until then, its words. */} + {hydrated ? ( + // (The viewer's small badges are drawn on `bg-muted`, which in umtool's theme is a text colour.) + <div className="[&_.bg-muted]:bg-panel-2"> + <PostBody post={postOf(lib, row)} capture={captureOf(lib, row)} /> + </div> + ) : ( + <article data-post-id={row.id}> + <p className="m-0 text-xs text-muted"> + {row.authorName || row.author} @{row.author} + </p> + <p className="m-0 mt-2 whitespace-pre-wrap text-base">{row.text}</p> + </article> + )} + + {/* Thread context, as the capture read it. */} + {cap?.context?.parent && ( + <blockquote data-library-context="parent" className="m-0 mt-2 border-l-2 border-seam-2 pl-2 text-[12.5px] text-text-2"> + <span className="text-muted">In answer to {cap.context.parent.handle ? `@${cap.context.parent.handle.replace(/^@/, "")}` : "a post"}: </span> + {cap.context.parent.text} + </blockquote> + )} + {cap?.context?.quoted && ( + <blockquote data-library-context="quoted" className="m-0 mt-2 border-l-2 border-seam-2 pl-2 text-[12.5px] text-text-2"> + <span className="text-muted">Quoting {cap.context.quoted.handle ? `@${cap.context.quoted.handle.replace(/^@/, "")}` : "a post"}: </span> + {cap.context.quoted.text} + </blockquote> + )} + {cap?.threadShot && ( + <details className="mt-2" data-library-thread-shot=""> + <summary className="cursor-pointer text-[12px] text-muted">The post with the one it answers, as captured</summary> + {/* eslint-disable-next-line @next/next/no-img-element */} + <img src={libraryMediaSrc(lib, row.id, cap.threadShot)} alt="Screenshot of the reply with the post it answers" loading="lazy" className="mt-1 max-w-full rounded-md border border-seam" /> + </details> + )} + + <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[12px] text-muted"> + {row.gone && ( + <span data-library-gone="" className="text-doubt-text"> + {goneSentence(row.gone, utc)} + </span> + )} + {row.capture && <span data-library-capture={row.capture.state}>{captureSentence(row.capture, utc)}</span>} + {row.capture?.mediaOwed && <span>media owed: {row.capture.mediaOwed === "kept" ? "fetched once the post is kept" : "asked for again by the next capture"}</span>} + {!row.capture && row.media.count > 0 && <span>{row.media.count} media, not captured</span>} + <span>first shown {utc(row.detail?.firstSeenAt ?? row.reads[0]?.at ?? row.createdAt)}</span> + </div> + + <div className="mt-2 flex flex-wrap items-center gap-1.5" data-library-actions=""> + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" variant={own?.state === s ? "pressed" : "outline"} disabled={off} data-library-press={s} onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], s)}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : "Later"} + </Button> + ))} + <Button size="sm" variant="quiet" disabled={off} data-library-press="clear" onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], "undecided")}> + Clear + </Button> + <Button + size="sm" + variant="quiet" + disabled={off} + data-library-press="note" + onClick={() => { + setNoteFor(noteFor === row.id ? null : row.id); + setNoteText(own?.note ?? ""); + }} + > + Note + </Button> + {scope === "thread" && <span className="text-[11.5px] text-doubt-text">judges its whole thread</span>} + </div> + {noteFor === row.id && ( + <div className="mt-2 space-y-1.5" data-library-note-editor=""> + <textarea + aria-label="Note" + autoFocus + value={noteText} + maxLength={2000} + onChange={(e) => setNoteText(e.target.value)} + rows={2} + className="block w-full max-w-full rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px] text-text" + /> + <div className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-muted"> + <span>A note is kept with a judgement:</span> + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off || !noteText.trim()} data-library-note-save={s} onClick={() => void judgeTargets(scope === "thread" ? [{ thread: row.thread }] : [{ id: row.id }], s, noteText.trim())}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : "Later"} with the note + </Button> + ))} + </div> + </div> + )} + </li> + ); + })} + </ol> + + {(view.offset > 0 || lastShown < total) && ( + <nav className="mt-3 flex items-center gap-2 text-[12px]" aria-label="Pages" data-library-pages=""> + {view.offset > 0 ? ( + <Link prefetch={false} href={here({ offset: Math.max(0, view.offset - data.pageSize) })} className={buttonVariants({ size: "sm" })}> + Previous {data.pageSize} + </Link> + ) : null} + {lastShown < total ? ( + <Link prefetch={false} href={here({ offset: view.offset + data.pageSize })} className={buttonVariants({ size: "sm" })}> + Next {Math.min(data.pageSize, total - lastShown)} + </Link> + ) : null} + </nav> + )} + + {/* ── the bar: what a press judges, bulk over the filter, undo, the keys ── */} + <div data-library-bar="" className="sticky bottom-[var(--dock-h,0px)] z-10 mt-4 space-y-1.5 border-t border-seam-2 bg-ground py-2"> + {bulk && ( + <div role="alertdialog" aria-label="Confirm" data-library-confirm={bulk} className="rounded-md border border-doubt-text p-2 text-[12.5px] text-text"> + <p className="m-0"> + {bulk === "undecided" ? "Clear the judgement of" : bulk === "keep" ? "Keep" : bulk === "drop" ? "Drop" : "Mark later"} all <strong data-library-confirm-count="">{total}</strong> post{total === 1 ? "" : "s"} + {words ? ` (${words})` : ""} + {topic ? ` in “${topic.title}”` : " in every topic"}?{" "} + {bulk === "keep" ? `Each keep archives the post's screenshot and media through the editor's paced capture job: one job per ${500} posts, never one per post.` : "Nothing is deleted: a drop is reversible."} + </p> + <div className="mt-1.5 flex flex-wrap gap-1.5"> + <Button size="sm" variant="go" disabled={off} data-library-confirm-yes="" onClick={() => void confirmBulk(bulk)}> + {bulk === "keep" ? "Keep" : bulk === "drop" ? "Drop" : bulk === "later" ? "Mark later" : "Clear"} {total} + </Button> + <Button size="sm" disabled={busy} data-library-confirm-no="" onClick={() => setBulk(null)}> + Cancel + </Button> + </div> + </div> + )} + <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5"> + <Button size="sm" variant={scope === "thread" ? "pressed" : "outline"} disabled={!hydrated} aria-pressed={scope === "thread"} data-library-scope={scope} onClick={() => setScope((s) => (s === "post" ? "thread" : "post"))}> + {scope === "thread" ? "Judging: the whole thread" : "Judging: the post"} + </Button> + {selected.size > 0 && ( + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-text-2" data-library-selected={selected.size}> + {selected.size} selected: + {(["keep", "drop", "later", "undecided"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off} data-library-selected-press={s} onClick={() => void judgeTargets([...selected].map((id) => ({ id })), s)}> + {s === "keep" ? "Keep" : s === "drop" ? "Drop" : s === "later" ? "Later" : "Clear"} + </Button> + ))} + <Button size="sm" variant="quiet" onClick={() => setSelected(new Set())}> + None + </Button> + </span> + )} + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted"> + All {total} in the filter: + {(["keep", "drop", "later"] as const).map((s) => ( + <Button key={s} size="sm" disabled={off || total === 0} data-library-bulk={s} onClick={() => setBulk(s)}> + {s === "keep" ? "Keep all" : s === "drop" ? "Drop all" : "Later all"} + </Button> + ))} + </span> + <Button size="sm" disabled={off || !last} data-library-undo="" title={UNDO_SAYS} onClick={() => void undo()}> + Undo + </Button> + <Button size="sm" variant="quiet" disabled={!hydrated} aria-expanded={help} data-library-help-toggle="" onClick={() => setHelp((h) => !h)}> + Keys ? + </Button> + </div> + <p className="m-0 text-[11.5px] text-muted" data-library-undo-says=""> + {UNDO_SAYS} + </p> + <p role="status" aria-live="polite" data-library-status={status?.error ? "error" : "ok"} className={cn("m-0 min-h-[1.2em] text-[12.5px]", status?.error ? "text-reject-text" : "text-text-2")}> + {status?.text ?? ""} + </p> + {help && ( + <dl data-library-help="" className="m-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-[12px] text-text-2"> + {LIBRARY_KEYS.map((k) => ( + <div key={k.key} className="contents"> + <dt> + <kbd>{k.key === "A" || k.key === "D" || k.key === "L" ? `Shift+${k.key}` : k.key}</kbd> + </dt> + <dd className="m-0">{k.label}</dd> + </div> + ))} + <div className="contents"> + <dt /> + <dd className="m-0 text-muted">With posts selected, a d l c judge the selection.</dd> + </div> + </dl> + )} + </div> + </section> + </div> + ); +} + +function TopicList({ topics, view, here, lib }: { topics: LibraryTopic[]; view: View; here: (patch: Partial<View>) => string; lib: string }) { + const all = topics.reduce((n, t) => n + t.posts, 0); + const unjudged = topics.reduce((n, t) => n + (t.counts?.unjudged ?? 0), 0); + if (topics.length === 0) { + return ( + <p className="m-0 mt-2 text-[12.5px] text-text-2" data-library-no-topics=""> + {lib} has no topic yet. A topic comes from reading a trending page in the editor. + </p> + ); + } + return ( + <ul className="m-0 mt-1 list-none space-y-1 p-0"> + <li> + <Link prefetch={false} href={here({ topic: null, fresh: false })} data-library-topic="" aria-current={view.topic ? undefined : "true"} className={cn("block rounded-[3px] border px-2 py-1.5 text-[12.5px]", view.topic ? "border-transparent text-text-2 hover:bg-panel-2" : "border-muted bg-panel-2 text-text")}> + All topics + <span className="ml-1 text-muted"> + {all} posts · {unjudged} unjudged + </span> + </Link> + </li> + {topics.map((t) => { + const on = view.topic === t.id; + const w = t.watch; + const watchState = !w ? "none" : w.ended ? "ended" : w.paused ? (w.paused.reason === "failing" ? "failing" : "paused") : w.on ? "on" : "off"; + return ( + <li key={t.id}> + <Link prefetch={false} href={here({ topic: t.id })} data-library-topic={t.id} data-library-watch={watchState} aria-current={on ? "true" : undefined} className={cn("block rounded-[3px] border px-2 py-1.5 text-[12.5px]", on ? "border-muted bg-panel-2 text-text" : "border-transparent text-text-2 hover:bg-panel-2")}> + <span className="block break-words font-medium">{t.title}</span> + <span className="block text-[11.5px] text-muted"> + <span data-library-topic-posts="">{t.posts}</span> posts · <span data-library-topic-unjudged="">{t.counts?.unjudged ?? 0}</span> unjudged + {t.fresh > 0 ? ( + <> + {" · "} + <span data-library-topic-new="">{t.fresh}</span> new + </> + ) : null} + </span> + {w && ( + <span className={cn("mt-0.5 block text-[11.5px]", watchState === "failing" ? "text-reject-text" : watchState === "paused" ? "text-doubt-text" : "text-muted")} data-library-topic-watch=""> + {watchState === "failing" ? "Watch failing · " : watchState === "paused" ? "Watch paused · " : ""} + {w.sentence} + </span> + )} + </Link> + </li> + ); + })} + </ul> + ); +} + +function TopicPanel({ lib, topic, topics, off, run, onPurged }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void>; onPurged: () => void }) { + const w = topic?.watch; + const live = !!w && w.on && !w.ended; + const failing = live && w?.paused?.reason === "failing"; + const [interval, setIntervalMinutes] = useState(String(w?.intervalMinutes ?? "")); + const [hours, setHours] = useState(""); + const [shots, setShots] = useState(w?.shots ?? false); + const [plan, setPlan] = useState<PurgePlan | null>(null); + + const watch = (on: boolean) => + run(async () => { + const r = await send("/api/library/watch", { + lib, + topic: topic!.id, + on, + ...(on && interval.trim() ? { intervalMinutes: Number(interval) } : {}), + ...(on && hours.trim() ? { hours: Number(hours) } : {}), + ...(on ? { shots } : {}), + }); + return String(r.sentence ?? ""); + }); + const scope = topic ? { topic: topic.id } : {}; + const dropped = topic ? (topic.counts?.drop ?? 0) : topics.reduce((n, t) => n + (t.counts?.drop ?? 0), 0); + + return ( + <div data-library-panel={topic?.id ?? "all"} className="rounded-md border border-seam p-3"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h2 className="m-0 break-words text-[15px] font-semibold text-text">{topic ? topic.title : "All topics"}</h2> + {topic && ( + <span className="text-[12px] text-muted"> + {topic.posts} posts · {topic.counts?.unjudged ?? 0} unjudged · {topic.counts?.keep ?? 0} kept · {topic.counts?.drop ?? 0} dropped · {topic.counts?.later ?? 0} later + </span> + )} + </div> + + {topic && ( + <div className="mt-2" data-library-watch-panel={!w ? "none" : w.ended ? "ended" : failing ? "failing" : w.paused ? "paused" : w.on ? "on" : "off"}> + <p className="m-0 text-[12.5px] text-text-2" data-library-watch-sentence=""> + {w ? w.sentence : "Not watched."} + </p> + {live && w?.paused && !failing && ( + <p className="m-0 mt-1 text-[12.5px] text-doubt-text" data-library-watch-why=""> + Paused: {w.paused.sentence} It resumes by itself at the first scan after the reason is gone (for a stale cookie jar: Refresh cookies in the editor, on /cookies). + </p> + )} + {failing && ( + <p className="m-0 mt-1 text-[12.5px] text-reject-text" data-library-watch-why=""> + Failing: three reads in a row did not end as read. {w?.paused?.sentence} Only the operator restarts a failing watch: press Watch again. + </p> + )} + <div className="mt-2 flex flex-wrap items-end gap-x-3 gap-y-2 text-[12px] text-muted"> + <label className="flex flex-col gap-0.5"> + every (minutes) + <input type="number" inputMode="numeric" min={15} max={1440} placeholder="30" value={interval} onChange={(e) => setIntervalMinutes(e.target.value)} data-library-watch-interval="" className="w-[6rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text" /> + </label> + <label className="flex flex-col gap-0.5"> + for (hours) + <input type="number" inputMode="numeric" min={1} max={168} placeholder="48" value={hours} onChange={(e) => setHours(e.target.value)} data-library-watch-hours="" className="w-[6rem] rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text" /> + </label> + <label className="inline-flex items-center gap-1.5 pb-1 text-text-2"> + <input type="checkbox" checked={shots} onChange={(e) => setShots(e.target.checked)} data-library-watch-shots="" /> + Screenshot everything new + </label> + <Button size="sm" variant={live && !failing ? "outline" : "go"} disabled={off} data-library-watch-on="" onClick={() => void watch(true)}> + {failing ? "Watch again" : live ? "Change the watch" : "Watch"} + </Button> + {live && ( + <Button size="sm" disabled={off} data-library-watch-off="" onClick={() => void watch(false)}> + Stop watching + </Button> + )} + </div> + </div> + )} + + <div className="mt-3 flex flex-wrap items-center gap-x-2 gap-y-1.5 border-t border-seam pt-2"> + <Button + size="sm" + disabled={off || topics.length === 0} + data-library-seen="" + title="New means first shown since this press" + onClick={() => + void run(async () => { + const ids = topic ? [topic.id] : topics.map((t) => t.id); + await send("/api/library/seen", { lib, topics: ids }); + return topic ? `“${topic.title}” marked seen: a post is new when a read first shows it after now.` : `${ids.length} topic${ids.length === 1 ? "" : "s"} marked seen.`; + }) + } + > + Mark seen + </Button> + {topic?.seenAt && ( + <span className="text-[11.5px] text-muted" data-library-seen-at=""> + marked seen {utc(topic.seenAt)} + </span> + )} + <Button + size="sm" + disabled={off || dropped === 0} + data-library-purge="" + onClick={() => + void run(async () => { + const r = (await send("/api/library/purge", { lib, ...scope, dryRun: true })) as unknown as PurgePlan; + setPlan(r); + }) + } + > + Purge dropped posts’ captures… + </Button> + </div> + {plan && ( + <div role="alertdialog" aria-label="Purge" data-library-purge-plan={plan.posts} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-purge-sentence=""> + {plan.sentence} + </p> + {/* What is true of the removal is the editor's sentence above (the only copies, what keeping again does): nothing is added to it here. */} + {plan.posts > 0 && ( + <p className="m-0 mt-1 text-muted" data-library-purge-numbers=""> + {plan.posts} to remove · {(plan.gone ?? []).length} of them gone from the page · {plan.agentDropped ?? 0} dropped by an agent, left alone + </p> + )} + <div className="mt-1.5 flex flex-wrap gap-1.5"> + {plan.posts > 0 && ( + <Button + size="sm" + variant="go" + disabled={off || plan.captureInFlight === true} + data-library-purge-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/purge", { lib, ...scope, confirm: plan.confirm }); + setPlan(null); + onPurged(); + return String(r.sentence ?? ""); + }) + } + > + Remove {plan.posts} capture{plan.posts === 1 ? "" : "s"} + </Button> + )} + <Button size="sm" data-library-purge-no="" onClick={() => setPlan(null)}> + {plan.posts > 0 ? "Cancel" : "Close"} + </Button> + </div> + </div> + )} + </div> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -95,6 +95,11 @@ Inbox cannot disagree about what is wrong with one. | `takes verdict <project> <take> like\|maybe\|no\|clear [--note "…"] [--json]` | **a take's verdict** in `takes/verdicts.json` — the Takes page's and Play's **Like · Maybe · No**; a version with a render and none is a call on home ("versions to judge", [knobs.md](knobs.md#what-needs-you-home-the-inbox-one-press-actions-quick-clip)) | | `takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \| --all] [--apply] [--json]` | **the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions)) | | `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | +| `library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]` | the **Posts library** ([tools.md](tools.md#posts-library-toolslibrary)) from a shell: the editor's X trending libraries, a library's topics (posts, unjudged, new since Mark seen, what its watch is doing) and its posts under the page's filters — `--state unjudged\|keep\|drop\|later` is the judgement in force, `--gone` gone from the page, `--media` carrying media, `--author` one account, `--q` every word, `--new` first shown since the topic's Mark seen (with `--topic`). Read THROUGH THE EDITOR (`GET /api/ops/trending`): umtool opens no file of a library. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL | +| `library judge <lib> --state keep\|drop\|later\|undecided (--id ID,… \| --thread ID,… \| --filter [--where S] [filters] (--dry-run \| --yes)) [--note T] [--no-archive] [--by agent\|operator]` | the editor's `judge-trending`: posts by id, threads by their root post's id, or every post a filter matches (`--where` the judgement they hold now; `--dry-run` counts, and without `--yes` nothing is judged, **exit 1**), at most 500 per ask — a keep's archiving is ONE paced capture job per ask, never one per post (`--no-archive` marks only). **`--by` is `agent` unless told**: an agent's judgement is a suggestion and never replaces the operator's (skipped, by name); the page's presses are the operator's | +| `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**) | | `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)) | @@ -285,6 +290,14 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `render-mode on [--for FOR] [--note NOTE]` | render mode: a render gets the machine, for a window | form · *corpus* | | `render-mode off [--force]` | render mode off | form · *corpus* | | `render-mode status` | is render mode on, for what, until when | form · *corpus* | +| `library ls` | the editor's X trending libraries | none: a read the Posts library page (/tools/library) shows | +| `library topics` | a trending library's topics: posts, unjudged, new, the watch | none: a read the Posts library page (/tools/library) shows | +| `library posts` | a trending library's posts, filtered | none: a read the Posts library page (/tools/library) shows | +| `library judge` | keep, drop or later posts of a trending library (the editor's judge-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library watch` | watch a topic of a trending library, or stop (the editor's watch-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library purge` | remove dropped posts' captures, after a dry run (the editor's purge-trending) | none: the removal is the operator's press on the Posts library page (/tools/library), in two steps | +| `library seen` | mark topics of a trending library seen | none: the Posts library page's Mark seen (/tools/library) | +| `library help` | the library verbs | none: prints the usage | | `pool stats [--since SINCE]` | the render pool: what it holds | form · *corpus* | | `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* | | `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* | diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md @@ -3,8 +3,8 @@ ## `/tools` Four lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Montage**: the phrase finder. **Articles**: -the verdict bench. **Corpus**: the channel context notes. While you are in a tool the rail opens Tools into its tools: -find · mix · phrases · **song ▸** (the four piles) · faces · sources · bench · context. +the verdict bench. **Corpus**: the channel context notes and the posts library. While you are in a tool the rail opens +Tools into its tools: find · mix · phrases · **song ▸** (the four piles) · faces · sources · bench · context · library. | Tool | Address | What it is | |---|---|---| @@ -17,6 +17,7 @@ find · mix · phrases · **song ▸** (the four piles) · faces · sources · b | Trim | `/tools/trim/<set>` | a hook set's trims against the waveform, then **run the chain** (apply-hook-trims → pick-take → mix-hooks) | | Verdict bench | `/tools/bench` | could a model propose a fact-check verdict well enough to review: runs of `archilyzer reports bench-verdicts`, each with its prompt version and items hash, each model's agreement and recalls against the bar (**passes the bar** / **fails the bar**), confusion matrices, the items; **compare with** another run over the same items (each model's agreement in both, the claims whose answers changed); **Right** / **Wrong** on each disagreement (was the model right? kept in the run's `marks.json`), and not-CORROBORATED precision and recall as ruled and as marked beside the bar; what the verdicts mean. The bar is set here (`settings.generation.verdicts`), and with it the window proposals read (`verdicts.window`: the run's window mode and seconds); a ticked model is the only kind verdict proposals run on (the Inbox's `verdict-proposed`, [inbox.md](inbox.md)) | | Channel context notes | `/tools/digest-context` | each channel's candidate `digest-context.suggested.md` ([below](#channel-context-notes-toolsdigest-context)): what it asserts beside what it rests on, and **Yes** or **No** | +| Posts library | `/tools/library` | a private X trending library, by topic: keep, drop or later each post, watch a topic, purge what was dropped ([below](#posts-library-toolslibrary)). Read and judged through the editor; on no site | A song's own page links its piles, find, mix and sources (its Overview's Song tools; [piece.md](piece.md#a-song-projectspath)). The old addresses (`/sort`, `/salvage`, `/verify`, `/keeps`, `/mix`, `/bench`, `/browse/find`, `/browse/faces`, @@ -41,6 +42,53 @@ Nothing applies a note by itself. The one route is `GET`/`POST /api/digest-conte and a request carrying any `Authorization` header — the way an agent writes — is a 403: the press is the operator's. Besides the notes files (`lib/paths.mjs` isCorpusNotesFile), these two are the only corpus files umtool writes. +## Posts library (`/tools/library`) + +A trending library is the editor's private collection of posts read off X's trending pages, by topic (the editor's +`read-x-trending`). This page is where it is judged before anything of it is published. **Everything is the editor's**: +the page reads the library through the editor and every press is the editor's action, written as the operator's. umtool +writes no file of a library and asks X nothing; nothing here puts a post into a project, a report, an article, the post +archive or a site. With the editor down, or no library in it, the page says so in a sentence. + +- **Topics** (left; a fold on a phone): posts, unjudged, new, and what its watch is doing. A paused watch says why; a + failing one (three reads in a row that did not end as read) is restarted only by the operator: **Watch again**. +- **A post** is drawn as the archive's viewer draws one, with its captured screenshot, pictures and video in the body, + the post it answers or quotes as its capture read it, and two sentences in their own words: **Gone from the page at + <time>** (a trending page that showed it no longer does; a ranked list dropped it, which says nothing more) and + **capture: <state> at <time>** (what the capture job recorded of the post's own page). +- **Keep / Drop / Later / Clear**, per post or, with **Judging: the whole thread**, per thread; **Note** keeps a note + with a judgement. A keep archives the post's screenshot and media through the editor's paced capture job. Drop deletes + nothing. **Undo** puts back what the last press replaced, written as the operator's whoever wrote it before; it does + not cancel a capture already queued, and a purge clears it. +- **All N in the filter**: Keep all / Drop all / Later all, behind a confirm that states the count. One capture job + per 500 posts, never one per post. +- **Filters** (in the URL, so a phone and a desk open the same view): All / Unjudged / Kept / Dropped / Later, **New** + (first shown since the topic's **Mark seen**, the only thing that moves it), **Gone from the page**, **Has media**, an + author, and a search over the words, the handle and the name. +- **Watch** a topic: every N minutes, for H hours, optionally screenshotting everything new. It runs only while X's + cookie jar is fresh, and pauses otherwise (Refresh cookies in the editor resumes it). +- **Purge dropped posts' captures…** says what would be removed (posts, files, bytes), then **Remove**. It takes the + captures of posts **the operator** dropped: an agent's drop is a suggestion, counted and left alone. For a dropped + post that is gone from the page the capture is the only copy, and the confirm says that removing it cannot be + undone. Judgements stay; media another post uses is left. + +| Key | | +|---|---| +| `j` `k` | next, previous post | +| `a` `d` `l` `c` | keep, drop, later, clear (the selection when posts are selected) | +| `t` | judge the post or its whole thread | +| `n` · `x` | note · select | +| `Shift+A` `Shift+D` `Shift+L` | keep, drop, later everything in the filter (asks first) | +| `u` | undo the last press | +| `/` · `g` · `m` | search · only gone from the page · only with media | +| `?` | the list | + +A captured file is served by `/api/library/media/<lib>/<id>/<name>`: only a picture or a video under a marked +library's `trending/posts-media/<id>/`, read only, to umtool's own pages. The press routes (`/api/library/judge`, +`/watch`, `/purge`, `/seen`) take a press from umtool's own page in a browser only, because they write it as the +operator's: a script or an agent gets a 403 naming `pnpm ops` and `umtool library` ([cli.md](cli.md)), where `--by` +is `agent` unless told and Mark seen wants `--by operator`. + ## The phrase finder (`/tools/phrases`) Finding the next montage phrase, with no model. Type phrases — one row each, **Add phrase** for another — pick the diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs @@ -0,0 +1,247 @@ +// The editor's X trending library, stubbed for umtool's Posts library page +// (library.spec.ts; lane posts-library): GET /api/ops/trending with the judge +// view's asks, and the three presses — judge-trending, watch-trending, +// purge-trending — over an invented library held in memory +// (library-fixture.mjs libraryState). Every press is RECORDED with the `by` +// it carried, which is the part no page shows. +// +// POST /__stub/trending {reset?: true, mode?: "ok" | "unreachable" | "none"} +// "unreachable": every trending route drops the connection (the editor is down); +// "none": the editor holds no library +// GET /__stub/trending -> { mode, requests, reads, judgements, captured, watches } +// `reads`: how many times the listing was asked (GET /api/ops/trending) since the reset +// +// Nothing here asks X, or any host, anything. +import { createHash } from "node:crypto"; +import { libraryState } from "./library-fixture.mjs"; + +let state = libraryState(); +let mode = "ok"; +let requests = []; +let reads = 0; +let jobs = 0; + +const NOW = "2026-11-18T09:00:00.000Z"; +const ROUTES = ["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"]; + +const effective = (p) => { + const own = state.judgements.posts[p.id]; + const thread = state.judgements.threads[p.thread]; + // The operator's entry outranks an agent's; between two of one hand, the post's own. + if (own && thread) return own.by === "agent" && thread.by === "operator" ? { ...thread, from: "thread" } : own; + return own ?? (thread ? { ...thread, from: "thread" } : undefined); +}; + +function watchSentence(w) { + if (!w) return undefined; + if (w.ended) return w.ended.sentence; + const every = `every ${w.intervalMinutes} min until 10:00 UTC${w.shots ? ", screenshotting every new post" : ""}`; + if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since 12:00 UTC, until the operator switches it on again: ${w.paused.sentence}`; + if (w.paused) return `Watched ${every} — PAUSED since 12:00 UTC: ${w.paused.sentence}`; + return `Watched ${every}; ${w.ticks} ticks so far, next at the next scan.`; +} + +function captureFiles(p) { + if (!state.captured.includes(p.id)) return undefined; + const media = []; + if (p.kinds.includes("image")) media.push({ name: `${p.id}_1.jpg`, kind: "image", bytes: 68 }); + if (p.kinds.includes("video")) media.push({ name: `${p.id}_2.mp4`, kind: "video", bytes: 58 }); + return { shot: "shot.png", ...(p.context ? { threadShot: "shot-thread.png", context: p.context } : {}), media }; +} + +function row(p, detail) { + const judgement = effective(p); + const captured = state.captured.includes(p.id); + return { + id: p.id, + author: p.author, + authorName: p.authorName, + createdAt: p.createdAt, + url: p.url, + text: p.text, + media: { count: p.mediaCount, kinds: p.kinds }, + topic: p.topic, + reads: [{ read: "tr-01JA0000000000000000000000", trendId: "1900000000000000001", at: p.firstSeenAt }], + ...(p.gone ? { gone: p.gone } : {}), + ...(p.capture && (captured || p.capture.state !== "captured") ? { capture: { ...p.capture, shot: captured, files: captureFiles(p)?.media.length ?? 0 } } : {}), + thread: p.thread, + ...(judgement ? { judgement } : {}), + ...(detail + ? { + detail: { + post: { isReply: p.isReply === true, isRepost: false, ...(p.replyTo ? { replyTo: p.replyTo } : {}), links: [], ...(p.mediaCount ? { mediaCount: p.mediaCount } : {}) }, + firstSeenAt: p.firstSeenAt, + ...(state.judgements.posts[p.id] ? { ownJudgement: state.judgements.posts[p.id] } : {}), + ...(state.judgements.threads[p.thread] ? { threadJudgement: state.judgements.threads[p.thread] } : {}), + ...(captureFiles(p) ? { capture: captureFiles(p) } : {}), + }, + } + : {}), + }; +} + +function listing(sp) { + const topic = sp.get("topic"); + const detail = sp.get("detail") === "1"; + const words = (sp.get("q") ?? "").toLowerCase().split(/\s+/).filter(Boolean); + const author = sp.get("author")?.replace(/^@/, "").toLowerCase() ?? null; + const since = sp.get("since"); + const stateOf = (p) => effective(p)?.state ?? "unjudged"; + const inTopic = state.posts.filter((p) => !topic || p.topic === topic); + const rows = inTopic.filter( + (p) => + (!sp.get("state") || stateOf(p) === sp.get("state")) && + (sp.get("gone") !== "1" || p.gone) && + (sp.get("media") !== "1" || p.mediaCount > 0) && + (author === null || p.author.toLowerCase() === author) && + (!since || p.firstSeenAt > since) && + words.every((w) => `${p.text} ${p.author} ${p.authorName}`.toLowerCase().includes(w)), + ); + const seen = detail && sp.get("seen") ? JSON.parse(sp.get("seen")) : null; + const offset = Number(sp.get("offset") ?? 0); + const limit = Number(sp.get("limit") ?? 100); + const authors = new Map(); + for (const p of inTopic) authors.set(p.author, (authors.get(p.author) ?? 0) + 1); + return { + ok: true, + slug: state.slug, + name: state.name, + topics: state.topics.map((t) => { + const mine = state.posts.filter((p) => p.topic === t.id); + const counts = { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 }; + for (const p of mine) { + counts[stateOf(p)]++; + if (p.gone) counts.gone++; + } + const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null; + return { id: t.id, title: t.title, posts: mine.length, ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] }; + }), + posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)), + total: rows.length, + reads: [], + ...(detail ? { authors: [...authors].map(([a, n]) => ({ author: a, posts: n })).sort((a, b) => b.posts - a.posts || (a.author < b.author ? -1 : 1)) } : {}), + ...(sp.get("ids") === "1" ? { ids: rows.map((p) => p.id) } : {}), + }; +} + +function judge(body) { + const before = new Map(state.posts.map((p) => [p.id, effective(p)?.state])); + const written = []; + const skipped = []; + for (const item of body.set ?? []) { + const key = item.id ?? item.thread; + const bag = item.id !== undefined ? state.judgements.posts : state.judgements.threads; + if (!state.posts.some((p) => (item.id !== undefined ? p.id === key : p.thread === key))) { + skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "not a post of the library" }); + continue; + } + if (body.by === "agent" && bag[key]?.by === "operator") { + skipped.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), reason: "the operator judged it" }); + continue; + } + if (item.state === "undecided") delete bag[key]; + else bag[key] = { state: item.state, ...(item.note ? { note: item.note } : {}), by: body.by, at: NOW }; + written.push({ ...(item.id !== undefined ? { id: key } : { thread: key }), state: item.state }); + } + const kept = state.posts.filter((p) => effective(p)?.state === "keep" && before.get(p.id) !== "keep").map((p) => p.id); + return { ok: true, slug: state.slug, written, skipped, kept, ...(kept.length && body.archive !== false ? { archive: { jobId: `stub-capture-${++jobs}`, ids: kept } } : {}) }; +} + +function watch(body) { + const topic = state.topics.find((t) => t.id === body.topic); + if (!topic) return { ok: false, error: `${state.slug} has no topic "${body.topic}"` }; + if (body.on && topic.watch?.paused?.reason === "failing" && body.by !== "operator") return { ok: false, error: "This watch is paused as failing: only the operator switches it on again." }; + if (!body.on) topic.watch = { ...(topic.watch ?? {}), on: false, ended: { at: NOW, reason: "off", sentence: "Switched off: not watched." } }; + else topic.watch = { on: true, intervalMinutes: body.intervalMinutes ?? 30, startedAt: NOW, until: "2026-11-20T10:00:00.000Z", shots: body.shots === true, by: body.by ?? "agent", ticks: 0, failures: 0, nextSource: 0, goneSources: [] }; + return { ok: true, slug: state.slug, topic: topic.id, watch: topic.watch, sentence: watchSentence(topic.watch) }; +} + +const digest = (ids) => createHash("sha256").update(JSON.stringify([state.slug, [...ids].sort()])).digest("hex").slice(0, 16); + +// The editor's rule (common/lib/xTrending/purge.ts): the OPERATOR's drops only; an agent's are counted and +// left; the posts gone from the page are named, and the sentence is true of them. +function purge(body) { + const scoped = state.posts.filter((p) => (!body.topic || p.topic === body.topic) && effective(p)?.state === "drop" && state.captured.includes(p.id)); + const mine = scoped.filter((p) => effective(p).by === "operator"); + const ids = mine.map((p) => p.id).sort(); + const agentDropped = scoped.length - mine.length; + const gone = mine.filter((p) => p.gone).map((p) => ({ id: p.id, at: p.gone.at })); + const files = ids.reduce((n, pid) => n + 2 + (captureFiles(state.posts.find((p) => p.id === pid))?.media.length ?? 0), 0); + const bytes = files * 68; + const confirm = digest(ids); + const what = `the capture${ids.length === 1 ? "" : "s"} of ${ids.length} dropped post${ids.length === 1 ? "" : "s"}: ${files} file${files === 1 ? "" : "s"}, ${bytes} B`; + const agent = agentDropped ? ` ${agentDropped} post${agentDropped === 1 ? "" : "s"} an agent dropped ${agentDropped === 1 ? "is" : "are"} left alone: a purge takes the operator's drops only.` : ""; + const only = gone.length ? ` ${ids.length === 1 ? "It is" : `${gone.length} of them ${gone.length === 1 ? "is" : "are"}`} gone from the page: this is the only copy: X no longer showed this post at ${gone[0].at.slice(0, 10)} ${gone[0].at.slice(11, 16)} UTC; removing it cannot be undone.` : ""; + const again = ids.length - gone.length > 0 ? ` Keeping ${gone.length ? "the other one" : ids.length === 1 ? "it" : "one of them"} again captures it again.` : ""; + const answer = { ok: true, slug: state.slug, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, gone, agentDropped, skipped: [], confirm }; + if (body.dryRun === true) { + return { ...answer, dryRun: true, sentence: ids.length ? `Would remove ${what}. The judgements stay.${only}${again}${agent}` : `No post the operator dropped has a capture: nothing to remove.${agent}` }; + } + if (body.by !== "operator") return { ok: false, error: "Removing dropped posts' captures is the operator's press" }; + if (body.confirm !== confirm) return { ok: false, error: `The dropped posts with a capture have changed since the dry run (${ids.length} now): nothing was removed. Run the dry run again and confirm what it shows.` }; + state.captured = state.captured.filter((pid) => !ids.includes(pid)); + return { ...answer, dryRun: false, sentence: `Removed ${what}. The judgements stay.${agent}` }; +} + +/** The spec's door. True when answered. */ +export function trendingControl(req, res, url, { json, readBody }) { + if (url.pathname !== "/__stub/trending") return false; + if (req.method === "GET") { + req.resume(); + json(res, 200, { mode, requests, reads, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])) }); + return true; + } + readBody(req, (body) => { + if (body?.reset === true) { + state = libraryState(); + requests = []; + reads = 0; + jobs = 0; + mode = "ok"; + } + 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; + } + json(res, 200, { ok: true, mode }); + }); + return true; +} + +/** The editor's trending routes (behind the bearer). True when answered. */ +export function trendingRoute(req, res, url, { json, readBody, authorization }) { + if (!ROUTES.includes(url.pathname)) return false; + if (mode === "unreachable") { + req.socket.destroy(); + return true; + } + if (req.method === "GET" && url.pathname === "/api/ops/trending") { + req.resume(); + reads++; + if (!url.searchParams.has("slug")) { + const all = listing(new URLSearchParams({ detail: "1" })); + json(res, 200, { ok: true, libraries: mode === "none" ? [] : [{ slug: state.slug, name: state.name, topics: all.topics.length, posts: all.total, unjudged: all.topics.reduce((n, t) => n + t.counts.unjudged, 0) }] }); + return true; + } + if (mode === "none" || url.searchParams.get("slug") !== state.slug) { + json(res, 404, { ok: false, error: `No such channel: ${url.searchParams.get("slug")}` }); + return true; + } + const topic = url.searchParams.get("topic"); + if (topic && !state.topics.some((t) => t.id === topic)) { + json(res, 400, { ok: false, error: `${state.slug} has no topic "${topic}" (its topics: ${state.topics.map((t) => t.id).join(", ")})` }); + return true; + } + json(res, 200, listing(url.searchParams)); + return true; + } + if (req.method !== "POST") return false; + readBody(req, (body) => { + const action = url.pathname.slice("/api/ops/".length); + requests.push({ action, body, authorization }); + if (!body || body.slug !== state.slug) return json(res, 400, { ok: false, error: `${body?.slug} is not an X trending library` }); + const answer = action === "judge-trending" ? judge(body) : action === "watch-trending" ? watch(body) : purge(body); + json(res, answer.ok ? 200 : 400, answer); + }); + return true; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -17,6 +17,7 @@ import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; import { servicesControl, servicesRoute } from "./editor-stub-services.mjs"; +import { trendingControl, trendingRoute } from "./editor-stub-trending.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; @@ -1287,6 +1288,8 @@ const server = http.createServer((req, res) => { if (intakeControl(req, res, url, { json, readBody })) return; // The cookie alerts a spec puts up (editor-stub-services.mjs, needs-you.spec.ts). if (servicesControl(req, res, url, { json, readBody })) return; + // The Posts library's invented library (editor-stub-trending.mjs, library.spec.ts). + if (trendingControl(req, res, url, { json, readBody })) return; if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") { return readBody(req, (body) => { const mode = body?.mode ?? "ok"; @@ -1306,6 +1309,8 @@ const server = http.createServer((req, res) => { // The editor's cookie alerts and X's jar (editor-stub-services.mjs): the Inbox's X jar row reads them. if (servicesRoute(req, res, url, { json })) return; + // Lane posts-library: an X trending library's listing and its three presses (editor-stub-trending.mjs). + if (trendingRoute(req, res, url, { json, readBody, authorization: auth })) return; // UI notes items 13 and 16: a channel's counts, the focus, capture-posts (editor-stub-intake.mjs). if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return; // Release 38 lane C: a research case's verify, leads and evidence stages (editor-stub-case-stages.mjs). diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs @@ -0,0 +1,133 @@ +// What library.spec.ts judges (lane posts-library; the page /tools/library): +// an invented X trending library — two topics with watches, a third with none, +// a thread, a post gone from the page, dropped posts with captures — as the +// stub editor answers it (editor-stub-trending.mjs), and the few media files +// umtool's own media route serves from the fixture's corpus. +// +// The channel directory is made by the spec and removed after it +// (makeLibraryFixture / removeLibraryFixture), not by make-fixture.mjs: no +// other spec sees one more channel. Invented ids, handles and words; no real +// trending id, and nothing here is ever asked of X. +import { linkSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const LIB = "trending-lib"; +export const LIB_NAME = "Trending fixture"; +export const NOT_A_LIB = "testchan"; + +const id = (n) => `19000000000000${String(n).padStart(5, "0")}`; +export const P = { + opening: id(7001), + reply: id(7002), + gone: id(7003), + dropped: id(7004), + later: id(7005), + fresh: id(7006), + goneDropped: id(7007), + cup: id(7101), + cupDropped: id(7102), +}; + +const READ_1 = "2026-11-17T10:00:00.000Z"; +const READ_2 = "2026-11-17T11:00:00.000Z"; +const READ_3 = "2026-11-17T12:00:00.000Z"; + +// A 1×1 PNG and a few bytes that stand for a video (the route serves bytes; nothing decodes them). +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64"); +export const VIDEO_BYTES = Buffer.from("FAKE-TEST-VALUEghijklmnopqrstuvwxyz-library-fixture-video"); + +/** The captured files of each post: name → bytes. */ +export const CAPTURES = { + [P.opening]: { "shot.png": PNG, [`${P.opening}_1.jpg`]: PNG, [`${P.opening}_2.mp4`]: VIDEO_BYTES }, + [P.reply]: { "shot.png": PNG, "shot-thread.png": PNG }, + [P.dropped]: { "shot.png": PNG, [`${P.dropped}_1.jpg`]: PNG }, + [P.cupDropped]: { "shot.png": PNG }, + [P.goneDropped]: { "shot.png": PNG }, +}; + +/** The library's state as the stub editor starts with it (a fresh copy per call). */ +export function libraryState() { + const post = (pid, author, authorName, text, topic, firstSeenAt, extra = {}) => ({ id: pid, author, authorName, createdAt: "2026-11-16T12:00:00.000Z", text, url: `https://x.com/${author}/status/${pid}`, topic, thread: pid, firstSeenAt, mediaCount: 0, kinds: [], ...extra }); + return { + slug: LIB, + name: LIB_NAME, + topics: [ + { + id: "kettle-festival", + title: "Kettle festival", + watch: { on: true, intervalMinutes: 30, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: false, by: "operator", ticks: 2, failures: 0, nextSource: 0, goneSources: [], paused: { reason: "jar", since: READ_3, sentence: "X's cookie jar is 75 minutes old, past the watch's 60." } }, + }, + { + id: "cup-shortage", + title: "Cup shortage", + watch: { on: true, intervalMinutes: 60, startedAt: READ_1, until: "2026-11-19T10:00:00.000Z", shots: true, by: "agent", ticks: 5, failures: 3, nextSource: 0, goneSources: [], paused: { reason: "failing", since: READ_3, sentence: "The last read ended rate-limited." } }, + }, + { id: "lids", title: "Lids" }, + ], + posts: [ + post(P.opening, "teapot_news", "Teapot News", "The kettle festival opens today.", "kettle-festival", READ_1, { mediaCount: 2, kinds: ["image", "video"], capture: { at: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "ok" } }), + post(P.reply, "saucer_fan", "Saucer Fan", "A reply about spouts.", "kettle-festival", READ_1, { + thread: P.opening, + isReply: true, + replyTo: { platform: "twitter", id: P.opening, author: "teapot_news" }, + capture: { at: "2026-11-17T10:06:00.000Z", state: "captured", mediaState: "none" }, + context: { parent: { handle: "teapot_news", text: "The kettle festival opens today." } }, + }), + post(P.gone, "lid_watch", "Lid Watch", "A lid fell off a kettle.", "kettle-festival", READ_1, { gone: { at: READ_2, read: "tr-01JB0000000000000000000000", trendId: "1900000000000000001" } }), + post(P.dropped, "spout_co", "Spout Co", "Spouts are back in stock.", "kettle-festival", READ_1, { mediaCount: 1, kinds: ["image"], capture: { at: "2026-11-17T10:07:00.000Z", state: "captured", mediaState: "ok" } }), + post(P.later, "teapot_news", "Teapot News", "More on the kettle parade later.", "kettle-festival", READ_2), + post(P.fresh, "kettle_fan", "Kettle Fan", "Just arrived at the festival.", "kettle-festival", READ_3, { capture: { at: "2026-11-17T12:05:00.000Z", state: "deleted", mediaState: "skipped" } }), + post(P.cup, "cup_other", "Cup Other", "Cups are short this week.", "cup-shortage", READ_1), + // The operator dropped it, and the page no longer shows it: its capture is the only copy. + post(P.goneDropped, "lid_watch", "Lid Watch", "Lids, half price.", "lids", READ_1, { gone: { at: READ_2, read: "tr-01JB0000000000000000000000", trendId: "1900000000000000003" }, capture: { at: "2026-11-17T10:09:00.000Z", state: "captured", mediaState: "none" } }), + post(P.cupDropped, "cup_other", "Cup Other", "Buy my cups.", "cup-shortage", READ_1, { capture: { at: "2026-11-17T10:08:00.000Z", state: "captured", mediaState: "none" } }), + ], + judgements: { + posts: { + [P.dropped]: { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" }, + [P.later]: { state: "later", note: "check the source", by: "agent", at: "2026-11-17T12:31:00.000Z" }, + [P.cupDropped]: { state: "drop", by: "agent", at: "2026-11-17T12:32:00.000Z" }, + [P.goneDropped]: { state: "drop", by: "operator", at: "2026-11-17T12:33:00.000Z" }, + }, + threads: {}, + }, + // Posts whose capture is still on disk (a purge takes the dropped ones). + captured: Object.keys(CAPTURES), + }; +} + +const libDir = (channels) => path.join(channels, LIB); + +/** The library's channel in the fixture corpus: its marker and its captured files (a video as a hardlink to its blob). */ +export function makeLibraryFixture({ channels }) { + removeLibraryFixture({ channels }); + const dir = libDir(channels); + mkdirSync(path.join(dir, "trending", "media-store", "ab"), { recursive: true }); + mkdirSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000"), { recursive: true }); + writeFileSync(path.join(dir, "config.json"), JSON.stringify({ name: LIB_NAME, handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); + writeFileSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), PNG); + writeFileSync(path.join(dir, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: {}, threads: {} })); + for (const [pid, files] of Object.entries(CAPTURES)) { + const cap = path.join(dir, "trending", "posts-media", pid); + mkdirSync(cap, { recursive: true }); + writeFileSync(path.join(cap, "capture.json"), JSON.stringify({ version: 1, id: pid, state: "captured" })); + for (const [name, bytes] of Object.entries(files)) { + if (name.endsWith(".mp4")) { + const blob = path.join(dir, "trending", "media-store", "ab", `${pid}.mp4`); + writeFileSync(blob, bytes); + linkSync(blob, path.join(cap, name)); + } else writeFileSync(path.join(cap, name), bytes); + } + } + // A name planted in a capture whose real path is the raw read's page: never served. + symlinkSync(path.join(dir, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), path.join(dir, "trending", "posts-media", P.opening, "planted.png")); + // A channel that is no library, with a file of the same shape. + const other = path.join(channels, NOT_A_LIB, "trending", "posts-media", P.opening); + mkdirSync(other, { recursive: true }); + writeFileSync(path.join(other, "shot.png"), PNG); +} + +export function removeLibraryFixture({ channels }) { + rmSync(libDir(channels), { recursive: true, force: true }); + rmSync(path.join(channels, NOT_A_LIB, "trending"), { recursive: true, force: true }); +} diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts @@ -0,0 +1,626 @@ +import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { LIB, makeLibraryFixture, NOT_A_LIB, P, removeLibraryFixture, VIDEO_BYTES } from "./fixtures/library-fixture.mjs"; +import * as urls from "./urls"; +import { warm, WARM_TIMEOUT } from "./warm"; + +// --------------------------------------------------------------------------- +// THE POSTS LIBRARY (/tools/library; plans/x-trending.md slice 3, lane +// posts-library): a private X trending library browsed by topic and judged. +// +// The library is the STUB EDITOR's (e2e/fixtures/editor-stub-trending.mjs: an +// invented library in memory, every press recorded with the `by` it carried); +// its captured media are files in the fixture's corpus, served by umtool's own +// route. Nothing here reaches X, the live editor, or the operator's reports. +// WRITES the fixture's REPORTS_ROOT/.umtool/posts-library.json (Mark seen) and +// channels/trending-lib/ (made before, removed after). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const CHANNELS = path.join(FIXTURE, "channels"); +const SEEN = path.join(FIXTURE, ".umtool", "posts-library.json"); +const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`; +const KETTLES = "kettle-festival"; +const CUPS = "cup-shortage"; + +type Recorded = { action: string; body: Record<string, any>; authorization: string }; +type StubState = { requests: Recorded[]; reads: number; judgements: { posts: Record<string, any>; threads: Record<string, any> }; captured: string[]; watches: Record<string, any> }; + +const stub = async (request: APIRequestContext): Promise<StubState> => (await request.get(`${STUB}/__stub/trending`)).json(); +const reset = async (request: APIRequestContext, mode: "ok" | "unreachable" | "none" = "ok") => { + expect((await request.post(`${STUB}/__stub/trending`, { data: { reset: true, mode } })).status()).toBe(200); + rmSync(SEEN, { force: true }); +}; +const last = async (request: APIRequestContext) => (await stub(request)).requests.at(-1)!; +// What a browser puts on the page's own fetch, and a page cannot forge: the press routes take a press with them only. +const asPage = (baseURL: string | undefined) => ({ origin: new URL(baseURL!).origin, "sec-fetch-site": "same-origin" }); +const lib = (view: Record<string, unknown> = {}) => urls.postsLibraryHref({ lib: LIB, ...view }); +const post = (page: Page, id: string) => page.locator(`[data-library-post="${id}"]`); +const rail = (page: Page) => page.locator('[data-library-topics="rail"]'); +const status = (page: Page) => page.locator("[data-library-status]"); +const idle = (page: Page) => expect(page.locator("[data-library]")).toHaveAttribute("data-library-busy", "false"); +const shown = (page: Page) => page.locator("[data-library-post]").evaluateAll((els) => els.map((e) => e.getAttribute("data-library-post"))); + +async function open(page: Page, view: Record<string, unknown> = {}) { + await page.goto(lib(view)); + await expect(page.locator('[data-stream-filled="library"]')).toBeVisible({ timeout: 30_000 }); + // The presses are live once the page is (a button is disabled until then). + await expect(page.locator("[data-library-scope]")).toBeEnabled(); +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + makeLibraryFixture({ channels: CHANNELS }); + await warm(playwright, [urls.postsLibraryHref(), urls.toolsHref()]); +}); +test.afterAll(async ({ request }) => { + await reset(request); + removeLibraryFixture({ channels: CHANNELS }); +}); +test.beforeEach(async ({ request, page }) => { + await reset(request); + await page.setViewportSize({ width: 1366, height: 900 }); +}); + +test("the head is sent before the library, behind a placeholder of its shape", async ({ baseURL }) => { + const res = await fetch(baseURL + lib(), { headers: { "Accept-Encoding": "identity", Cookie: "e2e-stream-delay=1500" } }); + expect(res.status).toBe(200); + const html = await res.text(); + const filledAt = html.indexOf("data-stream-filled"); + expect(filledAt, "the library never streamed in").toBeGreaterThan(0); + const shell = html.slice(0, filledAt); + expect(shell).toContain("data-app-rail"); + expect(shell).toContain("Posts library"); + expect(shell).toContain('data-stream-skeleton="library"'); + expect(shell).not.toContain("data-library-post"); + expect(html.slice(filledAt)).toContain(`data-library-post="${P.opening}"`); +}); + +test("found from Tools; topics on the left with their counts and what each watch is doing", async ({ page }) => { + await page.goto(urls.toolsHref()); + await expect(page.locator("[data-tool-entry=library] a")).toHaveAttribute("href", urls.postsLibraryHref()); + await open(page); + + const kettles = rail(page).locator(`[data-library-topic="${KETTLES}"]`); + await expect(kettles).toContainText("Kettle festival"); + await expect(kettles.locator("[data-library-topic-posts]")).toHaveText("6"); + await expect(kettles.locator("[data-library-topic-unjudged]")).toHaveText("4"); + // A paused watch says why; a failing one is told apart. + await expect(kettles).toHaveAttribute("data-library-watch", "paused"); + await expect(kettles.locator("[data-library-topic-watch]")).toContainText("Watch paused · Watched every 30 min"); + await expect(kettles.locator("[data-library-topic-watch]")).toContainText("X's cookie jar is 75 minutes old"); + const cups = rail(page).locator(`[data-library-topic="${CUPS}"]`); + await expect(cups).toHaveAttribute("data-library-watch", "failing"); + await expect(cups.locator("[data-library-topic-watch]")).toContainText("Watch failing"); + await expect(rail(page).locator('[data-library-topic="lids"]')).toHaveAttribute("data-library-watch", "none"); + // Every topic's posts, 9 in all. + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "9"); + + await kettles.click(); + await expect(page).toHaveURL(new RegExp(`topic=${KETTLES}`)); + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "6"); + await expect(page.locator(`[data-library-panel="${KETTLES}"]`)).toContainText("6 posts · 4 unjudged · 0 kept · 1 dropped · 1 later"); + // It fits a desk without scrolling sideways. + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + // Nothing here offers a post to a project, a report or a site. + await expect(page.locator("[data-posts-library]").getByRole("button", { name: /add to|publish|cut|project|report/i })).toHaveCount(0); + await expect(page.locator("[data-posts-library]").getByRole("link", { name: /add to|publish/i })).toHaveCount(0); +}); + +test("a post is drawn with its captured media, its thread context, and the words for gone and for a capture's state", async ({ page }) => { + await open(page, { topic: KETTLES }); + const media = (id: string, name: string) => `/api/library/media/${LIB}/${id}/${name}`; + + // The opening post: the archive viewer's body, with the screenshot, a picture and a video from umtool's media route. + const opening = post(page, P.opening); + await expect(opening.locator(`article[data-post-id="${P.opening}"]`)).toContainText("The kettle festival opens today."); + await expect(opening.locator("[data-post-capture-shot]")).toHaveAttribute("src", media(P.opening, "shot.png")); + await expect(opening.locator('[data-post-capture-media="image"] img')).toHaveAttribute("src", media(P.opening, `${P.opening}_1.jpg`)); + await expect(opening.locator('[data-post-capture-media="video"] video')).toHaveAttribute("src", media(P.opening, `${P.opening}_2.mp4`)); + // The picture really loads. + await expect.poll(() => opening.locator("[data-post-capture-shot]").evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0)).toBe(true); + await expect(opening.locator("[data-library-capture]")).toHaveText("capture: captured at 17 Nov 2026, 10:05 UTC"); + + // The reply: what it answers, as its capture read it, and the thread shot. + const reply = post(page, P.reply); + await expect(reply.locator('[data-library-context="parent"]')).toHaveText("In answer to @teapot_news: The kettle festival opens today."); + await expect(reply.locator("[data-library-thread]")).toHaveText("in a thread"); + await expect(reply.locator("[data-library-thread-shot] img")).toHaveAttribute("src", media(P.reply, "shot-thread.png")); + + // Gone from the page, in those words; a capture's own state verbatim. + await expect(post(page, P.gone).locator("[data-library-gone]")).toHaveText("Gone from the page at 17 Nov 2026, 11:00 UTC"); + await expect(post(page, P.fresh).locator("[data-library-capture]")).toHaveText("capture: deleted at 17 Nov 2026, 12:05 UTC"); + // No post is called deleted: the only place the word may stand is a capture's recorded state. + const text = await page.locator("[data-library-posts]").innerText(); + expect(text.match(/deleted/gi) ?? []).toHaveLength(1); + expect(await page.locator("[data-library-gone]").allInnerTexts()).toEqual(["Gone from the page at 17 Nov 2026, 11:00 UTC"]); + + // Judgements already there: whose, and the note. + await expect(post(page, P.dropped)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.dropped).locator("[data-library-by]")).toContainText("by the operator"); + await expect(post(page, P.later).locator("[data-library-by]")).toContainText("by the agent"); + await expect(post(page, P.later).locator("[data-library-note]")).toHaveText("Note: check the source"); +}); + +test("keep, drop, later and clear are the editor's judge-trending, as the operator; a thread, a note, and undo of the last press", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + await expect(status(page)).toHaveText("1 judgement kept. 1 post queued for archiving (the editor's capture job stub-capture-1)."); + let r = await last(request); + expect(r.action).toBe("judge-trending"); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "keep" }] }); + expect(r.authorization).toBe("Bearer umtool-e2e-token"); + await expect(post(page, P.opening).locator("[data-library-by]")).toContainText("by the operator"); + await idle(page); + + // Undo: its own entry removed, nothing archived, and the bar says what undo does not do. + await expect(page.locator("[data-library-undo-says]")).toHaveText("Undo puts the judgements back, written as the operator's whoever wrote them before. It does not cancel a capture already queued."); + await page.locator("[data-library-undo]").click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "unjudged"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "undecided" }], archive: false }); + await expect(status(page)).toContainText("Undone: 1 judgement put back."); + await expect(page.locator("[data-library-undo]")).toBeDisabled(); + await idle(page); + + // The whole thread: the reply's Drop judges the thread's root, and both posts read dropped. + await page.locator("[data-library-scope]").click(); + await expect(page.locator("[data-library-scope]")).toHaveAttribute("data-library-scope", "thread"); + await post(page, P.reply).locator('[data-library-press="drop"]').click(); + await expect(post(page, P.reply)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "drop"); + await expect(post(page, P.reply).locator("[data-library-by]")).toContainText("from its thread"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, by: "operator", set: [{ thread: P.opening, state: "drop" }] }); + await idle(page); + // Clear the thread's. + await post(page, P.reply).locator('[data-library-press="clear"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "unjudged"); + expect((await last(request)).body.set).toEqual([{ thread: P.opening, state: "undecided" }]); + await idle(page); + await page.locator("[data-library-scope]").click(); + + // A note goes with a judgement. + await post(page, P.gone).locator('[data-library-press="note"]').click(); + await post(page, P.gone).locator("[data-library-note-editor] textarea").fill("left the page within the hour"); + await post(page, P.gone).locator('[data-library-note-save="later"]').click(); + await expect(post(page, P.gone).locator("[data-library-note]")).toHaveText("Note: left the page within the hour"); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.gone, state: "later", note: "left the page within the hour" }] }); + await idle(page); + // Undo puts back what was there: nothing. + await page.locator("[data-library-undo]").click(); + await expect(post(page, P.gone)).toHaveAttribute("data-library-judgement", "unjudged"); + // Every press of this test was the operator's. + expect((await stub(request)).requests.every((x) => x.body.by === "operator")).toBe(true); +}); + +test("the keys: j and k move, a d l c judge, x selects, u undoes, ? lists them, Shift asks before a bulk press", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const focused = () => page.locator('[data-library-focus="true"]').getAttribute("data-library-post"); + const order = await shown(page); + expect(await focused()).toBe(order[0]); + await page.keyboard.press("j"); + expect(await focused()).toBe(order[1]); + await page.keyboard.press("j"); + await page.keyboard.press("k"); + expect(await focused()).toBe(order[1]); + + await page.keyboard.press("a"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "keep"); + expect((await last(request)).body.set).toEqual([{ id: order[1], state: "keep" }]); + await idle(page); + await page.keyboard.press("d"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "drop"); + await idle(page); + await page.keyboard.press("l"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "later"); + await idle(page); + // u: back to what it was before the last press (drop). + await page.keyboard.press("u"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "drop"); + expect((await last(request)).body).toMatchObject({ archive: false, by: "operator", set: [{ id: order[1], state: "drop" }] }); + await idle(page); + await page.keyboard.press("c"); + await expect(post(page, order[1]!)).toHaveAttribute("data-library-judgement", "unjudged"); + await idle(page); + + // x selects; with a selection a press judges the selected posts. + await page.keyboard.press("x"); + await page.keyboard.press("j"); + await page.keyboard.press("x"); + await expect(page.locator("[data-library-selected]")).toHaveAttribute("data-library-selected", "2"); + await page.keyboard.press("l"); + await expect(post(page, order[2]!)).toHaveAttribute("data-library-judgement", "later"); + expect((await last(request)).body.set).toEqual([{ id: order[1], state: "later" }, { id: order[2], state: "later" }]); + await idle(page); + + // t: the scope; ?: the list; typing in the search box presses nothing. + await page.keyboard.press("t"); + await expect(page.locator("[data-library-scope]")).toHaveAttribute("data-library-scope", "thread"); + await page.keyboard.press("t"); + await page.keyboard.press("?"); + await expect(page.locator("[data-library-help]")).toContainText("keep everything in the filter"); + await expect(page.locator("[data-library-help] kbd").first()).toHaveText("j"); + const before = (await stub(request)).requests.length; + await page.keyboard.press("/"); + await expect(page.locator("[data-library-search]")).toBeFocused(); + await page.keyboard.type("ad"); + expect((await stub(request)).requests.length).toBe(before); + await page.locator("[data-library-search]").fill(""); + await page.locator("[data-library-search]").blur(); + + // Shift+D asks first, with the count; Escape leaves it. + await page.keyboard.press("Shift+D"); + await expect(page.locator('[data-library-confirm="drop"] [data-library-confirm-count]')).toHaveText("6"); + await page.keyboard.press("Escape"); + await expect(page.locator("[data-library-confirm]")).toHaveCount(0); + expect((await stub(request)).requests.length).toBe(before); +}); + +test("the filters: unjudged, kept, dropped, later, gone, has media, by author, search, and new since Mark seen", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const only = async (expected: string[]) => { + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", String(expected.length)); + expect((await shown(page)).sort()).toEqual([...expected].sort()); + }; + await page.locator('[data-library-state="unjudged"]').click(); + await only([P.opening, P.reply, P.gone, P.fresh]); + await page.locator('[data-library-state="drop"]').click(); + await only([P.dropped]); + await page.locator('[data-library-state="later"]').click(); + await only([P.later]); + await page.locator('[data-library-state="keep"]').click(); + await only([]); + await expect(page.locator("[data-library-count]")).toHaveText("No post kept in “Kettle festival”."); + await page.locator('[data-library-state="all"]').click(); + await only([P.opening, P.reply, P.gone, P.dropped, P.later, P.fresh]); + + await page.locator('[data-library-toggle="gone"]').click(); + await only([P.gone]); + await page.locator('[data-library-toggle="gone"]').click(); + await page.locator('[data-library-toggle="media"]').click(); + await only([P.opening, P.dropped]); + await page.locator('[data-library-toggle="media"]').click(); + await only([P.opening, P.reply, P.gone, P.dropped, P.later, P.fresh]); + + await page.locator("[data-library-author]").selectOption("teapot_news"); + await only([P.opening, P.later]); + await page.locator("[data-library-author]").selectOption(""); + await page.locator("[data-library-search]").fill("LID kettle"); + await page.locator("[data-library-search]").press("Enter"); + await only([P.gone]); + await expect(page).toHaveURL(/q=LID\+kettle/); + await expect(page).toHaveURL(new RegExp(`topic=${KETTLES}`)); + + // New: never marked, every post is new. Marked seen before the last read: the one post that read first showed. + await open(page, { topic: KETTLES }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("6"); + mkdirSync(path.dirname(SEEN), { recursive: true }); + writeFileSync(SEEN, JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { [LIB]: { topics: { [KETTLES]: { seenAt: "2026-11-17T11:30:00.000Z" } } } } })); + await open(page, { topic: KETTLES }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("1"); + await page.locator('[data-library-toggle="new"]').click(); + await only([P.fresh]); + await expect(page.locator("[data-library-seen-at]")).toHaveText("marked seen 17 Nov 2026, 11:30 UTC"); + + // Mark seen is the only thing that moves it: after the press nothing is new. + await page.locator("[data-library-seen]").click(); + await expect(status(page)).toContainText("“Kettle festival” marked seen"); + await only([]); + const doc = JSON.parse(readFileSync(SEEN, "utf8")); + expect(doc.libraries[LIB].topics[KETTLES].previous).toBe("2026-11-17T11:30:00.000Z"); + expect(Date.parse(doc.libraries[LIB].topics[KETTLES].seenAt)).toBeGreaterThan(Date.parse("2026-11-18T00:00:00.000Z")); + // Marking seen asked the editor for nothing but reads. + expect((await stub(request)).requests).toEqual([]); +}); + +test("bulk over the filter: the confirm states the count and that keeps archive through the paced capture job; one ask, one job; undo puts all back", async ({ page, request }) => { + await open(page, { topic: KETTLES, state: "unjudged" }); + await page.locator('[data-library-bulk="keep"]').click(); + const confirm = page.locator('[data-library-confirm="keep"]'); + await expect(confirm.locator("[data-library-confirm-count]")).toHaveText("4"); + await expect(confirm).toContainText("Keep all 4 posts (unjudged) in “Kettle festival”?"); + await expect(confirm).toContainText("Each keep archives the post's screenshot and media through the editor's paced capture job: one job per 500 posts, never one per post."); + expect((await stub(request)).requests).toEqual([]); + await confirm.locator("[data-library-confirm-yes]").click(); + await expect(status(page)).toHaveText("4 judgements kept. 4 posts queued for archiving (the editor's capture job stub-capture-1)."); + const all = (await stub(request)).requests; + // ONE judge ask for the four posts: one capture job, not four. + expect(all).toHaveLength(1); + expect(all[0].body.by).toBe("operator"); + expect(all[0].body.set.map((s: { id: string }) => s.id).sort()).toEqual([P.opening, P.reply, P.gone, P.fresh].sort()); + expect(all[0].body.set.every((s: { state: string }) => s.state === "keep")).toBe(true); + // The unjudged filter is now empty. + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "0"); + await idle(page); + + await page.locator("[data-library-undo]").click(); + await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "4"); + const undo = await last(request); + expect(undo.body.archive).toBe(false); + expect(undo.body.set).toHaveLength(4); + expect(undo.body.set.every((s: { state: string }) => s.state === "undecided")).toBe(true); + expect((await stub(request)).judgements.posts[P.opening]).toBeUndefined(); +}); + +test("the watch: why it is paused, that only the operator restarts a failing one, and the switch with its terms", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + const panel = page.locator("[data-library-watch-panel]"); + await expect(panel).toHaveAttribute("data-library-watch-panel", "paused"); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Paused: X's cookie jar is 75 minutes old, past the watch's 60."); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Refresh cookies in the editor, on /cookies"); + + await open(page, { topic: CUPS }); + await expect(panel).toHaveAttribute("data-library-watch-panel", "failing"); + await expect(panel.locator("[data-library-watch-why]")).toContainText("Only the operator restarts a failing watch: press Watch again."); + await panel.locator("[data-library-watch-interval]").fill("45"); + await panel.locator("[data-library-watch-hours]").fill("24"); + await panel.locator("[data-library-watch-on]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); + let r = await last(request); + expect(r.action).toBe("watch-trending"); + expect(r.body).toEqual({ slug: LIB, topic: CUPS, on: true, intervalMinutes: 45, hours: 24, shots: true, by: "operator" }); + await expect(panel.locator("[data-library-watch-sentence]")).toContainText("Watched every 45 min"); + await expect(rail(page).locator(`[data-library-topic="${CUPS}"]`)).toHaveAttribute("data-library-watch", "on"); + await idle(page); + + await panel.locator("[data-library-watch-off]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "ended"); + r = await last(request); + expect(r.body).toEqual({ slug: LIB, topic: CUPS, on: false, by: "operator" }); + + // A topic never watched: Watch, with "screenshot everything new". + await open(page, { topic: "lids" }); + await expect(panel).toHaveAttribute("data-library-watch-panel", "none"); + await expect(panel.locator("[data-library-watch-sentence]")).toHaveText("Not watched."); + await panel.locator("[data-library-watch-shots]").check(); + await panel.locator("[data-library-watch-on]").click(); + await expect(panel).toHaveAttribute("data-library-watch-panel", "on"); + expect((await last(request)).body).toEqual({ slug: LIB, topic: "lids", on: true, shots: true, by: "operator" }); +}); + +test("purge of the operator's dropped posts' captures: two presses, the first saying what would go and what is true of it; the undo memory goes with it", async ({ page, request }) => { + await open(page, { topic: KETTLES }); + // A keep first: there is something to undo. + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + await idle(page); + await expect(page.locator("[data-library-undo]")).toBeEnabled(); + + await page.locator("[data-library-purge]").click(); + const plan = page.locator("[data-library-purge-plan]"); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay. Keeping it again captures it again."); + await expect(plan.locator("[data-library-purge-numbers]")).toHaveText("1 to remove · 0 of them gone from the page · 0 dropped by an agent, left alone"); + let r = await last(request); + expect(r.action).toBe("purge-trending"); + expect(r.body).toEqual({ slug: LIB, topic: KETTLES, dryRun: true, by: "operator" }); + // Nothing removed yet. + expect((await stub(request)).captured).toContain(P.dropped); + await idle(page); + + await plan.locator("[data-library-purge-yes]").click(); + await expect(status(page)).toHaveText("Removed the capture of 1 dropped post: 3 files, 204 B. The judgements stay."); + r = await last(request); + expect(r.body.by).toBe("operator"); + expect(r.body.topic).toBe(KETTLES); + expect(r.body.confirm).toMatch(/^[0-9a-f]{16}$/); + expect(r.body.dryRun).toBeUndefined(); + const after = await stub(request); + expect(after.captured).not.toContain(P.dropped); + expect(after.judgements.posts[P.dropped].state).toBe("drop"); + await expect(post(page, P.dropped)).toHaveAttribute("data-library-judgement", "drop"); + // S2: a purge takes the undo memory: the keep before it can no longer be undone from here. + await expect(page.locator("[data-library-undo]")).toBeDisabled(); + const asked = (await stub(request)).requests.length; + await page.keyboard.press("u"); + await expect(status(page)).toHaveText("Nothing to undo."); + expect((await stub(request)).requests.length).toBe(asked); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + await idle(page); + + // Again: nothing to remove, and no removal is offered. + await page.locator("[data-library-purge]").click(); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No post the operator dropped has a capture: nothing to remove."); + await expect(plan.locator("[data-library-purge-yes]")).toHaveCount(0); + await plan.locator("[data-library-purge-no]").click(); + + // S1: an AGENT's drop is never purged: it is counted and left, and nothing is offered. + await open(page, { topic: CUPS }); + await page.locator("[data-library-purge]").click(); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No post the operator dropped has a capture: nothing to remove. 1 post an agent dropped is left alone: a purge takes the operator's drops only."); + await expect(plan.locator("[data-library-purge-yes]")).toHaveCount(0); + await plan.locator("[data-library-purge-no]").click(); + expect((await stub(request)).captured).toContain(P.cupDropped); + + // S1: a dropped post gone from the page: the capture is the only copy, and nothing promises it back. + await open(page, { topic: "lids" }); + await page.locator("[data-library-purge]").click(); + await expect(plan.locator("[data-library-purge-sentence]")).toHaveText( + "Would remove the capture of 1 dropped post: 2 files, 136 B. The judgements stay. It is gone from the page: this is the only copy: X no longer showed this post at 2026-11-17 11:00 UTC; removing it cannot be undone.", + ); + await expect(plan.locator("[data-library-purge-numbers]")).toHaveText("1 to remove · 1 of them gone from the page · 0 dropped by an agent, left alone"); + await expect(plan).not.toContainText("captures it again"); + // Cancel after a dry run removes nothing. + await plan.locator("[data-library-purge-no]").click(); + expect((await stub(request)).captured).toContain(P.goneDropped); +}); + +test("the media route serves a library's captured pictures and videos, and nothing else", async ({ request }) => { + const at = (l: string, id: string, name: string) => `/api/library/media/${l}/${id}/${name}`; + const shot = await request.get(at(LIB, P.opening, "shot.png")); + expect(shot.status()).toBe(200); + expect(shot.headers()["content-type"]).toBe("image/png"); + expect(shot.headers()["cache-control"]).toBe("private, no-store"); + expect(shot.headers()["cross-origin-resource-policy"]).toBe("same-origin"); + // A video, by byte range. + const part = await request.get(at(LIB, P.opening, `${P.opening}_2.mp4`), { headers: { range: "bytes=0-9" } }); + expect(part.status()).toBe(206); + expect(part.headers()["content-range"]).toBe(`bytes 0-9/${VIDEO_BYTES.length}`); + expect((await part.body()).toString()).toBe(VIDEO_BYTES.subarray(0, 10).toString()); + const head = await request.head(at(LIB, P.opening, "shot.png")); + expect(head.status()).toBe(200); + + // The record, a name whose real path is the raw read, a traversal, an id that is no id: never. + for (const [l, id, name] of [ + [LIB, P.opening, "capture.json"], + [LIB, P.opening, "planted.png"], + [LIB, P.opening, "missing.png"], + [LIB, "..", "judgements.json"], + [LIB, "reads", "page.png"], + [LIB, P.opening, "..%2F..%2Fjudgements.json"], + [LIB, P.opening, "%2E%2E"], + // A channel that is no library, with a file of the same shape on disk. + [NOT_A_LIB, P.opening, "shot.png"], + ["nope", P.opening, "shot.png"], + ]) { + const res = await request.get(at(l, id, name)); + expect([400, 404], `${l}/${id}/${name} answered ${res.status()}`).toContain(res.status()); + } + expect(existsSync(path.join(CHANNELS, NOT_A_LIB, "trending", "posts-media", P.opening, "shot.png"))).toBe(true); + // It lists nothing: no directory, no index. + for (const dir of [`/api/library/media/${LIB}/${P.opening}`, `/api/library/media/${LIB}`, "/api/library/media"]) { + expect((await request.get(dir)).status(), dir).toBe(404); + } + // Another site's page cannot fetch it. + expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403); + expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "same-origin" } })).status()).toBe(200); + // A range that cannot be met keeps the route's private headers. + const beyond = await request.get(at(LIB, P.opening, `${P.opening}_2.mp4`), { headers: { range: "bytes=999999-" } }); + expect(beyond.status()).toBe(416); + expect(beyond.headers()["cache-control"]).toBe("private, no-store"); + expect(beyond.headers()["cross-origin-resource-policy"]).toBe("same-origin"); + expect(beyond.headers()["content-range"]).toBe(`bytes */${VIDEO_BYTES.length}`); + // Read only. + expect([404, 405]).toContain((await request.post(at(LIB, P.opening, "shot.png"), { data: {} })).status()); +}); + +test("the press routes take a press from umtool's own page only: stamped the operator's whatever the body says; a request no browser sent is not the operator", async ({ request, baseURL }) => { + const page = asPage(baseURL); + // The page's fetch, with a body that claims to be an agent: not read. + const judged = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, by: "agent", set: [{ id: P.cup, state: "later", by: "agent" }] } }); + expect(judged.status()).toBe(200); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.cup, state: "later" }] }); + expect((await request.post("/api/library/watch", { headers: page, data: { lib: LIB, topic: "lids", on: true, by: "agent" } })).status()).toBe(200); + expect((await last(request)).body.by).toBe("operator"); + expect((await request.post("/api/library/purge", { headers: page, data: { lib: LIB, dryRun: true, by: "agent" } })).status()).toBe(200); + expect((await last(request)).body.by).toBe("operator"); + + // M1: A HEADERLESS POST (curl, a script, an agent with no bearer) IS NOT THE OPERATOR: refused on all four, + // the dry run and its confirm included, and nothing reaches the editor or umtool's state. + const before = (await stub(request)).requests.length; + const bodies: Record<string, unknown> = { + judge: { lib: LIB, set: [{ id: P.cup, state: "keep" }] }, + watch: { lib: LIB, topic: "lids", on: false }, + purge: { lib: LIB, dryRun: true }, + seen: { lib: LIB, topics: ["lids"] }, + }; + for (const [route, data] of Object.entries(bodies)) { + for (const headers of [{}, { authorization: "Bearer umtool-e2e-token" }, { ...page, authorization: "Bearer umtool-e2e-token" }, { origin: "https://example.org", "sec-fetch-site": "cross-site" }] as Record<string, string>[]) { + const res = await request.post(`/api/library/${route}`, { headers, data }); + expect(res.status(), `${route} ${JSON.stringify(headers)}`).toBe(403); + if (!headers.origin || headers.authorization) expect((await res.json()).error).toContain("pnpm ops judge-trending"); + } + } + const confirm = await request.post("/api/library/purge", { data: { lib: LIB, confirm: "FAKE-TEST-VALUE" } }); + expect(confirm.status()).toBe(403); + expect((await stub(request)).requests.length).toBe(before); + expect(existsSync(SEEN)).toBe(false); + + // Mark seen, from the page: the library and the topic are checked through the editor first. + const ghost = await request.post("/api/library/seen", { headers: page, data: { lib: LIB, topics: ["lids", "spoons"] } }); + expect(ghost.status()).toBe(404); + expect((await ghost.json()).error).toContain('has no topic "spoons": nothing was marked'); + expect((await request.post("/api/library/seen", { headers: page, data: { lib: "nope", topics: ["lids"] } })).status()).toBe(404); + expect(existsSync(SEEN)).toBe(false); + expect((await request.post("/api/library/seen", { headers: page, data: { lib: LIB, topics: ["lids"] } })).status()).toBe(200); + expect(Object.keys(JSON.parse(readFileSync(SEEN, "utf8")).libraries[LIB].topics)).toEqual(["lids"]); + + // The page's own read, asked again after a press: the view's rows, to umtool's own pages only. + const read = await request.get(`/api/library?lib=${LIB}&topic=${KETTLES}&state=drop`); + expect(read.status()).toBe(200); + expect(read.headers()["cache-control"]).toBe("private, no-store"); + const rows = await read.json(); + expect(rows.ok).toBe(true); + expect(rows.posts.map((p: { id: string }) => p.id)).toEqual([P.dropped]); + expect((await request.get(`/api/library?lib=${LIB}`, { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403); + + // Ill-shaped: refused here with a sentence, the editor not asked. + const bad = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, set: [{ id: "../x", state: "keep" }] } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toContain("not a post id"); + // A bulk press whose count is stale judges nothing. + const stale = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, bulk: { view: { topic: KETTLES, state: "unjudged" }, state: "drop" }, expect: 99 } }); + expect(stale.status()).toBe(409); + expect((await stale.json()).error).toContain("nothing was judged"); + expect((await stub(request)).requests.filter((x) => x.action === "judge-trending").length).toBe(1); +}); + +test("S5: one view is two reads of the editor, whatever the number of topics and marks; so is the read after a press", async ({ page, request }) => { + // Every topic marked seen: the new counts still come in the one listing read. + mkdirSync(path.dirname(SEEN), { recursive: true }); + const seenAt = "2026-11-17T11:30:00.000Z"; + writeFileSync(SEEN, JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { [LIB]: { topics: { [KETTLES]: { seenAt }, [CUPS]: { seenAt }, lids: { seenAt } } } } })); + await request.post(`${STUB}/__stub/trending`, { data: { mode: "ok" } }); + const before = (await stub(request)).reads; + await open(page, { topic: KETTLES }); + await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("1"); + await expect(rail(page).locator(`[data-library-topic="${CUPS}"] [data-library-topic-new]`)).toHaveCount(0); + await idle(page); + expect((await stub(request)).reads - before).toBe(2); + // A press: the press itself, then the view read again: two reads more. + await post(page, P.gone).locator('[data-library-press="later"]').click(); + await expect(post(page, P.gone)).toHaveAttribute("data-library-judgement", "later"); + await idle(page); + await expect(page.locator(`[data-library-panel="${KETTLES}"]`)).toContainText("3 unjudged"); + expect((await stub(request)).reads - before).toBe(4); +}); + +test("on a phone (360 px): nothing pushes the page sideways, the topics fold, and a press works", async ({ page, request }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await open(page, { topic: KETTLES }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await expect(rail(page)).toBeHidden(); + const fold = page.locator('[data-library-topics="fold"]'); + await expect(fold.locator("summary")).toHaveText("Topics · Kettle festival"); + await fold.locator("summary").click(); + await expect(fold.locator(`[data-library-topic="${CUPS}"]`)).toBeVisible(); + await fold.locator("summary").click(); + + await post(page, P.opening).locator('[data-library-press="keep"]').click(); + await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep"); + expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.opening, state: "keep" }] }); + // The bar and the watch panel fit too. + await expect(page.locator("[data-library-bar]")).toBeVisible(); + for (const sel of ["[data-library-bar]", "[data-library-panel]", "[data-library-filters]", `[data-library-post="${P.opening}"]`]) { + const box = (await page.locator(sel).first().boundingBox())!; + expect(box.x, sel).toBeGreaterThanOrEqual(-1); + expect(box.x + box.width, sel).toBeLessThanOrEqual(361); + } + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true); + await page.screenshot({ path: test.info().outputPath("library-360.png"), fullPage: true }); +}); + +test("with the editor down, or holding no library, the page says so in a sentence", async ({ page, request }) => { + await reset(request, "unreachable"); + await page.goto(lib()); + const gone = page.locator("[data-library-unavailable]"); + await expect(gone).toHaveAttribute("data-library-unavailable", "unreachable", { timeout: 30_000 }); + await expect(gone).toContainText("The editor is not answering at"); + await expect(gone).toContainText("The library is read and judged through the editor: start it, then reload."); + await expect(page.locator("[data-library-post]")).toHaveCount(0); + // The shell is whole. + await expect(page.locator("[data-app-rail]")).toBeVisible(); + + await reset(request, "none"); + await page.goto(lib()); + await expect(gone).toHaveAttribute("data-library-unavailable", "no-library"); + await expect(gone).toContainText("The editor has no X trending library."); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -706,6 +706,30 @@ export const GROUPS = [ ], }, { + cmd: "library", + usage: [ + " umtool library [ls] | topics <lib> | posts <lib> [--topic T] [--state S] [--gone] [--media] [--author H] [--q TEXT]", + " [--new] [--limit N] [--offset N] [--json] a private X trending library, read through the editor", + " judge <lib> --state keep|drop|later|undecided (--id ID,… | --thread ID,… | --filter [--where S] …", + " (--dry-run | --yes)) [--note T] [--no-archive] [--by agent|operator]", + " watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", + " purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", + " seen <lib> (<topic>… | --all) --by operator Mark seen: what --new counts from", + ], + docs: [ + ["`library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]`", + "the **Posts library** ([tools.md](tools.md#posts-library-toolslibrary)) from a shell: the editor's X trending libraries, a library's topics (posts, unjudged, new since Mark seen, what its watch is doing) and its posts under the page's filters — `--state unjudged\\|keep\\|drop\\|later` is the judgement in force, `--gone` gone from the page, `--media` carrying media, `--author` one account, `--q` every word, `--new` first shown since the topic's Mark seen (with `--topic`). Read THROUGH THE EDITOR (`GET /api/ops/trending`): umtool opens no file of a library. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL"], + ["`library judge <lib> --state keep\\|drop\\|later\\|undecided (--id ID,… \\| --thread ID,… \\| --filter [--where S] [filters] (--dry-run \\| --yes)) [--note T] [--no-archive] [--by agent\\|operator]`", + "the editor's `judge-trending`: posts by id, threads by their root post's id, or every post a filter matches (`--where` the judgement they hold now; `--dry-run` counts, and without `--yes` nothing is judged, **exit 1**), at most 500 per ask — a keep's archiving is ONE paced capture job per ask, never one per post (`--no-archive` marks only). **`--by` is `agent` unless told**: an agent's judgement is a suggestion and never replaces the operator's (skipped, by name); the page's presses are the operator's"], + ["`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**)"], + ], + }, + { cmd: "pool", usage: [ " umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -351,6 +351,14 @@ export const VERBS = Object.freeze([ form("render-mode on", "corpus", "render mode: a render gets the machine, for a window", [opt("--for", { help: "90m, 2h (default 2h)" }), opt("--note")]), form("render-mode off", "corpus", "render mode off", [bool("--force", "even while a render holds it")], { confirm: { what: "take render mode from the render that holds it", when: ["--force"] } }), form("render-mode status", "corpus", "is render mode on, for what, until when", []), + none("library ls", "corpus", "the editor's X trending libraries", "a read the Posts library page (/tools/library) shows"), + none("library topics", "corpus", "a trending library's topics: posts, unjudged, new, the watch", "a read the Posts library page (/tools/library) shows"), + none("library posts", "corpus", "a trending library's posts, filtered", "a read the Posts library page (/tools/library) shows"), + none("library judge", "corpus", "keep, drop or later posts of a trending library (the editor's judge-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library watch", "corpus", "watch a topic of a trending library, or stop (the editor's watch-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library purge", "corpus", "remove dropped posts' captures, after a dry run (the editor's purge-trending)", "the removal is the operator's press on the Posts library page (/tools/library), in two steps"), + none("library seen", "corpus", "mark topics of a trending library seen", "the Posts library page's Mark seen (/tools/library)"), + none("library help", "corpus", "the library verbs", "prints the usage"), form("pool stats", "corpus", "the render pool: what it holds", [opt("--since", { help: "7d" })], { shape: "pool stats" }), form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()], { confirm: { what: "delete render pool files past the cap", unless: ["--dry-run"] } }), form("pool verify", "corpus", "the render pool's files checked", [num("--sample"), bool("--all")], Q), diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs @@ -43,6 +43,7 @@ const SUBVERBS = [ { cmd: "candidates", file: "lib/report/candidatesCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g }, { cmd: "clips", file: "lib/report/reactions.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help"] }, { cmd: "pool", file: "lib/report/poolCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, + { cmd: "library", file: "lib/library/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "render-mode", file: "lib/report/renderMode.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "schedule", file: "bin/schedule.ts", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "storage", file: "bin/umtool.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, within: ["async function cmdStorage()", "async function cmdStorageDeliverables"] }, diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -19,6 +19,7 @@ // `node --test lib/hrefs.test.mjs` runs it without a bundler. // --------------------------------------------------------------------------- +import { libraryHref as libraryViewHref } from "./library/filters.mjs"; import { ARTICLES_KEY } from "./articles/key.mjs"; /** A query value; `undefined`, `null`, `false` and "" are left out. */ @@ -575,6 +576,11 @@ export function digestContextHref(): string { return "/tools/digest-context"; } +/** The Posts library (lane posts-library): a private trending library's topics and posts, judged. */ +export function postsLibraryHref(view: Parameters<typeof libraryViewHref>[0] = {}): string { + return libraryViewHref(view); +} + /** Every tool. */ export function toolsHref(): string { return "/tools"; diff --git a/umtool/lib/library/caller.mjs b/umtool/lib/library/caller.mjs @@ -0,0 +1,35 @@ +// WHO MAY PRESS (lane posts-library, review 1): the Posts library's press +// routes write every press as the OPERATOR's, so they take a press only from +// what the operator uses — umtool's own page, in a browser. +// +// A request is the page's when it carries what a browser sends and a page +// cannot forge (`Origin` on a write, `Sec-Fetch-Site` on every request: +// lib/report/writeGuard.mjs fromBrowser) AND is same-origin to a host that is +// this machine (lib/report/sameOrigin.mjs crossSiteRefusal). Anything else — +// curl, a script, an agent, the editor's server, with or without a bearer — +// is sent to the doors where a caller says who it is: `pnpm ops` and `umtool +// library`, whose `by` is "agent" unless told. +// +// The proxy's guard (umtool/proxy.ts) lets a request with neither header +// through on purpose (the CLI and the editor write other routes that way), so +// this is asked HERE, by every press route, before the body is read. +// +// Plain ESM. +import { crossSiteRefusal } from "../report/sameOrigin.mjs"; +import { fromBrowser } from "../report/writeGuard.mjs"; + +export const AGENTS_GO_ELSEWHERE = + "This route is the Posts library page's: its presses are written as the operator's, so it takes them from umtool's own page in a browser only. An agent or a script uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` or `umtool library`, and says \"by\": \"agent\"."; + +/** + * Why a request may not press, or null when it is the page's. + * @param {{ get(name: string): string | null }} headers + * @param {Record<string, string | undefined>} [env] + * @returns {{ status: 403, error: string } | null} + */ +export function pressRefusal(headers, env = process.env) { + if (headers.get("authorization") !== null) return { status: 403, error: AGENTS_GO_ELSEWHERE }; + if (!fromBrowser(headers)) return { status: 403, error: AGENTS_GO_ELSEWHERE }; + const cross = crossSiteRefusal(headers, env); + return cross ? { status: 403, error: cross } : null; +} diff --git a/umtool/lib/library/caller.test.mjs b/umtool/lib/library/caller.test.mjs @@ -0,0 +1,40 @@ +// Who may press the Posts library's routes (review 1, M1): umtool's own page +// in a browser, and nothing else — a request with no browser header is NOT +// the operator. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { AGENTS_GO_ELSEWHERE, pressRefusal } from "./caller.mjs"; + +const h = (o) => new Headers(o); +const ENV = {}; + +test("the page's own fetch presses: a same-origin browser request to this machine", () => { + assert.equal(pressRefusal(h({ host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin" }), ENV), null); + assert.equal(pressRefusal(h({ host: "127.0.0.1:3050", origin: "http://127.0.0.1:3050" }), ENV), null); + assert.equal(pressRefusal(h({ host: "localhost:3050", "sec-fetch-site": "same-origin" }), ENV), null); +}); + +test("a request no browser sent is not the operator: curl, a script, an agent, the editor — with a bearer or with nothing", () => { + for (const headers of [{}, { host: "localhost:3050" }, { host: "localhost:3050", "content-type": "application/json" }, { host: "localhost:3050", "user-agent": "curl/8" }]) { + assert.deepEqual(pressRefusal(h(headers), ENV), { status: 403, error: AGENTS_GO_ELSEWHERE }); + } + // A bearer is refused even from a browser-shaped request. + assert.deepEqual(pressRefusal(h({ host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin", authorization: "Bearer x" }), ENV), { status: 403, error: AGENTS_GO_ELSEWHERE }); + assert.match(AGENTS_GO_ELSEWHERE, /pnpm ops judge-trending/); + assert.match(AGENTS_GO_ELSEWHERE, /"by": "agent"/); +}); + +test("another site's page, a sibling site's, an opaque origin and a host that is not this machine are refused", () => { + for (const headers of [ + { host: "localhost:3050", origin: "https://example.org", "sec-fetch-site": "cross-site" }, + { host: "localhost:3050", origin: "http://localhost:3001", "sec-fetch-site": "same-site" }, + { host: "localhost:3050", origin: "null" }, + { host: "rebound.example.org", origin: "http://rebound.example.org", "sec-fetch-site": "same-origin" }, + ]) { + const no = pressRefusal(h(headers), ENV); + assert.equal(no?.status, 403, JSON.stringify(headers)); + assert.notEqual(no?.error, AGENTS_GO_ELSEWHERE); + } +}); diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -0,0 +1,215 @@ +// `umtool library …` (lane posts-library): the Posts library page's reads and +// presses from a shell, through the SAME calls (lib/library/client.mjs) to the +// editor — the listing, judge-trending, watch-trending, purge-trending — and +// Mark seen (lib/library/seen.mjs). umtool writes no file of a library and +// asks X nothing. +// +// WHO IS ASKING. `--by` is "agent" unless told otherwise, as `pnpm ops` is: an +// agent's judgement is a suggestion the operator's outranks, a failing watch is +// restarted only by the operator, and a purge's removal is the operator's +// (`--by operator`, with the `--confirm` its `--dry-run` printed). +// +// Needs the editor at ARCHILYZER_EDITOR_URL (default http://localhost:3001) and +// WORKER_TOKEN (else the editor's env files). Exit 1 on a refusal. +// +// Plain ESM. +import { agentToken } from "../annotations/agentAuth.mjs"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listLibraries, listLibrary, listLibraryIds, purge, watch } from "./client.mjs"; +import { markSeen, seenOf } from "./seen.mjs"; + +const VALUE_FLAGS = new Set(["--topic", "--state", "--author", "--q", "--limit", "--offset", "--id", "--thread", "--note", "--by", "--interval", "--hours", "--confirm", "--where"]); +const BOOL_FLAGS = new Set(["--json", "--gone", "--media", "--new", "--filter", "--yes", "--dry-run", "--no-archive", "--shots", "--all"]); + +export const LIBRARY_USAGE = [ + "umtool library [ls] [--json] the editor's X trending libraries", + "umtool library topics <lib> [--json] a library's topics: posts, unjudged, new, the watch", + "umtool library posts <lib> [--topic T] [--state unjudged|keep|drop|later] [--gone] [--media]", + " [--author H] [--q TEXT] [--new] [--limit N] [--offset N] [--json]", + "umtool library judge <lib> --state keep|drop|later|undecided (--id ID[,ID…] | --thread ID[,ID…] |", + " --filter [--where unjudged|keep|drop|later] [the posts filters] (--dry-run | --yes))", + " [--note TEXT] [--no-archive] [--by agent|operator]", + "umtool library watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", + "umtool library purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", + "umtool library seen <lib> (<topic>… | --all) --by operator Mark seen: what `--new` counts from (the operator's mark)", +].join("\n"); + +class Refusal extends Error {} + +function parse(args) { + const flags = {}; + const words = []; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + const eq = a.startsWith("--") && a.includes("=") ? a.indexOf("=") : -1; + const name = eq > 0 ? a.slice(0, eq) : a; + if (VALUE_FLAGS.has(name)) { + const v = eq > 0 ? a.slice(eq + 1) : args[++i]; + if (v === undefined) throw new Refusal(`${name} needs a value`); + flags[name] = v; + } else if (BOOL_FLAGS.has(name) && eq < 0) flags[name] = true; + else if (a.startsWith("--")) throw new Refusal(`library: unknown flag ${name}`); + else words.push(a); + } + return { flags, words }; +} + +const whole = (flags, name, min) => { + if (flags[name] === undefined) return undefined; + const n = Number(flags[name]); + if (!Number.isInteger(n) || n < min) throw new Refusal(`${name} is a whole number, ${min} or more`); + return n; +}; + +function byOf(flags) { + const by = flags["--by"] ?? "agent"; + if (by !== "agent" && by !== "operator") throw new Refusal(`--by is "agent" or "operator"`); + return by; +} + +const need = (lib) => { + if (!lib) throw new Refusal(`library: name the library (\`umtool library ls\` lists them)`); + return lib; +}; + +async function filterOf(flags, lib, reportsRoot) { + if (flags["--state"] !== undefined && !LIBRARY_STATES.includes(flags["--state"])) throw new Refusal(`the judgement to filter by is one of ${LIBRARY_STATES.join(", ")}`); + let since = null; + if (flags["--new"]) { + if (!flags["--topic"]) throw new Refusal("--new goes with --topic: each topic is marked seen on its own"); + since = (await seenOf(reportsRoot, lib))[flags["--topic"]] ?? null; + } + return { slug: lib, topic: flags["--topic"] ?? null, state: flags["--state"] ?? null, gone: !!flags["--gone"], media: !!flags["--media"], author: flags["--author"] ?? null, q: flags["--q"] ?? null, since }; +} + +const line = (p) => { + const j = p.judgement ? `${p.judgement.state}${p.judgement.from === "thread" ? " (thread)" : ""} by ${p.judgement.by}` : "unjudged"; + const gone = p.gone ? ` · gone from the page at ${p.gone.at}` : ""; + const capture = p.capture ? ` · capture: ${p.capture.state} at ${p.capture.at}` : ""; + return `${p.id} @${p.author} ${j}${gone}${capture}\n ${String(p.text).replace(/\s+/g, " ").slice(0, 160)}`; +}; + +/** + * @param {string[]} args what follows `library` + * @param {{ ask?: Function, out?: (s: string) => void, err?: (s: string) => void, reportsRoot?: string, env?: Record<string, string | undefined> }} [deps] + * @returns {Promise<number>} the exit code + */ +export async function libraryCommand(args, deps = {}) { + const out = deps.out ?? ((s) => console.log(s)); + const err = deps.err ?? ((s) => console.error(s)); + const env = deps.env ?? process.env; + const reportsRoot = deps.reportsRoot ?? REPORTS_ROOT; + const ask = deps.ask ?? editorAsker({ editorUrl: env.ARCHILYZER_EDITOR_URL ?? "http://localhost:3001", token: agentToken(env) }); + try { + const { flags, words } = parse(args); + const json = !!flags["--json"]; + const sub = words[0] ?? "ls"; + const lib = words[1]; + const say = (value, text) => out(json ? JSON.stringify(value, null, 2) : text); + + if (sub === "help") { + out(LIBRARY_USAGE); + return 0; + } + if (sub === "ls") { + const libraries = await listLibraries(ask); + say({ libraries }, libraries.length ? libraries.map((l) => `${l.slug} ${l.name} ${l.topics} topics · ${l.posts} posts · ${l.unjudged} unjudged`).join("\n") : "The editor has no X trending library."); + return 0; + } + if (sub === "topics") { + // One read: the topics, and each one's new posts from its Mark seen time. + const seen = await seenOf(reportsRoot, need(lib)); + const listing = await listLibrary(ask, { slug: lib, detail: true, limit: 1, seen }); + const topics = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts })); + say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); + return 0; + } + if (sub === "posts") { + const filter = await filterOf(flags, need(lib), reportsRoot); + const listing = await listLibrary(ask, { ...filter, limit: whole(flags, "--limit", 1) ?? 50, offset: whole(flags, "--offset", 0), detail: true }); + say({ slug: lib, total: listing.total, posts: listing.posts }, `${listing.total} post${listing.total === 1 ? "" : "s"}${listing.posts.length < listing.total ? ` (${listing.posts.length} shown)` : ""}\n${listing.posts.map(line).join("\n")}`.trimEnd()); + return 0; + } + if (sub === "judge") { + need(lib); + const state = flags["--state"]; + if (!JUDGE_STATES.includes(state)) throw new Refusal(`judge: --state is one of ${JUDGE_STATES.join(", ")}`); + const by = byOf(flags); + const ways = [flags["--id"] !== undefined, flags["--thread"] !== undefined, !!flags["--filter"]].filter(Boolean).length; + if (ways !== 1) throw new Refusal("judge: give --id, --thread or --filter, one of them"); + const note = flags["--note"] && state !== "undecided" ? { note: flags["--note"] } : {}; + let set; + if (flags["--filter"]) { + // --state is the judgement to WRITE; the posts' judgement now is --where. + const ids = await listLibraryIds(ask, { ...(await filterOf({ ...flags, "--state": flags["--where"] }, lib, reportsRoot)) }); + if (flags["--dry-run"] || !flags["--yes"]) { + say({ slug: lib, dryRun: true, state, posts: ids.length, ids }, `${ids.length} post${ids.length === 1 ? "" : "s"} would be judged ${state}${flags["--dry-run"] ? "" : " (--yes judges them)"}.`); + return flags["--dry-run"] ? 0 : 1; + } + set = ids.map((id) => ({ id, state, ...note })); + if (!set.length) { + say({ slug: lib, written: [], skipped: [], kept: [], archives: [] }, "No post matches: nothing judged."); + return 0; + } + } else { + const key = flags["--id"] !== undefined ? "id" : "thread"; + set = String(flags[`--${key}`]).split(",").map((s) => s.trim()).filter(Boolean).map((id) => ({ [key]: id, state, ...note })); + if (!set.length) throw new Refusal(`judge: --${key} names no post`); + } + const result = await judge(ask, { slug: lib, by, set, ...(flags["--no-archive"] ? { archive: false } : {}) }); + const skipped = result.skipped.map((s) => `\n skipped ${s.id ?? s.thread}: ${s.reason}`).join(""); + say({ slug: lib, by, ...result }, `${result.written.length} judgement${result.written.length === 1 ? "" : "s"} written as the ${by}'s.${skipped}${archiveSentence(result) ? `\n${archiveSentence(result)}` : ""}`); + return 0; + } + if (sub === "watch") { + need(lib); + const [topic, to] = [words[2], words[3]]; + if (!topic || (to !== "on" && to !== "off")) throw new Refusal("watch: umtool library watch <lib> <topic> on|off"); + const interval = whole(flags, "--interval", 1); + const hours = whole(flags, "--hours", 1); + const result = await watch(ask, { + slug: lib, + topic, + on: to === "on", + ...(to === "on" && interval !== undefined ? { intervalMinutes: interval } : {}), + ...(to === "on" && hours !== undefined ? { hours } : {}), + ...(to === "on" && flags["--shots"] ? { shots: true } : {}), + by: byOf(flags), + }); + say(result, String(result.sentence ?? "")); + return 0; + } + if (sub === "purge") { + need(lib); + const scope = { slug: lib, ...(flags["--topic"] ? { topic: flags["--topic"] } : {}) }; + const by = byOf(flags); + if (flags["--dry-run"]) { + const plan = await purge(ask, { ...scope, dryRun: true, by }); + say(plan, `${plan.sentence}\n${plan.posts} to remove · ${(plan.gone ?? []).length} of them gone from the page · ${plan.agentDropped ?? 0} dropped by an agent, left alone${plan.posts ? `\nconfirm: ${plan.confirm} (umtool library purge ${lib}${flags["--topic"] ? ` --topic ${flags["--topic"]}` : ""} --confirm ${plan.confirm} --by operator)` : ""}`); + return 0; + } + if (!flags["--confirm"]) throw new Refusal("purge: --dry-run says what would be removed and prints the --confirm the removal needs"); + const done = await purge(ask, { ...scope, confirm: flags["--confirm"], by }); + say(done, String(done.sentence ?? "")); + return 0; + } + if (sub === "seen") { + need(lib); + // What is "new" is the operator's to say: an agent marking topics seen would hide posts from him. + if (byOf(flags) !== "operator") throw new Refusal("seen: Mark seen is the operator's (it decides what he is shown as new): say --by operator. An agent does not mark topics seen."); + const known = (await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id); + let topics = words.slice(2); + if (flags["--all"]) topics = known; + if (!topics.length) throw new Refusal("seen: name the topics, or --all"); + const unknown = topics.filter((t) => !known.includes(t)); + if (unknown.length) throw new Refusal(`seen: ${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked`); + const marked = await markSeen(reportsRoot, { slug: lib, topics }); + say({ ok: true, ...marked }, `${topics.length} topic${topics.length === 1 ? "" : "s"} marked seen: ${topics.join(", ")}`); + return 0; + } + throw new Refusal(`library: unknown verb "${sub}"\n${LIBRARY_USAGE}`); + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return 1; + } +} diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs @@ -0,0 +1,157 @@ +// `umtool library` (lane posts-library): the page's calls from a shell. A fake +// editor (no socket), a temp reports root. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { libraryCommand } from "./cli.mjs"; + +function harness(answers = {}) { + const asked = []; + const lines = []; + const errors = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + if (route === "/api/ops/trending") return { ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 1, posts: 3, unjudged: 2 }] }; + if (route.startsWith("/api/ops/trending?")) { + const sp = new URL(route, "http://x").searchParams; + if (sp.get("ids") === "1") return { ok: true, ids: answers.ids ?? ["11", "12"], posts: [], total: 2, topics: [] }; + return { + ok: true, + total: 1, + topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), watch: { on: true, sentence: "Watched every 30 min." }, sources: [] }], + posts: [{ id: "11", author: "teapot_news", text: "The kettle\nfestival opens.", thread: "11", gone: { at: "2026-11-17T11:00:00.000Z" }, capture: { state: "captured", at: "2026-11-17T10:05:00.000Z" } }], + }; + } + if (route === "/api/ops/judge-trending") return { ok: true, written: init.body.set.map((s) => ({ ...s })), skipped: answers.skipped ?? [], kept: init.body.set.filter((s) => s.state === "keep").map((s) => s.id), ...(init.body.archive === false ? {} : { archive: { jobId: "cap-1", ids: ["11"] } }) }; + if (route === "/api/ops/watch-trending") { + if (answers.watchRefused) throw new Error(answers.watchRefused); + return { ok: true, sentence: "Watched every 45 min." }; + } + if (route === "/api/ops/purge-trending") return init.body.dryRun ? { ok: true, dryRun: true, posts: 1, gone: [{ id: "11", at: "2026-11-17T11:00:00.000Z" }], agentDropped: 2, confirm: "FAKE-TEST-VALUE", sentence: "Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay." } : { ok: true, dryRun: false, posts: 1, sentence: "Removed the capture of 1 dropped post: 3 files, 204 B. The judgements stay." }; + throw new Error(`unexpected ${route}`); + }; + return { asked, lines, errors, deps: { ask, out: (s) => lines.push(s), err: (s) => errors.push(s) }, posts: () => asked.filter((a) => a.method === "POST") }; +} + +async function withRoot(fn) { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-cli-")); + try { + return await fn(root); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +test("ls, topics and posts read through the editor; --json prints the answer", async () => { + await withRoot(async (root) => { + const h = harness(); + assert.equal(await libraryCommand([], { ...h.deps, reportsRoot: root }), 0); + assert.equal(h.lines[0], "lib Lib 1 topics · 3 posts · 2 unjudged"); + assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0); + assert.equal(h.lines[1], "kettles Kettles 3 posts · 2 unjudged · 3 new\n Watched every 30 min."); + assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--state", "unjudged", "--gone", "--media", "--author", "teapot_news", "--q", "kettle lid", "--limit", "5", "--offset", "10"], { ...h.deps, reportsRoot: root }), 0); + assert.equal(h.asked.at(-1).route, "/api/ops/trending?slug=lib&topic=kettles&limit=5&offset=10&state=unjudged&gone=1&media=1&author=teapot_news&q=kettle+lid&detail=1"); + // Gone from the page, in those words; the capture's state verbatim. + assert.match(h.lines[2], /^1 post\n11 {2}@teapot_news {2}unjudged · gone from the page at 2026-11-17T11:00:00\.000Z · capture: captured at 2026-11-17T10:05:00\.000Z\n {4}The kettle festival opens\.$/); + assert.equal(await libraryCommand(["posts", "lib", "--json"], { ...h.deps, reportsRoot: root }), 0); + assert.equal(JSON.parse(h.lines[3]).posts[0].id, "11"); + }); +}); + +test("judge: an agent by default, the operator when said; ids, threads, and a filter that asks first", async () => { + await withRoot(async (root) => { + const h = harness(); + const deps = { ...h.deps, reportsRoot: root }; + assert.equal(await libraryCommand(["judge", "lib", "--state", "keep", "--id", "11,12", "--note", "the opening"], deps), 0); + assert.deepEqual(h.posts()[0].body, { slug: "lib", by: "agent", set: [{ id: "11", state: "keep", note: "the opening" }, { id: "12", state: "keep", note: "the opening" }] }); + assert.match(h.lines[0], /^2 judgements written as the agent's\.\n1 post queued for archiving \(the editor's capture job cap-1\)\.$/); + assert.equal(await libraryCommand(["judge", "lib", "--state", "drop", "--thread", "11", "--by", "operator", "--no-archive"], deps), 0); + assert.deepEqual(h.posts()[1].body, { slug: "lib", by: "operator", set: [{ thread: "11", state: "drop" }], archive: false }); + + // --filter: a count first (exit 1 without --yes, 0 with --dry-run), then one judge ask. + assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--topic", "kettles", "--media"], deps), 1); + assert.equal(h.lines.at(-1), "2 posts would be judged later (--yes judges them)."); + assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--topic", "kettles", "--dry-run", "--json"], deps), 0); + assert.deepEqual(JSON.parse(h.lines.at(-1)), { slug: "lib", dryRun: true, state: "later", posts: 2, ids: ["11", "12"] }); + assert.equal(h.posts().length, 2); + assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--where", "unjudged", "--topic", "kettles", "--media", "--yes"], deps), 0); + assert.equal(h.asked.at(-2).route, "/api/ops/trending?slug=lib&topic=kettles&state=unjudged&media=1&ids=1"); + assert.deepEqual(h.posts()[2].body.set, [{ id: "11", state: "later" }, { id: "12", state: "later" }]); + + for (const [args, re] of [ + [["judge", "lib", "--state", "deleted", "--id", "11"], /--state is one of keep, drop, later, undecided/], + [["judge", "lib", "--state", "keep"], /--id, --thread or --filter, one of them/], + [["judge", "lib", "--state", "keep", "--id", "11", "--thread", "11"], /one of them/], + [["judge", "lib", "--state", "keep", "--id", "11", "--by", "me"], /--by is "agent" or "operator"/], + [["judge", "--state", "keep", "--id", "11"], /name the library/], + [["posts", "lib", "--new"], /--new goes with --topic/], + [["posts", "lib", "--nope"], /unknown flag --nope/], + [["frobnicate", "lib"], /unknown verb "frobnicate"/], + ]) { + const before = h.posts().length; + assert.equal(await libraryCommand(args, deps), 1); + assert.match(h.errors.at(-1), re); + assert.equal(h.posts().length, before); + } + }); +}); + +test("watch and purge: the switch with its terms; the editor's refusal is exit 1 in its words; the purge is a dry run, then --confirm", async () => { + await withRoot(async (root) => { + const h = harness(); + const deps = { ...h.deps, reportsRoot: root }; + assert.equal(await libraryCommand(["watch", "lib", "kettles", "on", "--interval", "45", "--hours=24", "--shots"], deps), 0); + assert.deepEqual(h.posts()[0].body, { slug: "lib", topic: "kettles", on: true, intervalMinutes: 45, hours: 24, shots: true, by: "agent" }); + assert.equal(h.lines[0], "Watched every 45 min."); + assert.equal(await libraryCommand(["watch", "lib", "kettles", "off", "--interval", "45", "--by", "operator"], deps), 0); + assert.deepEqual(h.posts()[1].body, { slug: "lib", topic: "kettles", on: false, by: "operator" }); + assert.equal(await libraryCommand(["watch", "lib", "kettles"], deps), 1); + + const refused = harness({ watchRefused: "This watch is paused as failing: only the operator switches it on again." }); + assert.equal(await libraryCommand(["watch", "lib", "kettles", "on"], { ...refused.deps, reportsRoot: root }), 1); + assert.equal(refused.errors[0], "This watch is paused as failing: only the operator switches it on again."); + + assert.equal(await libraryCommand(["purge", "lib", "--topic", "kettles", "--dry-run"], deps), 0); + assert.deepEqual(h.posts().at(-1).body, { slug: "lib", topic: "kettles", dryRun: true, by: "agent" }); + // The same numbers the page and `pnpm ops` give: to remove, gone from the page, an agent's left alone. + assert.match(h.lines.at(-1), /^Would remove the capture of 1 dropped post: 3 files, 204 B\. The judgements stay\.\n1 to remove · 1 of them gone from the page · 2 dropped by an agent, left alone\nconfirm: FAKE-TEST-VALUE {3}\(umtool library purge lib --topic kettles --confirm FAKE-TEST-VALUE --by operator\)$/); + assert.equal(await libraryCommand(["purge", "lib"], deps), 1); + assert.match(h.errors.at(-1), /--dry-run says what would be removed/); + assert.equal(await libraryCommand(["purge", "lib", "--topic", "kettles", "--confirm", "FAKE-TEST-VALUE", "--by", "operator"], deps), 0); + assert.deepEqual(h.posts().at(-1).body, { slug: "lib", topic: "kettles", confirm: "FAKE-TEST-VALUE", by: "operator" }); + }); +}); + +test("seen marks topics in umtool's own state, and --new counts from it", async () => { + await withRoot(async (root) => { + const h = harness(); + const deps = { ...h.deps, reportsRoot: root }; + // Mark seen is the operator's: an agent (the default) is refused, and nothing is written. + assert.equal(await libraryCommand(["seen", "lib", "--all"], deps), 1); + assert.match(h.errors.at(-1), /Mark seen is the operator's .*say --by operator\. An agent does not mark topics seen\./); + assert.equal(await libraryCommand(["seen", "lib", "kettles", "--by", "agent"], deps), 1); + assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--new"], deps), 0); + assert.doesNotMatch(h.asked.at(-1).route, /since=/); + // A topic the library does not hold: refused, nothing marked. + assert.equal(await libraryCommand(["seen", "lib", "spoons", "--by", "operator"], deps), 1); + assert.match(h.errors.at(-1), /lib has no topic "spoons": nothing was marked/); + assert.equal(await libraryCommand(["seen", "lib", "--by", "operator"], deps), 1); + assert.equal(await libraryCommand(["seen", "lib", "--all", "--by", "operator", "--json"], deps), 0); + const marked = JSON.parse(h.lines.at(-1)); + assert.ok(Date.parse(marked.topics.kettles.seenAt) > 0); + assert.equal(h.posts().length, 0); + assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--new"], deps), 0); + assert.match(h.asked.at(-1).route, new RegExp(`since=${encodeURIComponent(marked.topics.kettles.seenAt).replace(/\./g, "\\.")}`)); + // topics: ONE read, the marks riding it. + const before = h.asked.length; + assert.equal(await libraryCommand(["topics", "lib"], deps), 0); + assert.match(h.lines.at(-1), /2 unjudged · 2 new/); + assert.equal(h.asked.length, before + 1); + assert.match(h.asked.at(-1).route, /detail=1/); + assert.match(h.asked.at(-1).route, /seen=%7B%22kettles%22/); + }); +}); diff --git a/umtool/lib/library/client.mjs b/umtool/lib/library/client.mjs @@ -0,0 +1,157 @@ +// THE POSTS LIBRARY, ASKED OF THE EDITOR (lane posts-library). One set of +// calls for umtool's Posts library page (through lib/articles/generation.ts +// askEditor) and for `umtool library` (through editorAsker below): the +// listing (GET /api/ops/trending) and the three presses (judge-trending, +// watch-trending, purge-trending). +// +// UMTOOL WRITES NOTHING OF A LIBRARY AND ASKS X NOTHING. Every press is the +// editor's action; a keep's capture is the editor's paced job. This module +// reads no file of the corpus. +// +// `ask(route, {method?, body?})` answers the editor's JSON and throws an Error +// carrying its words when it refuses or cannot be reached. +// +// Plain ESM, no imports. + +export const JUDGE_CHUNK = 500; +export const LIST_PAGE_MAX = 500; +export const LIBRARY_STATES = ["unjudged", "keep", "drop", "later"]; +export const JUDGE_STATES = ["keep", "drop", "later", "undecided"]; + +/** + * The query of one listing ask. + * @param {{ slug: string, topic?: string|null, limit?: number, offset?: number, state?: string|null, gone?: boolean, media?: boolean, author?: string|null, q?: string|null, since?: string|null, by?: string|null, seen?: Record<string, string>|null, ids?: boolean, detail?: boolean }} p + */ +export function libraryQuery(p) { + const q = new URLSearchParams({ slug: p.slug }); + if (p.topic) q.set("topic", p.topic); + if (p.limit) q.set("limit", String(p.limit)); + if (p.offset) q.set("offset", String(p.offset)); + if (p.state) q.set("state", p.state); + if (p.gone) q.set("gone", "1"); + if (p.media) q.set("media", "1"); + if (p.author) q.set("author", p.author); + if (p.q && p.q.trim()) q.set("q", p.q.trim()); + if (p.since) q.set("since", p.since); + if (p.by) q.set("by", p.by); + // The topics' Mark seen times: with detail, every topic's new posts come back in this one read. + if (p.seen && p.detail) q.set("seen", JSON.stringify(p.seen)); + if (p.ids) q.set("ids", "1"); + if (p.detail) q.set("detail", "1"); + return `/api/ops/trending?${q.toString()}`; +} + +/** Every library the editor holds: [{slug, name, topics, posts, unjudged}]. */ +export async function listLibraries(ask) { + const answer = await ask("/api/ops/trending"); + return Array.isArray(answer.libraries) ? answer.libraries : []; +} + +/** One listing ask (libraryQuery's parameters). */ +export function listLibrary(ask, params) { + return ask(libraryQuery(params)); +} + +/** Every id matching a filter, in listing order. */ +export async function listLibraryIds(ask, params) { + const answer = await ask(libraryQuery({ ...params, ids: true, detail: false, limit: undefined, offset: undefined })); + return Array.isArray(answer.ids) ? answer.ids : []; +} + +/** Every row matching a filter, with detail, a page at a time. */ +export async function listLibraryRows(ask, params) { + const rows = []; + for (let offset = 0; ; offset += LIST_PAGE_MAX) { + const answer = await ask(libraryQuery({ ...params, detail: true, ids: false, limit: LIST_PAGE_MAX, offset })); + const page = Array.isArray(answer.posts) ? answer.posts : []; + rows.push(...page); + if (page.length < LIST_PAGE_MAX || rows.length >= (answer.total ?? 0)) break; + } + return rows; +} + +/** + * Judge, at most JUDGE_CHUNK per ask (the editor's limit). Each chunk's keeps + * are ONE capture job, started by the editor's action: never a job per post. + * + * A LATER CHUNK THAT FAILS IS NOT A SILENT PARTIAL: what the chunks before it + * wrote is written, so the answer carries it with `failed` — the editor's + * words, and how many of the set were never asked. (The first chunk failing + * wrote nothing: it throws, as any refusal does.) + * @param {{ slug: string, by: "agent"|"operator", set: Array<{id?: string, thread?: string, state: string, note?: string}>, archive?: boolean }} p + * @returns {Promise<{ written: object[], skipped: object[], kept: string[], archives: object[], asks: number, failed?: { error: string, asked: number, unasked: number } }>} + */ +export async function judge(ask, p) { + const out = { written: [], skipped: [], kept: [], archives: [], asks: 0 }; + for (let i = 0; i < p.set.length; i += JUDGE_CHUNK) { + let answer; + try { + answer = await ask("/api/ops/judge-trending", { + method: "POST", + body: { slug: p.slug, by: p.by, set: p.set.slice(i, i + JUDGE_CHUNK), ...(p.archive === false ? { archive: false } : {}) }, + }); + } catch (err) { + if (i === 0) throw err; + out.failed = { error: err instanceof Error ? err.message : String(err), asked: i, unasked: p.set.length - i }; + return out; + } + out.asks++; + out.written.push(...(answer.written ?? [])); + out.skipped.push(...(answer.skipped ?? [])); + out.kept.push(...(answer.kept ?? [])); + if (answer.archive) out.archives.push(answer.archive); + } + return out; +} + +/** The watch's switch, the library's settings, or one scan: watch-trending's body, as given. */ +export function watch(ask, body) { + return ask("/api/ops/watch-trending", { method: "POST", body }); +} + +/** purge-trending's body, as given ({slug, dryRun: true, …} or {slug, confirm, by: "operator", …}). */ +export function purge(ask, body) { + return ask("/api/ops/purge-trending", { method: "POST", body }); +} + +/** + * What became of the keeps' archiving, as one sentence (or "" when nothing was kept). + * @param {{ kept: string[], archives: Array<{jobId?: string, error?: string, ids: string[]}> }} r + */ +export function archiveSentence(r) { + if (!r.kept.length) return ""; + const started = r.archives.filter((a) => a.jobId); + const refused = r.archives.filter((a) => a.error); + const n = (k) => `${k} post${k === 1 ? "" : "s"}`; + const parts = []; + if (started.length) parts.push(`${n(started.reduce((s, a) => s + a.ids.length, 0))} queued for archiving (the editor's capture job${started.length === 1 ? "" : "s"} ${started.map((a) => a.jobId).join(", ")})`); + if (refused.length) parts.push(`${n(refused.reduce((s, a) => s + a.ids.length, 0))} kept but not archived now: ${refused[0].error}`); + if (!parts.length) parts.push(`${n(r.kept.length)} kept, not archived now`); + return parts.join("; ") + "."; +} + +/** + * An asker for a process with no Next around it (the CLI): the editor's URL + * and the shared token, the editor's refusals as Errors with its words. + * @param {{ editorUrl: string, token: string, doFetch?: typeof fetch, timeoutMs?: number }} o + */ +export function editorAsker({ editorUrl, token, doFetch = fetch, timeoutMs = 30_000 }) { + const base = String(editorUrl).replace(/\/+$/, ""); + return async (route, init = {}) => { + if (!token) throw new Error("WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with."); + let res; + try { + res = await doFetch(`${base}${route}`, { + method: init.method ?? "GET", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (err) { + throw new Error(`could not reach the editor at ${base}: ${err?.message ?? err}`); + } + const body = await res.json().catch(() => ({})); + if (!res.ok || body.ok === false) throw new Error(String(body.error ?? `the editor answered HTTP ${res.status}`)); + return body; + }; +} diff --git a/umtool/lib/library/client.test.mjs b/umtool/lib/library/client.test.mjs @@ -0,0 +1,110 @@ +// The Posts library's calls to the editor (lane posts-library): the query a +// view becomes, judging in chunks the editor takes, and the asker's refusals. +// No socket: `ask` and `doFetch` are fakes. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { archiveSentence, editorAsker, judge, JUDGE_CHUNK, libraryQuery, listLibraries, listLibraryIds, listLibraryRows, purge, watch } from "./client.mjs"; + +function recorder(answers) { + const asked = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + return typeof answers === "function" ? answers(route, init, asked.length) : answers; + }; + return { ask, asked }; +} + +test("a view becomes the editor's query: only what is asked is sent", () => { + assert.equal(libraryQuery({ slug: "lib" }), "/api/ops/trending?slug=lib"); + assert.equal( + libraryQuery({ slug: "lib", topic: "kettles", limit: 50, offset: 100, state: "unjudged", gone: true, media: true, author: "teapot_news", q: " kettle lid ", since: "2026-11-17T10:00:00.000Z", detail: true }), + "/api/ops/trending?slug=lib&topic=kettles&limit=50&offset=100&state=unjudged&gone=1&media=1&author=teapot_news&q=kettle++lid&since=2026-11-17T10%3A00%3A00.000Z&detail=1", + ); + assert.equal(libraryQuery({ slug: "lib", topic: null, state: null, gone: false, q: " ", ids: true }), "/api/ops/trending?slug=lib&ids=1"); + // The topics' seen marks ride the detail read (one read answers every topic's new posts); never without detail. + assert.equal(libraryQuery({ slug: "lib", detail: true, seen: { kettles: "2026-11-17T10:00:00.000Z" }, by: "operator" }), `/api/ops/trending?slug=lib&by=operator&seen=${encodeURIComponent('{"kettles":"2026-11-17T10:00:00.000Z"}').replace(/%20/g, "+")}&detail=1`); + assert.equal(libraryQuery({ slug: "lib", ids: true, seen: { kettles: "2026-11-17T10:00:00.000Z" } }), "/api/ops/trending?slug=lib&ids=1"); +}); + +test("the libraries, the ids of a filter, and every row a page at a time", async () => { + const libs = recorder({ ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 1, posts: 2, unjudged: 1 }] }); + assert.deepEqual(await listLibraries(libs.ask), [{ slug: "lib", name: "Lib", topics: 1, posts: 2, unjudged: 1 }]); + assert.equal(libs.asked[0].route, "/api/ops/trending"); + + const ids = recorder({ ok: true, ids: ["1", "2"], posts: [] }); + assert.deepEqual(await listLibraryIds(ids.ask, { slug: "lib", state: "drop", limit: 5, offset: 5, detail: true }), ["1", "2"]); + assert.equal(ids.asked[0].route, "/api/ops/trending?slug=lib&state=drop&ids=1"); + + const total = 620; + const rows = recorder((route) => { + const offset = Number(new URL(route, "http://x").searchParams.get("offset") ?? 0); + return { ok: true, total, posts: Array.from({ length: Math.min(500, total - offset) }, (_, i) => ({ id: String(offset + i) })) }; + }); + assert.equal((await listLibraryRows(rows.ask, { slug: "lib" })).length, total); + assert.deepEqual(rows.asked.map((a) => a.route), ["/api/ops/trending?slug=lib&limit=500&detail=1", "/api/ops/trending?slug=lib&limit=500&offset=500&detail=1"]); +}); + +test("judging goes in chunks of at most 500: one ask, so one capture job, per chunk — never one per post", async () => { + const set = Array.from({ length: 2 * JUDGE_CHUNK + 7 }, (_, i) => ({ id: String(1000 + i), state: "keep" })); + const r = recorder((route, init, n) => ({ ok: true, written: init.body.set.map((s) => ({ id: s.id, state: s.state })), skipped: [], kept: init.body.set.map((s) => s.id), archive: { jobId: `job-${n}`, ids: init.body.set.map((s) => s.id) } })); + const out = await judge(r.ask, { slug: "lib", by: "operator", set }); + assert.equal(r.asked.length, 3); + assert.deepEqual(r.asked.map((a) => a.body.set.length), [500, 500, 7]); + assert.ok(r.asked.every((a) => a.route === "/api/ops/judge-trending" && a.method === "POST" && a.body.by === "operator" && a.body.slug === "lib" && !("archive" in a.body))); + assert.equal(out.asks, 3); + assert.equal(out.kept.length, 1007); + assert.deepEqual(out.archives.map((a) => a.jobId), ["job-1", "job-2", "job-3"]); + assert.match(archiveSentence(out), /^1007 posts queued for archiving \(the editor's capture jobs job-1, job-2, job-3\)\.$/); + + // archive: false is passed on (an undo), and starts nothing. + const undo = recorder({ ok: true, written: [], skipped: [], kept: [] }); + await judge(undo.ask, { slug: "lib", by: "operator", set: [{ id: "1", state: "undecided" }], archive: false }); + assert.equal(undo.asked[0].body.archive, false); + assert.equal(archiveSentence({ kept: [], archives: [] }), ""); + assert.match(archiveSentence({ kept: ["1"], archives: [{ error: "X's cookie jar is 70 minutes old", ids: ["1"] }] }), /^1 post kept but not archived now: X's cookie jar is 70 minutes old\.$/); +}); + +test("the watch and the purge post their bodies as given", async () => { + const r = recorder({ ok: true }); + await watch(r.ask, { slug: "lib", topic: "kettles", on: true, by: "operator" }); + await purge(r.ask, { slug: "lib", dryRun: true }); + assert.deepEqual(r.asked, [ + { route: "/api/ops/watch-trending", method: "POST", body: { slug: "lib", topic: "kettles", on: true, by: "operator" } }, + { route: "/api/ops/purge-trending", method: "POST", body: { slug: "lib", dryRun: true } }, + ]); +}); + +test("the CLI's asker: the bearer, the editor's words on a refusal, a sentence when nothing answers or no token is set", async () => { + const calls = []; + const ok = editorAsker({ editorUrl: "http://editor.invalid:1/", token: "t", doFetch: async (url, init) => (calls.push({ url, init }), new Response(JSON.stringify({ ok: true, n: 1 }))) }); + assert.deepEqual(await ok("/api/ops/trending"), { ok: true, n: 1 }); + assert.equal(calls[0].url, "http://editor.invalid:1/api/ops/trending"); + assert.equal(calls[0].init.headers.authorization, "Bearer t"); + const refused = editorAsker({ editorUrl: "http://editor.invalid:1", token: "t", doFetch: async () => new Response(JSON.stringify({ ok: false, error: "lib is not an X trending library" }), { status: 400 }) }); + await assert.rejects(refused("/x"), /lib is not an X trending library/); + const down = editorAsker({ editorUrl: "http://editor.invalid:1", token: "t", doFetch: async () => { throw new Error("ECONNREFUSED"); } }); + await assert.rejects(down("/x"), /could not reach the editor at http:\/\/editor\.invalid:1: ECONNREFUSED/); + let asked = false; + const none = editorAsker({ editorUrl: "http://editor.invalid:1", token: "", doFetch: async () => ((asked = true), new Response("{}")) }); + await assert.rejects(none("/x"), /WORKER_TOKEN is not set/); + assert.equal(asked, false); +}); + +test("S6: a later chunk that fails is said: what was written, the editor's words, how many were never asked; the first chunk failing throws", async () => { + const set = Array.from({ length: 2 * JUDGE_CHUNK + 7 }, (_, i) => ({ id: String(1000 + i), state: "drop" })); + const r = recorder((route, init, n) => { + if (n === 2) throw new Error("X is cooling down"); + return { ok: true, written: init.body.set.map((s) => ({ id: s.id, state: s.state })), skipped: [], kept: [] }; + }); + const out = await judge(r.ask, { slug: "lib", by: "operator", set }); + // Two asks: the third chunk was never sent after the second failed. + assert.equal(r.asked.length, 2); + assert.equal(out.written.length, 500); + assert.deepEqual(out.failed, { error: "X is cooling down", asked: 500, unasked: 507 }); + const first = recorder(() => { + throw new Error("lib is not an X trending library"); + }); + await assert.rejects(judge(first.ask, { slug: "lib", by: "operator", set }), /not an X trending library/); +}); diff --git a/umtool/lib/library/filters.mjs b/umtool/lib/library/filters.mjs @@ -0,0 +1,93 @@ +// THE POSTS LIBRARY PAGE'S VIEW, AS ITS URL SAYS IT (lane posts-library): +// /tools/library?lib=&topic=&state=&gone=1&media=1&author=&q=&new=1&offset= +// A phone and a desktop open the same view from the same link. Plain ESM. + +import { LIBRARY_STATES } from "./client.mjs"; + +export const LIBRARY_PATH = "/tools/library"; +export const PAGE_SIZE = 50; + +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const TOPIC = /^[a-z0-9][a-z0-9-]{0,119}$/; +const HANDLE = /^@?[A-Za-z0-9_]{1,30}$/; +const one = (v) => (Array.isArray(v) ? v[0] : v); +const flag = (v) => one(v) === "1"; + +/** + * The view a page's search params ask for; anything ill-shaped is dropped, never thrown. + * @param {Record<string, string | string[] | undefined>} sp + * @returns {{ lib: string|null, topic: string|null, state: string|null, gone: boolean, media: boolean, author: string|null, q: string, fresh: boolean, offset: number }} + */ +export function parseLibraryView(sp) { + const str = (k) => (typeof one(sp[k]) === "string" ? one(sp[k]).trim() : ""); + const offset = Number(str("offset")); + return { + lib: SLUG.test(str("lib")) ? str("lib") : null, + topic: TOPIC.test(str("topic")) ? str("topic") : null, + state: LIBRARY_STATES.includes(str("state")) ? str("state") : null, + gone: flag(sp.gone), + media: flag(sp.media), + author: HANDLE.test(str("author")) ? str("author").replace(/^@/, "") : null, + q: str("q").slice(0, 200), + fresh: flag(sp.new), + offset: Number.isInteger(offset) && offset > 0 ? offset : 0, + }; +} + +/** The page's address for a view (a partial one: what is absent is off). */ +export function libraryHref(view = {}) { + const q = new URLSearchParams(); + if (view.lib) q.set("lib", view.lib); + if (view.topic) q.set("topic", view.topic); + if (view.state) q.set("state", view.state); + if (view.gone) q.set("gone", "1"); + if (view.media) q.set("media", "1"); + if (view.author) q.set("author", view.author); + if (view.q) q.set("q", view.q); + if (view.fresh) q.set("new", "1"); + if (view.offset) q.set("offset", String(view.offset)); + const s = q.toString(); + return s ? `${LIBRARY_PATH}?${s}` : LIBRARY_PATH; +} + +/** + * The editor's listing parameters for a view. `seenAt` is the topic's Mark + * seen time: "new" means first shown by a read after it (never marked: every + * post is new, so no `since`). + * @param {ReturnType<typeof parseLibraryView>} view + * @param {{ seenAt?: string | null }} [o] + */ +export function listingParamsOf(view, { seenAt = null } = {}) { + return { + slug: view.lib, + topic: view.topic, + state: view.state, + gone: view.gone, + media: view.media, + author: view.author, + q: view.q, + since: view.fresh && seenAt ? seenAt : null, + }; +} + +/** The filters in force, in words, for a confirm ("unjudged, with media, by @x"); "" for none. */ +export function filterWords(view) { + const out = []; + if (view.state) out.push(view.state === "unjudged" ? "unjudged" : view.state === "keep" ? "kept" : view.state === "drop" ? "dropped" : "marked later"); + if (view.fresh) out.push("new since Mark seen"); + if (view.gone) out.push("gone from the page"); + if (view.media) out.push("with media"); + if (view.author) out.push(`by @${view.author}`); + if (view.q) out.push(`matching “${view.q}”`); + return out.join(", "); +} + +/** "gone from the page at <time>": the one sentence for a gone mark. Never "deleted". */ +export function goneSentence(gone, fmt = (iso) => iso) { + return gone && typeof gone.at === "string" ? `Gone from the page at ${fmt(gone.at)}` : ""; +} + +/** A capture's own state, verbatim: "capture: <state> at <time>". */ +export function captureSentence(capture, fmt = (iso) => iso) { + return capture && typeof capture.state === "string" ? `capture: ${capture.state} at ${fmt(capture.at)}` : ""; +} diff --git a/umtool/lib/library/keys.mjs b/umtool/lib/library/keys.mjs @@ -0,0 +1,47 @@ +// THE POSTS LIBRARY'S KEYS (lane posts-library), one table: the page's +// handler, its key bar and the `?` sheet all read it. Plain ESM. + +export const LIBRARY_KEYS = [ + { key: "j", action: "next", label: "next post" }, + { key: "k", action: "prev", label: "previous post" }, + { key: "a", action: "keep", label: "keep" }, + { key: "d", action: "drop", label: "drop" }, + { key: "l", action: "later", label: "later" }, + { key: "c", action: "clear", label: "clear the judgement" }, + { key: "t", action: "scope", label: "judge the post or its whole thread" }, + { key: "n", action: "note", label: "note" }, + { key: "x", action: "select", label: "select" }, + { key: "A", action: "bulk-keep", label: "keep everything in the filter" }, + { key: "D", action: "bulk-drop", label: "drop everything in the filter" }, + { key: "L", action: "bulk-later", label: "mark everything in the filter later" }, + { key: "u", action: "undo", label: "undo the last press" }, + { key: "/", action: "search", label: "search" }, + { key: "g", action: "gone", label: "only gone from the page" }, + { key: "m", action: "media", label: "only with media" }, + { key: "?", action: "help", label: "this list" }, +]; + +const BY_KEY = new Map(LIBRARY_KEYS.map((k) => [k.key, k.action])); + +/** + * The action a key press asks for, or null: nothing while typing in a field, + * nothing with Ctrl / Meta / Alt held (the browser's own keys). + * @param {{ key: string, ctrlKey?: boolean, metaKey?: boolean, altKey?: boolean, typing?: boolean }} e + */ +export function libraryAction(e) { + if (e.typing || e.ctrlKey || e.metaKey || e.altKey) return null; + return BY_KEY.get(e.key) ?? null; +} + +/** Whether a key event's target is a field being typed in. */ +export function isTyping(target) { + if (!target || typeof target !== "object") return false; + const tag = String(target.tagName ?? "").toLowerCase(); + return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable === true; +} + +/** The judge state an action sets ("undecided" removes the judgement), or null. */ +export function stateOfAction(action) { + const a = String(action ?? "").replace(/^bulk-/, ""); + return a === "keep" || a === "drop" || a === "later" ? a : a === "clear" ? "undecided" : null; +} diff --git a/umtool/lib/library/load.ts b/umtool/lib/library/load.ts @@ -0,0 +1,93 @@ +import type { XTrendingListing, XTrendingPostRow, XTrendingTopicRow } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { askEditor, EditorError, editorUrl } from "@/lib/articles/generation"; +import { listLibraries, listLibrary } from "@/lib/library/client.mjs"; +import { listingParamsOf, PAGE_SIZE, parseLibraryView } from "@/lib/library/filters.mjs"; +import { seenOf } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +// WHAT THE POSTS LIBRARY PAGE SHOWS (lane posts-library), read THROUGH THE +// EDITOR (GET /api/ops/trending): the libraries, one library's topics with +// their counts and watches, and one page of posts under the view's filters. +// umtool opens no file of a library here. The one thing it adds is its own: +// each topic's Mark seen time, handed to the listing, which answers how many +// posts of each topic are new in the same read. +// +// TWO READS OF THE EDITOR PER VIEW, whatever the number of topics: the +// libraries, and one listing (the topics, their counts and new posts, the +// page of posts). +// +// SERVER-ONLY. + +export type LibraryView = ReturnType<typeof parseLibraryView>; +export type LibrarySummary = { slug: string; name: string; topics: number; posts: number; unjudged: number }; +export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number }; +export type LibraryPost = XTrendingPostRow; + +export type LibraryData = + | { ok: false; sentence: string; reason: string } + | { + ok: true; + libraries: LibrarySummary[]; + lib: string; + name: string; + view: LibraryView; + topics: LibraryTopic[]; + posts: LibraryPost[]; + total: number; + authors: Array<{ author: string; posts: number }>; + pageSize: number; + }; + +// ALWAYS ASKED AGAIN (`fresh`): a judge view shows what a press just wrote, and askEditor's two-second +// memo may hold an answer another render asked for while that press was still on its way to the editor. +const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, { ...init, fresh: true }); + +/** Why the library cannot be shown, as one sentence. */ +export function unavailableSentence(err: unknown): { sentence: string; reason: string } { + if (err instanceof EditorError) { + if (err.reason === "no-token") return { reason: err.reason, sentence: "umtool has no WORKER_TOKEN, so the editor cannot be asked. The library is read and judged through the editor: set WORKER_TOKEN to the value the editor runs with." }; + if (err.reason === "unreachable") return { reason: err.reason, sentence: `The editor is not answering at ${editorUrl()}. The library is read and judged through the editor: start it, then reload.` }; + if (err.reason === "editor-token") return { reason: err.reason, sentence: "The editor's own WORKER_TOKEN is not set, so its ops surface is off. The library is read and judged through it." }; + if (err.reason === "denied") return { reason: err.reason, sentence: "The editor refused umtool's WORKER_TOKEN: the two tokens differ. The library is read and judged through the editor." }; + return { reason: err.reason, sentence: err.message }; + } + return { reason: "error", sentence: err instanceof Error ? err.message : String(err) }; +} + +export async function loadLibrary(view: LibraryView): Promise<LibraryData> { + try { + const libraries = (await listLibraries(ask)) as LibrarySummary[]; + if (libraries.length === 0) { + return { ok: false, reason: "no-library", sentence: "The editor has no X trending library. One is made in the editor (a channel with the platform x-trending), and its topics come from reading a trending page there." }; + } + const lib = view.lib ?? libraries[0].slug; + if (!libraries.some((l) => l.slug === lib)) { + return { ok: false, reason: "no-library", sentence: `The editor has no library "${lib}". Its libraries: ${libraries.map((l) => l.slug).join(", ")}.` }; + } + const seen = (await seenOf(REPORTS_ROOT, lib)) as Record<string, string>; + const shown = { ...view, lib }; + const listing = (await listLibrary(ask, { + ...listingParamsOf(shown, { seenAt: view.topic ? (seen[view.topic] ?? null) : null }), + limit: PAGE_SIZE, + offset: view.offset, + detail: true, + // New since Mark seen, per topic, answered by this same read (a topic never marked is new in full). + seen, + })) as unknown as XTrendingListing & { name?: string }; + const topics: LibraryTopic[] = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts })); + return { + ok: true, + libraries, + lib, + name: listing.name ?? lib, + view: shown, + topics, + posts: listing.posts, + total: listing.total, + authors: listing.authors ?? [], + pageSize: PAGE_SIZE, + }; + } catch (err) { + return { ok: false, ...unavailableSentence(err) }; + } +} diff --git a/umtool/lib/library/media.mjs b/umtool/lib/library/media.mjs @@ -0,0 +1,60 @@ +// A LIBRARY'S CAPTURED MEDIA, FOUND FOR THE ONE ROUTE THAT SERVES IT (lane +// posts-library): GET /api/library/media/<lib>/<id>/<name>. +// +// A trending library is PRIVATE. Every other reader of the corpus in umtool +// refuses a library by its marker; this is the one that REQUIRES it, and it +// can name exactly one kind of file: +// +// <channelsDir>/<lib>/trending/posts-media/<id>/<name> +// +// lib a slug whose config.json carries the library marker +// id digits only +// name one path segment of [A-Za-z0-9._-], not starting with a dot, with a +// picture's or a video's extension — so never capture.json, an +// article's text, the raw reads, the judgements or the index +// and the file's REAL path must sit under the real trending/posts-media of +// that library: a name that is a symlink out of it is refused. (The media +// files are hardlinks into the library's store, which are plain files.) +// +// It lists nothing: no directory, no index of ids. Plain ESM. +import { realpath, stat } from "node:fs/promises"; +import path from "node:path"; +import { isTrendingLibrary } from "../report/xTrendingMarker.mjs"; + +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const ID = /^\d{1,32}$/; +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +export const LIBRARY_MEDIA_TYPES = Object.freeze({ + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + ".gif": "image/gif", + ".mp4": "video/mp4", + ".m4v": "video/mp4", + ".mov": "video/quicktime", + ".webm": "video/webm", +}); + +export { libraryMediaSrc } from "./mediaSrc.mjs"; + +/** + * The file a media request names, or why not. + * @param {{ channelsDir: string, lib: string, id: string, name: string }} o + * @returns {Promise<{ ok: true, abs: string, size: number, type: string } | { ok: false, status: 400 | 404 }>} + */ +export async function resolveLibraryMedia({ channelsDir, lib, id, name }) { + if (typeof lib !== "string" || typeof id !== "string" || typeof name !== "string") return { ok: false, status: 400 }; + if (!SLUG.test(lib) || !ID.test(id) || !NAME.test(name) || name.includes("..")) return { ok: false, status: 400 }; + const type = LIBRARY_MEDIA_TYPES[path.extname(name).toLowerCase()]; + if (!type) return { ok: false, status: 404 }; + if (!(await isTrendingLibrary(channelsDir, lib))) return { ok: false, status: 404 }; + const root = path.join(/* turbopackIgnore: true */ channelsDir, lib, "trending", "posts-media"); + const abs = path.join(/* turbopackIgnore: true */ root, id, name); + const [real, realRoot] = await Promise.all([realpath(/* turbopackIgnore: true */ abs).catch(() => null), realpath(/* turbopackIgnore: true */ root).catch(() => null)]); + if (!real || !realRoot || !real.startsWith(realRoot + path.sep)) return { ok: false, status: 404 }; + const st = await stat(/* turbopackIgnore: true */ real).catch(() => null); + if (!st?.isFile()) return { ok: false, status: 404 }; + return { ok: true, abs: real, size: st.size, type }; +} diff --git a/umtool/lib/library/media.test.mjs b/umtool/lib/library/media.test.mjs @@ -0,0 +1,95 @@ +// The one file a library's media route may name (lane posts-library), over a +// temp corpus: only a picture or a video under +// channels/<lib>/trending/posts-media/<id>/ of a channel carrying the library +// marker — never the record, the raw reads, another channel, or a name that +// resolves outside the directory. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { link, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { libraryMediaSrc, resolveLibraryMedia } from "./media.mjs"; + +const ID = "1900000000000006001"; + +async function corpus() { + const channels = await mkdtemp(path.join(tmpdir(), "umtool-library-media-")); + const lib = path.join(channels, "trending-lib"); + const cap = path.join(lib, "trending", "posts-media", ID); + await mkdir(cap, { recursive: true }); + await writeFile(path.join(lib, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); + await writeFile(path.join(cap, "shot.png"), "SHOT"); + await writeFile(path.join(cap, "capture.json"), "{}"); + await writeFile(path.join(cap, "article.md"), "words"); + // A media file as the store leaves it: a hardlink to its blob. + await mkdir(path.join(lib, "trending", "media-store", "ab"), { recursive: true }); + await writeFile(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), "VIDEO-BYTES"); + await link(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), path.join(cap, `${ID}_1.mp4`)); + // What must never be served. + await mkdir(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000"), { recursive: true }); + await writeFile(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), "RAW-PAGE"); + await writeFile(path.join(lib, "trending", "judgements.json"), "{}"); + await writeFile(path.join(channels, "outside.png"), "OUTSIDE"); + // An ordinary posts channel with a capture of the same shape. + const account = path.join(channels, "kettle-org-x"); + await mkdir(path.join(account, "posts-media", ID), { recursive: true }); + await mkdir(path.join(account, "trending", "posts-media", ID), { recursive: true }); + await writeFile(path.join(account, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/kettle_org" })); + await writeFile(path.join(account, "trending", "posts-media", ID, "shot.png"), "NOT-A-LIBRARY"); + return { channels, lib, cap }; +} + +test("a picture and a video of a library's capture are found, with their type and size", async () => { + const { channels, cap } = await corpus(); + try { + const shot = await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: "shot.png" }); + assert.deepEqual(shot, { ok: true, abs: path.join(cap, "shot.png"), size: 4, type: "image/png" }); + const video = await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: `${ID}_1.mp4` }); + assert.equal(video.ok && video.type, "video/mp4"); + assert.equal(video.ok && video.size, 11); + assert.equal(libraryMediaSrc("trending-lib", ID, "shot.png"), `/api/library/media/trending-lib/${ID}/shot.png`); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); + +test("refused: the record and any non-media name, a traversal, another id shape, a channel that is no library, a missing file", async () => { + const { channels } = await corpus(); + try { + const no = async (lib, id, name) => (await resolveLibraryMedia({ channelsDir: channels, lib, id, name })).ok; + for (const name of ["capture.json", "article.md", "shot", ".hidden.png", "..", "../shot.png", "a/b.png", "shot.png/..", "x..png", ""]) { + assert.equal(await no("trending-lib", ID, name), false, name); + } + for (const id of ["..", "../reads", "_avatars", "", "19a", `${ID}/..`]) assert.equal(await no("trending-lib", id, "shot.png"), false, id); + for (const lib of ["kettle-org-x", "nope", "..", "trending-lib/..", ""]) assert.equal(await no(lib, ID, "shot.png"), false, lib); + assert.equal(await no("trending-lib", ID, "missing.png"), false); + // A directory with a media-looking name is not a file. + assert.equal(await no("trending-lib", "1900000000000006009", "shot.png"), false); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: undefined })).ok, false); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); + +test("a name planted in the capture directory whose real path is OUTSIDE posts-media is refused: the raw read, the corpus, the directory itself", async () => { + const { channels, lib, cap } = await corpus(); + try { + await symlink(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), path.join(cap, "raw.png")); + await symlink(path.join(channels, "outside.png"), path.join(cap, "outside.png")); + await symlink(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), path.join(cap, "viastore.mp4")); + await symlink(path.join(lib, "trending", "reads"), path.join(lib, "trending", "posts-media", "1900000000000006002")); + for (const name of ["raw.png", "outside.png", "viastore.mp4"]) { + assert.deepEqual(await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name }), { ok: false, status: 404 }, name); + } + // An id that is a link to another directory. + await writeFile(path.join(lib, "trending", "reads", "x.png"), "RAW"); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: "1900000000000006002", name: "x.png" })).ok, false); + // A link that stays inside posts-media is the file it names. + await symlink(path.join(cap, "shot.png"), path.join(cap, "alias.png")); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: "alias.png" })).ok, true); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/library/mediaSrc.mjs b/umtool/lib/library/mediaSrc.mjs @@ -0,0 +1,12 @@ +// The address the Posts library page gives a captured file (lane posts-library): the route +// /api/library/media/<lib>/<id>/<name>. In a file of its own, with no import, so a browser bundle takes it +// without the resolver beside it (lib/library/media.mjs reads the disk). + +/** + * @param {string} lib + * @param {string} id + * @param {string} name + */ +export function libraryMediaSrc(lib, id, name) { + return `/api/library/media/${encodeURIComponent(lib)}/${encodeURIComponent(id)}/${encodeURIComponent(name)}`; +} diff --git a/umtool/lib/library/presses.mjs b/umtool/lib/library/presses.mjs @@ -0,0 +1,158 @@ +// THE POSTS LIBRARY PAGE'S PRESSES (lane posts-library): what +// /api/library/{judge,watch,purge} do with a body, apart from Next. Each is +// the editor's action, asked through `ask` (lib/library/client.mjs). +// +// EVERY PRESS FROM THE PAGE IS THE OPERATOR'S: `by: "operator"` is stamped +// HERE, on the server. A `by` in the body is not read, so nothing a browser +// (or anything else posting to these routes) sends can say otherwise; an +// agent's hand is `pnpm ops` or `umtool library`, which say "agent". +// +// Plain ESM. +import { JUDGE_STATES, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, purge, watch } from "./client.mjs"; +import { listingParamsOf, parseLibraryView } from "./filters.mjs"; +import { pressSetOf, undoSetOf } from "./undo.mjs"; + +export const OPERATOR = "operator"; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const ID = /^\d{1,32}$/; + +export class PressError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "PressError"; + this.status = status; + } +} + +function libOf(body) { + if (!body || typeof body !== "object" || Array.isArray(body)) throw new PressError("the body is a JSON object"); + if (typeof body.lib !== "string" || !SLUG.test(body.lib)) throw new PressError(`"lib" is the library's slug`); + return body.lib; +} + +function cleanSet(set) { + if (!Array.isArray(set) || set.length === 0) throw new PressError(`"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`); + return set.map((item, i) => { + const at = `set[${i}]`; + if (!item || typeof item !== "object") throw new PressError(`${at} is an object`); + const hasId = typeof item.id === "string"; + const hasThread = typeof item.thread === "string"; + if (hasId === hasThread) throw new PressError(`${at} names a post ("id") or a thread ("thread"), one of them`); + const key = hasId ? item.id : item.thread; + if (!ID.test(key)) throw new PressError(`${at}: "${key}" is not a post id`); + if (!JUDGE_STATES.includes(item.state)) throw new PressError(`${at}: "state" is one of ${JUDGE_STATES.join(", ")}`); + if (item.note !== undefined && typeof item.note !== "string") throw new PressError(`${at}: a note is text`); + return { ...(hasId ? { id: key } : { thread: key }), state: item.state, ...(item.note && item.state !== "undecided" ? { note: item.note } : {}) }; + }); +} + +const n = (k, what = "post") => `${k} ${what}${k === 1 ? "" : "s"}`; + +function judgedSentence(out, state) { + const skipped = out.skipped.length ? ` ${n(out.skipped.length, "id")} skipped: ${out.skipped[0].reason ?? "not judged"}.` : ""; + const did = state === "undecided" ? "cleared" : state === "keep" ? "kept" : state === "drop" ? "dropped" : state === "later" ? "marked later" : "judged"; + const archive = archiveSentence(out); + // A later chunk failed: exactly how many were written, and that the rest were not. + const failed = out.failed ? ` THE REST WERE NOT JUDGED: after ${n(out.failed.asked, "post")} the editor refused (${out.failed.error}), and ${n(out.failed.unasked, "post")} ${out.failed.unasked === 1 ? "was" : "were"} never asked. Undo puts back the ${out.written.length} that were written.` : ""; + return `${n(out.written.length, "judgement")} ${state ? did : "written"}.${skipped}${archive ? ` ${archive}` : ""}${failed}`; +} + +/** + * POST /api/library/judge. + * { lib, set: [{id | thread, state, note?}], undo? } the posts or threads named. `undo: true` is the + * undo of a press: it archives nothing (and cancels no capture already queued). + * { lib, bulk: { view, state, note? }, expect } every post the VIEW's filters match (the page's + * URL parameters), judged post by post in chunks of at most 500. `expect` is the count the confirm + * showed: when the filter no longer matches that many, nothing is judged. + * Answers { ok, written, skipped, kept, archives, sentence, undo? } — `undo` (bulk) is the set that puts + * every judged post back. + * + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {any} body + * @param {{ seenAt?: (lib: string, topic: string) => Promise<string | null> }} [deps] + */ +export async function judgePress(ask, body, deps = {}) { + const lib = libOf(body); + if ((body.set === undefined) === (body.bulk === undefined)) throw new PressError(`give "set" (the posts or threads named) or "bulk" (everything a view's filters match), one of them`); + if (body.set !== undefined) { + const set = cleanSet(body.set); + const out = await judge(ask, { slug: lib, by: OPERATOR, set, ...(body.undo === true ? { archive: false } : {}) }); + const states = new Set(set.map((s) => s.state)); + return { ok: true, ...out, sentence: body.undo === true ? `Undone: ${n(out.written.length, "judgement")} put back.` : judgedSentence(out, states.size === 1 ? set[0].state : null) }; + } + const bulk = body.bulk; + if (!bulk || typeof bulk !== "object") throw new PressError(`"bulk" is {view, state, note?}`); + if (!JUDGE_STATES.includes(bulk.state)) throw new PressError(`"bulk.state" is one of ${JUDGE_STATES.join(", ")}`); + if (bulk.note !== undefined && typeof bulk.note !== "string") throw new PressError(`"bulk.note" is text`); + if (!Number.isInteger(body.expect) || body.expect < 1) throw new PressError(`"expect" is the number of posts the confirm showed`); + const view = { ...parseLibraryView(bulk.view && typeof bulk.view === "object" ? bulk.view : {}), lib }; + const seenAt = view.fresh && view.topic && deps.seenAt ? await deps.seenAt(lib, view.topic) : null; + // The rows as they are NOW, with their own judgements: the targets, and what an undo puts back. + const rows = await listLibraryRows(ask, listingParamsOf(view, { seenAt })); + if (rows.length !== body.expect) { + throw new PressError(`The filter now matches ${n(rows.length)}, not the ${body.expect} the confirm showed: nothing was judged. Look again and press once more.`, 409); + } + // A bulk press judges POSTS. Clearing a post that is judged only through its thread would write nothing (it has + // no entry of its own): those are left out and counted, not reported as cleared. + const throughThread = bulk.state === "undecided" ? rows.filter((r) => !r.detail?.ownJudgement && r.judgement?.from === "thread") : []; + const left = new Set(throughThread.map((r) => r.id)); + const targets = rows.filter((r) => !left.has(r.id)).map((r) => ({ id: r.id })); + const notChanged = throughThread.length ? ` ${n(throughThread.length, "post")} ${throughThread.length === 1 ? "is" : "are"} judged through ${throughThread.length === 1 ? "its" : "their"} thread: not changed (clear the thread, with Judging: the whole thread).` : ""; + if (targets.length === 0) return { ok: true, written: [], skipped: [], kept: [], archives: [], asks: 0, undo: [], throughThread: throughThread.length, sentence: `Nothing cleared.${notChanged}` }; + const out = await judge(ask, { slug: lib, by: OPERATOR, set: pressSetOf(targets, bulk.state, bulk.note ?? "") }); + // The undo is of what WAS written: after a chunk that failed, the posts never asked are not in it. + const written = new Set(out.written.map((w) => w.id)); + const done = out.failed ? targets.filter((t) => written.has(t.id)) : targets; + return { ok: true, ...out, ...(out.failed ? { partial: true } : {}), throughThread: throughThread.length, undo: undoSetOf(rows, done), sentence: `${judgedSentence(out, bulk.state)}${notChanged}` }; +} + +/** + * POST /api/library/seen: { lib, topics: [<topicId>, …] } — Mark seen. The library and every topic are checked + * THROUGH THE EDITOR'S LISTING before anything is written (umtool's own state never names a library or a topic + * the editor does not hold). `mark(lib, topics)` writes (lib/library/seen.mjs markSeen). + */ +export async function seenPress(ask, body, { mark }) { + const lib = libOf(body); + if (!Array.isArray(body.topics) || body.topics.length === 0 || !body.topics.every((t) => typeof t === "string" && t)) throw new PressError(`"topics" is the list of topic ids to mark seen`); + const libraries = await listLibraries(ask); + if (!libraries.some((l) => l.slug === lib)) throw new PressError(`The editor has no library "${lib}".`, 404); + const known = new Set((await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id)); + const unknown = body.topics.filter((t) => !known.has(t)); + if (unknown.length) throw new PressError(`${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked.`, 404); + return { ok: true, ...(await mark(lib, [...new Set(body.topics)])) }; +} + +/** + * POST /api/library/watch: { lib, topic, on, intervalMinutes?, hours?, shots? } — one topic's switch, the + * operator's (so it restarts a failing watch). Answers the editor's { ok, topic, watch, sentence }. + */ +export async function watchPress(ask, body) { + const lib = libOf(body); + if (typeof body.topic !== "string" || !body.topic) throw new PressError(`"topic" is the topic's id`); + if (typeof body.on !== "boolean") throw new PressError(`"on" is true (watch the topic) or false (stop watching it)`); + const int = (k) => { + if (body[k] === undefined || body[k] === null || body[k] === "") return {}; + if (!Number.isInteger(body[k])) throw new PressError(`"${k}" is a whole number`); + return { [k]: body[k] }; + }; + return watch(ask, { + slug: lib, + topic: body.topic, + on: body.on, + ...(body.on ? { ...int("intervalMinutes"), ...int("hours"), ...(typeof body.shots === "boolean" ? { shots: body.shots } : {}) } : {}), + by: OPERATOR, + }); +} + +/** + * POST /api/library/purge: { lib, topic?, dryRun: true } counts; { lib, topic?, confirm } removes what that + * dry run showed. The operator's, in two steps. Answers the editor's purge-trending answer. + */ +export async function purgePress(ask, body) { + const lib = libOf(body); + if (body.topic !== undefined && body.topic !== null && (typeof body.topic !== "string" || !body.topic)) throw new PressError(`"topic" is a topic's id`); + const scope = { slug: lib, ...(body.topic ? { topic: body.topic } : {}) }; + if (body.dryRun === true) return purge(ask, { ...scope, dryRun: true, by: OPERATOR }); + if (typeof body.confirm !== "string" || !/^[0-9a-f]{16}$/.test(body.confirm)) throw new PressError(`A removal carries the "confirm" its dry run answered: press Purge, read what it would remove, then confirm.`); + return purge(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); +} diff --git a/umtool/lib/library/presses.test.mjs b/umtool/lib/library/presses.test.mjs @@ -0,0 +1,170 @@ +// The Posts library page's presses (lane posts-library): each one the +// editor's action with `by: "operator"` stamped on the server, whatever the +// body says. A fake `ask`: no socket. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { judgePress, PressError, purgePress, seenPress, watchPress } from "./presses.mjs"; + +function editor(rows = [], { failAt = 0 } = {}) { + const asked = []; + let judged = 0; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + if (route === "/api/ops/trending") return { ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 2, posts: rows.length, unjudged: 0 }] }; + if (route === "/api/ops/judge-trending" && ++judged === failAt) throw new Error("X is cooling down for 14 minutes"); + if (route.startsWith("/api/ops/trending?") && new URL(route, "http://x").searchParams.get("detail") !== "1") return { ok: true, topics: [{ id: "kettles" }, { id: "cups" }], posts: [], total: 0 }; + if (route.startsWith("/api/ops/trending")) { + const offset = Number(new URL(route, "http://x").searchParams.get("offset") ?? 0); + return { ok: true, total: rows.length, posts: rows.slice(offset, offset + 500) }; + } + if (route === "/api/ops/judge-trending") { + const kept = init.body.set.filter((s) => s.state === "keep" && s.id).map((s) => s.id); + return { ok: true, written: init.body.set.map(({ note: _n, ...s }) => s), skipped: [], kept, ...(kept.length && init.body.archive !== false ? { archive: { jobId: `cap-${asked.length}`, ids: kept } } : {}) }; + } + return { ok: true, echoed: init.body }; + }; + return { ask, asked, posts: () => asked.filter((a) => a.method === "POST") }; +} + +test("a press on the posts named is the operator's, whatever the body says about who", async () => { + const e = editor(); + const out = await judgePress(e.ask, { lib: "lib", by: "agent", set: [{ id: "1900000000000001001", state: "keep", note: "the opening", by: "agent" }, { thread: "1900000000000001002", state: "drop" }] }); + assert.equal(e.posts().length, 1); + assert.deepEqual(e.posts()[0].body, { slug: "lib", by: "operator", set: [{ id: "1900000000000001001", state: "keep", note: "the opening" }, { thread: "1900000000000001002", state: "drop" }] }); + assert.equal(out.ok, true); + assert.match(out.sentence, /^2 judgements written\. 1 post queued for archiving \(the editor's capture job cap-1\)\.$/); +}); + +test("an undo archives nothing", async () => { + const e = editor(); + const out = await judgePress(e.ask, { lib: "lib", undo: true, set: [{ id: "1900000000000001001", state: "keep" }, { id: "1900000000000001002", state: "undecided", note: "dropped" }] }); + assert.equal(e.posts()[0].body.archive, false); + assert.equal(e.posts()[0].body.by, "operator"); + assert.deepEqual(e.posts()[0].body.set[1], { id: "1900000000000001002", state: "undecided" }); + assert.equal(out.sentence, "Undone: 2 judgements put back."); +}); + +test("bulk: every post the view matches, in chunks of at most 500 (one capture job per chunk), with the set that undoes it", async () => { + const rows = Array.from({ length: 620 }, (_, i) => ({ id: String(1900000000000002000n + BigInt(i)), thread: String(1900000000000002000n + BigInt(i)), detail: i === 0 ? { ownJudgement: { state: "later", note: "check", by: "agent", at: "t" } } : {} })); + const e = editor(rows); + const seen = []; + const out = await judgePress(e.ask, { lib: "lib", by: "agent", bulk: { view: { lib: "other", topic: "kettles", state: "unjudged", media: "1", new: "1" }, state: "keep", note: "all of it" }, expect: 620 }, { seenAt: async (lib, topic) => (seen.push([lib, topic]), "2026-11-17T10:00:00.000Z") }); + // The view's library is the body's `lib`, never the view's own. + const lists = e.asked.filter((a) => a.route.startsWith("/api/ops/trending")); + assert.deepEqual(seen, [["lib", "kettles"]]); + assert.equal(lists[0].route, "/api/ops/trending?slug=lib&topic=kettles&limit=500&state=unjudged&media=1&since=2026-11-17T10%3A00%3A00.000Z&detail=1"); + const judged = e.posts(); + assert.deepEqual(judged.map((p) => p.body.set.length), [500, 120]); + assert.ok(judged.every((p) => p.body.by === "operator" && p.body.set.every((s) => s.state === "keep" && s.note === "all of it" && s.id))); + assert.equal(out.archives.length, 2); + assert.equal(out.undo.length, 620); + assert.deepEqual(out.undo[0], { id: rows[0].id, state: "later", note: "check" }); + assert.deepEqual(out.undo[1], { id: rows[1].id, state: "undecided" }); + assert.match(out.sentence, /^620 judgements kept\. 620 posts queued for archiving \(the editor's capture jobs cap-\d+, cap-\d+\)\.$/); +}); + +test("bulk judges nothing when the filter no longer matches the count the confirm showed", async () => { + const e = editor([{ id: "1900000000000001001", thread: "1900000000000001001" }]); + await assert.rejects(judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 3 }), (err) => err instanceof PressError && err.status === 409 && /now matches 1 post, not the 3 the confirm showed: nothing was judged/.test(err.message)); + assert.equal(e.posts().length, 0); + await assert.rejects(judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" } }), /"expect"/); +}); + +test("refused before anything is asked: no library, both or neither of set and bulk, an ill-shaped set", async () => { + const e = editor(); + for (const [body, re] of [ + [null, /JSON object/], + [{ set: [] }, /"lib"/], + [{ lib: "../x", set: [{ id: "1", state: "keep" }] }, /"lib"/], + [{ lib: "lib" }, /one of them/], + [{ lib: "lib", set: [{ id: "1", state: "keep" }], bulk: {} }, /one of them/], + [{ lib: "lib", set: [] }, /"set" is a list/], + [{ lib: "lib", set: [{ id: "1", thread: "1", state: "keep" }] }, /one of them/], + [{ lib: "lib", set: [{ id: "../x", state: "keep" }] }, /not a post id/], + [{ lib: "lib", set: [{ id: "1", state: "deleted" }] }, /"state" is one of keep, drop, later, undecided/], + [{ lib: "lib", bulk: { view: {}, state: "purge" }, expect: 1 }, /"bulk.state"/], + ]) { + await assert.rejects(judgePress(e.ask, body), re); + } + assert.equal(e.asked.length, 0); +}); + +test("the watch's switch is the operator's; off sends no terms", async () => { + const e = editor(); + await watchPress(e.ask, { lib: "lib", topic: "kettles", on: true, intervalMinutes: 30, hours: 48, shots: true, by: "agent", settings: { maxTopics: 12 }, tick: true }); + assert.deepEqual(e.posts()[0], { route: "/api/ops/watch-trending", method: "POST", body: { slug: "lib", topic: "kettles", on: true, intervalMinutes: 30, hours: 48, shots: true, by: "operator" } }); + await watchPress(e.ask, { lib: "lib", topic: "kettles", on: false, intervalMinutes: 30 }); + assert.deepEqual(e.posts()[1].body, { slug: "lib", topic: "kettles", on: false, by: "operator" }); + await assert.rejects(watchPress(e.ask, { lib: "lib", topic: "kettles" }), /"on"/); + await assert.rejects(watchPress(e.ask, { lib: "lib", on: true }), /"topic"/); + await assert.rejects(watchPress(e.ask, { lib: "lib", topic: "kettles", on: true, hours: "48" }), /"hours" is a whole number/); +}); + +test("the purge is two presses: the dry run, then the removal with the dry run's digest, both the operator's", async () => { + const e = editor(); + await purgePress(e.ask, { lib: "lib", topic: "kettles", dryRun: true, by: "agent", ids: ["1"] }); + assert.deepEqual(e.posts()[0], { route: "/api/ops/purge-trending", method: "POST", body: { slug: "lib", topic: "kettles", dryRun: true, by: "operator" } }); + await purgePress(e.ask, { lib: "lib", confirm: "FAKE-TEST-VALUE" }); + assert.deepEqual(e.posts()[1].body, { slug: "lib", confirm: "FAKE-TEST-VALUE", by: "operator" }); + await assert.rejects(purgePress(e.ask, { lib: "lib" }), /carries the "confirm" its dry run answered/); + await assert.rejects(purgePress(e.ask, { lib: "lib", confirm: "yes" }), /confirm/); + assert.equal(e.posts().length, 2); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +test("S6: a bulk press whose later chunk fails says exactly how many were written, that the rest were not, and returns the undo of what WAS written", async () => { + const rows = Array.from({ length: 620 }, (_, i) => ({ id: String(1900000000000003000n + BigInt(i)), thread: String(1900000000000003000n + BigInt(i)), detail: i === 0 ? { ownJudgement: { state: "keep", by: "agent", at: "t" } } : {} })); + const e = editor(rows, { failAt: 2 }); + const out = await judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 620 }); + assert.equal(out.ok, true); + assert.equal(out.partial, true); + assert.equal(out.written.length, 500); + assert.equal(out.sentence, "500 judgements dropped. THE REST WERE NOT JUDGED: after 500 posts the editor refused (X is cooling down for 14 minutes), and 120 posts were never asked. Undo puts back the 500 that were written."); + // The undo names the 500 written, in their order, and none of the 120. + assert.equal(out.undo.length, 500); + assert.deepEqual(out.undo[0], { id: rows[0].id, state: "keep" }); + assert.equal(out.undo.at(-1).id, rows[499].id); + assert.ok(!out.undo.some((u) => u.id === rows[500].id)); + // The first chunk failing wrote nothing: a refusal, not a partial. + const first = editor(rows, { failAt: 1 }); + await assert.rejects(judgePress(first.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 620 }), /cooling down/); +}); + +test("nit: a bulk Clear leaves posts judged only through their thread, and says how many: not changed", async () => { + const rows = [ + { id: "1900000000000004001", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t" }, detail: { ownJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "1900000000000004002", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t", from: "thread" }, detail: { threadJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "1900000000000004003", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t", from: "thread" }, detail: {} }, + ]; + const e = editor(rows); + const out = await judgePress(e.ask, { lib: "lib", bulk: { view: { state: "keep" }, state: "undecided" }, expect: 3 }); + assert.deepEqual(e.posts()[0].body.set, [{ id: "1900000000000004001", state: "undecided" }]); + assert.equal(out.throughThread, 2); + assert.equal(out.sentence, "1 judgement cleared. 2 posts are judged through their thread: not changed (clear the thread, with Judging: the whole thread)."); + assert.deepEqual(out.undo, [{ id: "1900000000000004001", state: "keep" }]); + // Only such posts: nothing is asked of the editor, and it is said. + const only = editor(rows.slice(1)); + const none = await judgePress(only.ask, { lib: "lib", bulk: { view: {}, state: "undecided" }, expect: 2 }); + assert.equal(only.posts().length, 0); + assert.equal(none.sentence, "Nothing cleared. 2 posts are judged through their thread: not changed (clear the thread, with Judging: the whole thread)."); + // Any other state judges them all, post by post. + const drop = editor(rows); + await judgePress(drop.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 3 }); + assert.equal(drop.posts()[0].body.set.length, 3); +}); + +test("nit: Mark seen checks the library and every topic through the editor's listing before anything is written", async () => { + const e = editor(); + const marks = []; + const mark = async (lib, topics) => (marks.push([lib, topics]), { slug: lib, topics: Object.fromEntries(topics.map((t) => [t, { seenAt: "2026-11-18T10:00:00.000Z" }])) }); + assert.deepEqual(await seenPress(e.ask, { lib: "lib", topics: ["kettles", "kettles", "cups"] }, { mark }), { ok: true, slug: "lib", topics: { kettles: { seenAt: "2026-11-18T10:00:00.000Z" }, cups: { seenAt: "2026-11-18T10:00:00.000Z" } } }); + assert.deepEqual(marks, [["lib", ["kettles", "cups"]]]); + await assert.rejects(seenPress(e.ask, { lib: "other", topics: ["kettles"] }, { mark }), (err) => err.status === 404 && /The editor has no library "other"/.test(err.message)); + await assert.rejects(seenPress(e.ask, { lib: "lib", topics: ["kettles", "spoons"] }, { mark }), (err) => err.status === 404 && /lib has no topic "spoons": nothing was marked/.test(err.message)); + await assert.rejects(seenPress(e.ask, { lib: "lib", topics: [] }, { mark }), /"topics"/); + assert.equal(marks.length, 1); + assert.equal(e.posts().length, 0); +}); diff --git a/umtool/lib/library/route.ts b/umtool/lib/library/route.ts @@ -0,0 +1,37 @@ +import { askEditor, clearEditorMemo, EditorError } from "@/lib/articles/generation"; +import { pressRefusal } from "@/lib/library/caller.mjs"; +import { PressError } from "@/lib/library/presses.mjs"; + +// What the Posts library's press routes share (lane posts-library). +// +// THESE ROUTES ARE THE PAGE'S, AND ONLY THE PAGE'S: every press through them +// is stamped the operator's (lib/library/presses.mjs), so a press is taken +// only from umtool's own page in a browser (lib/library/caller.mjs +// pressRefusal: what a browser sends, same-origin, to this machine). A +// request no browser sent — curl, a script, an agent, the editor, with a +// bearer or with nothing at all — is refused before its body is read, and +// sent to `pnpm ops` / `umtool library`, where a caller says who it is. + +export const NO_STORE = { "cache-control": "no-store" }; + +// A read is always asked again: a press is judged against the rows as they are NOW (a bulk press's +// targets and its undo), never an answer askEditor kept from two seconds ago. +export const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, { ...init, fresh: true }); + +/** Run one press: the caller checked, the body parsed, the press's answer, or its refusal in its own words. */ +export async function press(request: Request, run: (body: unknown) => Promise<unknown>): Promise<Response> { + const refused = pressRefusal(request.headers); + if (refused) return Response.json({ error: refused.error }, { status: refused.status, headers: NO_STORE }); + const body = await request.json().catch(() => null); + try { + return Response.json(await run(body), { headers: NO_STORE }); + } catch (err) { + const status = err instanceof PressError || err instanceof EditorError ? err.status : 500; + const reason = err instanceof EditorError ? { reason: err.reason } : {}; + return Response.json({ error: err instanceof Error ? err.message : String(err), ...reason }, { status, headers: NO_STORE }); + } finally { + // askEditor drops its kept reads when a write STARTS; a read that crossed the write on its way is + // kept again with the old answer. Dropped once more now that the write has landed. + clearEditorMemo(); + } +} diff --git a/umtool/lib/library/seen.mjs b/umtool/lib/library/seen.mjs @@ -0,0 +1,147 @@ +// "NEW SINCE LAST VISIT" (lane posts-library): when the operator pressed Mark +// seen on a topic. UMTOOL'S OWN STATE, beside the projects, never a file of +// the library (umtool writes none of those): +// +// REPORTS_ROOT/.umtool/posts-library.json +// { format: "umtool-posts-library", version: 1, +// libraries: { "<slug>": { topics: { "<topicId>": { seenAt, previous? } } } } } +// +// MOVED ONLY BY AN EXPLICIT PRESS (the page's Mark seen, `umtool library +// seen`): opening the page moves nothing, so "new" stays new until the +// operator says he has seen it, on whichever device. `previous` is the mark it +// replaced. +// +// SEVERAL PROCESSES WRITE IT (the app, `umtool library seen`): a write is a +// read-modify-rename under a LOCK FILE beside it (`posts-library.json.lock`, +// made exclusively; one left by a process that died is taken over after 10 s), +// and serialised in-process too, so two marks at once are both kept. Every +// write is a whole file to a temp name and a rename. A file that does not +// parse is never overwritten. +// +// Plain ESM. +import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; + +export const SEEN_FORMAT = "umtool-posts-library"; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const TOPIC = /^[a-z0-9][a-z0-9-]{0,119}$/; + +export function seenFile(reportsRoot) { + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "posts-library.json"); +} + +const isIso = (v) => typeof v === "string" && Number.isFinite(Date.parse(v)); + +function clean(raw) { + const libraries = {}; + const src = raw && typeof raw === "object" && raw.libraries && typeof raw.libraries === "object" ? raw.libraries : {}; + for (const [slug, lib] of Object.entries(src)) { + if (!SLUG.test(slug) || !lib || typeof lib !== "object") continue; + const topics = {}; + for (const [topic, t] of Object.entries(lib.topics && typeof lib.topics === "object" ? lib.topics : {})) { + if (!TOPIC.test(topic) || !t || !isIso(t.seenAt)) continue; + topics[topic] = { seenAt: t.seenAt, ...(isIso(t.previous) ? { previous: t.previous } : {}) }; + } + libraries[slug] = { topics }; + } + return libraries; +} + +/** + * Every mark: `{ libraries, error? }`. A missing file is empty; an unreadable one is empty with `error`. + * @param {string} reportsRoot + */ +export async function readSeen(reportsRoot) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ seenFile(reportsRoot), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { libraries: {} }; + return { libraries: {}, error: `posts-library.json cannot be read: ${err?.message ?? err}` }; + } + try { + return { libraries: clean(JSON.parse(text)) }; + } catch { + return { libraries: {}, error: "posts-library.json does not parse: nothing is marked seen until it is fixed" }; + } +} + +/** A library's marks: { [topicId]: seenAt }. */ +export async function seenOf(reportsRoot, slug) { + const { libraries } = await readSeen(reportsRoot); + return Object.fromEntries(Object.entries(libraries[slug]?.topics ?? {}).map(([t, v]) => [t, v.seenAt])); +} + +let chain = Promise.resolve(); + +export const SEEN_LOCK_STALE_MS = 10_000; +const LOCK_WAIT_MS = 5_000; + +/** Run `fn` holding the state file's lock (an exclusive create; a stale one is taken over). */ +async function locked(file, fn) { + const lock = `${file}.lock`; + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const deadline = Date.now() + LOCK_WAIT_MS; + for (;;) { + try { + const fh = await open(/* turbopackIgnore: true */ lock, "wx"); + await fh.writeFile(`${process.pid}\n`); + await fh.close(); + break; + } catch (err) { + if (err?.code !== "EEXIST") throw err; + const st = await stat(/* turbopackIgnore: true */ lock).catch(() => null); + if (st && Date.now() - st.mtimeMs > SEEN_LOCK_STALE_MS) { + await rm(/* turbopackIgnore: true */ lock, { force: true }); + continue; + } + if (Date.now() > deadline) throw new Error("posts-library.json is being written by another umtool process: nothing was marked, press again"); + await new Promise((r) => setTimeout(r, 25)); + } + } + try { + return await fn(); + } finally { + await rm(/* turbopackIgnore: true */ lock, { force: true }).catch(() => {}); + } +} + +/** + * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and + * a file that is there and does not parse. + * @param {string} reportsRoot + * @param {{ slug: string, topics: string[], now?: number }} o + * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} + */ +export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { + if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); + if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); + const run = () => locked(seenFile(reportsRoot), async () => { + const current = await readSeen(reportsRoot); + if (current.error) throw new Error(current.error); + const lib = current.libraries[slug] ?? { topics: {} }; + const seenAt = new Date(now).toISOString(); + const marked = {}; + for (const t of topics) { + const was = lib.topics[t]?.seenAt; + lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; + marked[t] = lib.topics[t]; + } + current.libraries[slug] = lib; + const file = seenFile(reportsRoot); + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = tmpPathFor(file); + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify({ format: SEEN_FORMAT, version: 1, libraries: current.libraries }, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } + return { slug, topics: marked }; + }); + const p = chain.then(run, run); + chain = p.catch(() => {}); + return p; +} diff --git a/umtool/lib/library/seen.test.mjs b/umtool/lib/library/seen.test.mjs @@ -0,0 +1,81 @@ +// Mark seen (lane posts-library): umtool's own state under a reports root's +// .umtool/, moved only by the press. A temp root, never the operator's. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { utimes } from "node:fs/promises"; +import { markSeen, readSeen, SEEN_LOCK_STALE_MS, seenFile, seenOf } from "./seen.mjs"; + +test("nothing is marked until the press; a press marks the topics named and remembers the mark it replaced", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-")); + try { + assert.deepEqual(await readSeen(root), { libraries: {} }); + assert.deepEqual(await seenOf(root, "lib"), {}); + // Reading wrote nothing. + assert.deepEqual(await readdir(root), []); + + const t1 = Date.parse("2026-11-18T10:00:00.000Z"); + assert.deepEqual(await markSeen(root, { slug: "lib", topics: ["kettles"], now: t1 }), { slug: "lib", topics: { kettles: { seenAt: "2026-11-18T10:00:00.000Z" } } }); + assert.equal(seenFile(root), path.join(root, ".umtool", "posts-library.json")); + assert.deepEqual(await seenOf(root, "lib"), { kettles: "2026-11-18T10:00:00.000Z" }); + + const t2 = Date.parse("2026-11-18T12:00:00.000Z"); + await Promise.all([markSeen(root, { slug: "lib", topics: ["kettles", "cups"], now: t2 }), markSeen(root, { slug: "other", topics: ["cups"], now: t2 })]); + const doc = JSON.parse(await readFile(seenFile(root), "utf8")); + assert.equal(doc.format, "umtool-posts-library"); + assert.deepEqual(doc.libraries.lib.topics, { kettles: { seenAt: "2026-11-18T12:00:00.000Z", previous: "2026-11-18T10:00:00.000Z" }, cups: { seenAt: "2026-11-18T12:00:00.000Z" } }); + assert.deepEqual(await seenOf(root, "other"), { cups: "2026-11-18T12:00:00.000Z" }); + assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("refused: an ill-shaped slug or topic, no topics; a file that does not parse is never written over", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-")); + try { + await assert.rejects(markSeen(root, { slug: "../x", topics: ["kettles"] }), /not a library's slug/); + await assert.rejects(markSeen(root, { slug: "lib", topics: [] }), /topic ids/); + await assert.rejects(markSeen(root, { slug: "lib", topics: ["../x"] }), /topic ids/); + await mkdir(path.join(root, ".umtool"), { recursive: true }); + await writeFile(seenFile(root), "{ not json"); + assert.match((await readSeen(root)).error, /does not parse/); + await assert.rejects(markSeen(root, { slug: "lib", topics: ["kettles"] }), /does not parse/); + assert.equal(await readFile(seenFile(root), "utf8"), "{ not json"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("nit: the write is under a lock file: it waits for another process's, takes over one left by a process that died, and leaves none behind", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-")); + try { + await mkdir(path.join(root, ".umtool"), { recursive: true }); + const lock = `${seenFile(root)}.lock`; + // Another process holds it, and writes its own mark before letting go. + await writeFile(lock, "999999\n"); + const mine = markSeen(root, { slug: "lib", topics: ["kettles"], now: Date.parse("2026-11-18T12:00:00.000Z") }); + await new Promise((r) => setTimeout(r, 120)); + assert.deepEqual(await readSeen(root), { libraries: {} }, "nothing written while the lock is held"); + await writeFile(seenFile(root), JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { lib: { topics: { cups: { seenAt: "2026-11-18T11:00:00.000Z" } } } } })); + await rm(lock); + await mine; + // Both marks are there: the read was made under the lock, after the other write. + assert.deepEqual(await seenOf(root, "lib"), { cups: "2026-11-18T11:00:00.000Z", kettles: "2026-11-18T12:00:00.000Z" }); + assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]); + + // A lock older than the limit is a dead process's. + await writeFile(lock, "999999\n"); + const old = new Date(Date.now() - SEEN_LOCK_STALE_MS - 5_000); + await utimes(lock, old, old); + await markSeen(root, { slug: "lib", topics: ["lids"] }); + assert.ok((await seenOf(root, "lib")).lids); + assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/library/undo.mjs b/umtool/lib/library/undo.mjs @@ -0,0 +1,43 @@ +// UNDO OF THE LAST PRESS (lane posts-library): the judge-trending set that +// puts back what each judged id (a post, or a thread) held before the press +// — its OWN entry's state and note, or "undecided" when it had none. +// +// It is sent with `archive: false`: an undo starts no capture, and it does not +// cancel one a keep already queued (the capture job asks, before each +// download, whether the post is still kept). The entry it restores is written +// by the operator's hand, whoever wrote the one before. +// +// Plain ESM, no imports. + +export const UNDO_SAYS = "Undo puts the judgements back, written as the operator's whoever wrote them before. It does not cancel a capture already queued."; + +const before = (j) => (j && typeof j.state === "string" ? { state: j.state, ...(typeof j.note === "string" && j.note ? { note: j.note } : {}) } : { state: "undecided" }); + +/** + * The set that undoes a press on `targets`, read from the rows as they were + * BEFORE it (the listing's detail rows: `detail.ownJudgement`, `detail.threadJudgement`). + * A target no row speaks for goes back to undecided. + * + * @param {Array<{id: string, thread: string, detail?: {ownJudgement?: object, threadJudgement?: object}}>} rows + * @param {Array<{id?: string, thread?: string}>} targets + * @returns {Array<{id?: string, thread?: string, state: string, note?: string}>} + */ +export function undoSetOf(rows, targets) { + const byId = new Map(rows.map((r) => [r.id, r])); + const byThread = new Map(); + for (const r of rows) if (!byThread.has(r.thread)) byThread.set(r.thread, r); + return targets.map((t) => + t.thread !== undefined + ? { thread: t.thread, ...before(byThread.get(t.thread)?.detail?.threadJudgement) } + : { id: t.id, ...before(byId.get(t.id)?.detail?.ownJudgement) }, + ); +} + +/** The set a press sends: every target with the state (and the note, for a judgement that is not removed). */ +export function pressSetOf(targets, state, note = "") { + return targets.map((t) => ({ + ...(t.thread !== undefined ? { thread: t.thread } : { id: t.id }), + state, + ...(note && state !== "undecided" ? { note } : {}), + })); +} diff --git a/umtool/lib/library/view.test.mjs b/umtool/lib/library/view.test.mjs @@ -0,0 +1,70 @@ +// The Posts library's view, keys and undo (lane posts-library): pure rules. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { captureSentence, filterWords, goneSentence, libraryHref, listingParamsOf, parseLibraryView } from "./filters.mjs"; +import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "./keys.mjs"; +import { pressSetOf, UNDO_SAYS, undoSetOf } from "./undo.mjs"; + +test("a view is read from the URL and written back; an ill-shaped value is dropped", () => { + const view = parseLibraryView({ lib: "trending-lib", topic: "kettles", state: "unjudged", gone: "1", media: "1", author: "@teapot_news", q: " lid ", new: "1", offset: "50" }); + assert.deepEqual(view, { lib: "trending-lib", topic: "kettles", state: "unjudged", gone: true, media: true, author: "teapot_news", q: "lid", fresh: true, offset: 50 }); + assert.equal(libraryHref(view), "/tools/library?lib=trending-lib&topic=kettles&state=unjudged&gone=1&media=1&author=teapot_news&q=lid&new=1&offset=50"); + assert.deepEqual(parseLibraryView({ lib: "../x", topic: "A B", state: "deleted", gone: "yes", author: "a/b", offset: "-3", q: ["two", "three"] }), { lib: null, topic: null, state: null, gone: false, media: false, author: null, q: "two", fresh: false, offset: 0 }); + assert.equal(libraryHref({}), "/tools/library"); + assert.equal(libraryHref({ lib: "l", state: "keep" }), "/tools/library?lib=l&state=keep"); +}); + +test("\"new\" is first shown since the topic's Mark seen; a topic never marked has no since", () => { + const view = parseLibraryView({ lib: "l", topic: "kettles", new: "1" }); + assert.equal(listingParamsOf(view, { seenAt: "2026-11-17T10:00:00.000Z" }).since, "2026-11-17T10:00:00.000Z"); + assert.equal(listingParamsOf(view).since, null); + assert.equal(listingParamsOf(parseLibraryView({ lib: "l", topic: "kettles" }), { seenAt: "2026-11-17T10:00:00.000Z" }).since, null); +}); + +test("the sentences: the filters in words, gone from the page (never deleted), a capture's state verbatim", () => { + assert.equal(filterWords(parseLibraryView({ state: "unjudged", media: "1", author: "x_y", q: "lid", gone: "1", new: "1" })), "unjudged, new since Mark seen, gone from the page, with media, by @x_y, matching “lid”"); + assert.equal(filterWords(parseLibraryView({})), ""); + assert.equal(goneSentence({ at: "2026-11-17T11:00:00.000Z", read: "r", trendId: "1" }), "Gone from the page at 2026-11-17T11:00:00.000Z"); + assert.equal(goneSentence(undefined), ""); + assert.doesNotMatch(goneSentence({ at: "t" }), /delet/i); + assert.equal(captureSentence({ state: "deleted", at: "2026-11-17T12:00:00.000Z" }), "capture: deleted at 2026-11-17T12:00:00.000Z"); + assert.equal(captureSentence({ state: "captured", at: "T" }, () => "noon"), "capture: captured at noon"); +}); + +test("the keys: one action per key, none while typing or with a modifier held", () => { + assert.equal(new Set(LIBRARY_KEYS.map((k) => k.key)).size, LIBRARY_KEYS.length); + const of = (key, extra = {}) => libraryAction({ key, ...extra }); + assert.deepEqual(["j", "k", "a", "d", "l", "c", "t", "n", "x", "u", "/", "g", "m", "?"].map((k) => of(k)), ["next", "prev", "keep", "drop", "later", "clear", "scope", "note", "select", "undo", "search", "gone", "media", "help"]); + assert.deepEqual(["A", "D", "L"].map((k) => of(k)), ["bulk-keep", "bulk-drop", "bulk-later"]); + assert.equal(of("a", { typing: true }), null); + assert.equal(of("a", { ctrlKey: true }), null); + assert.equal(of("d", { metaKey: true }), null); + assert.equal(of("q"), null); + assert.equal(isTyping({ tagName: "TEXTAREA" }), true); + assert.equal(isTyping({ tagName: "DIV", isContentEditable: true }), true); + assert.equal(isTyping({ tagName: "BUTTON" }), false); + assert.deepEqual(["keep", "drop", "later", "clear", "bulk-drop", "next"].map(stateOfAction), ["keep", "drop", "later", "undecided", "drop", null]); +}); + +test("undo puts back each id's OWN entry, or removes the judgement it had none of; a thread press restores the thread's", () => { + const rows = [ + { id: "1", thread: "1", detail: { ownJudgement: { state: "later", note: "check", by: "agent", at: "t" }, threadJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "2", thread: "1", detail: { threadJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "3", thread: "3", detail: {} }, + ]; + assert.deepEqual(undoSetOf(rows, [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "9" }]), [ + { id: "1", state: "later", note: "check" }, + // 2 had only its thread's judgement: its own goes back to none. + { id: "2", state: "undecided" }, + { id: "3", state: "undecided" }, + { id: "9", state: "undecided" }, + ]); + assert.deepEqual(undoSetOf(rows, [{ thread: "1" }, { thread: "3" }]), [{ thread: "1", state: "keep" }, { thread: "3", state: "undecided" }]); + assert.deepEqual(pressSetOf([{ id: "1" }, { thread: "3" }], "drop", "spam"), [{ id: "1", state: "drop", note: "spam" }, { thread: "3", state: "drop", note: "spam" }]); + assert.deepEqual(pressSetOf([{ id: "1" }], "undecided", "ignored"), [{ id: "1", state: "undecided" }]); + assert.match(UNDO_SAYS, /does not cancel a capture already queued/); + // S7: an undone entry becomes the operator's, and the bar says so. + assert.match(UNDO_SAYS, /written as the operator's whoever wrote them before/); +}); diff --git a/umtool/lib/report/xTrendingLibrary.test.mjs b/umtool/lib/report/xTrendingLibrary.test.mjs @@ -97,3 +97,79 @@ test("a library with posts in the ordinary place is refused by its marker: not o } }); + +// Lane posts-library (slice 3): the Posts library page reads a library ON +// PURPOSE, through the editor, and serves its captured media from one route. +// It is still no way into a project, a report, an article, the post archive or +// a site: nothing of it imports a writer of those, and the media route is the +// one reader of the corpus that REQUIRES the marker. +import { readdir, readFile as readSource } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { resolveLibraryMedia } from "../library/media.mjs"; + +const UMTOOL = fileURLToPath(new URL("../../", import.meta.url)); + +async function sourcesUnder(rel) { + const out = []; + const walk = async (dir) => { + for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + const p = path.join(dir, e.name); + if (e.isDirectory()) await walk(p); + else if (/\.(ts|tsx|mjs)$/.test(e.name) && !e.name.includes(".test.")) out.push({ rel: path.relative(UMTOOL, p), text: await readSource(p, "utf8") }); + } + }; + await walk(path.join(UMTOOL, rel)); + return out; +} + +test("posts-library: nothing of the page, its routes or its CLI imports a way into a project, a report, an article, the post archive or a site", async () => { + const files = (await Promise.all(["lib/library", "app/tools/library", "app/api/library", "components/tools/library"].map(sourcesUnder))).flat(); + assert.ok(files.length >= 14, `the Posts library's sources were read (${files.length})`); + const WAYS_OUT = [ + "addPostFromArchive", "postsCli", "postCards", "postReel", "postContext", "timelineCli", "timelineApi", "report/chain", "report/manifest", + "lib/projects", "@/lib/articles/sites", "publish", "report-draft", "build-deploy", "capture-posts", "create-channel", "writeManifest", + ]; + for (const f of files) { + const imports = [...f.text.matchAll(/from\s+"([^"]+)"|import\("([^"]+)"\)/g)].map((m) => m[1] ?? m[2]); + for (const spec of imports) { + for (const way of WAYS_OUT) assert.ok(!spec.includes(way), `${f.rel} imports ${spec}`); + } + // The editor is asked for the listing and the three presses, and nothing else. + for (const m of f.text.matchAll(/["'`](\/api\/ops\/[a-z-]+)/g)) { + assert.ok(["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"].includes(m[1]), `${f.rel} asks the editor for ${m[1]}`); + } + // No request of X or of any outside host is built here. + assert.ok(!/fetch\(\s*["'`]https?:\/\//.test(f.text), `${f.rel} fetches an outside address`); + // The corpus is never written from here. + if (!f.rel.endsWith("seen.mjs")) assert.ok(!/\b(writeFile|rename|rm|unlink|mkdir|appendFile|copyFile|symlink|link)\(/.test(f.text), `${f.rel} writes a file`); + } + // Mark seen writes umtool's own state, under the reports root's .umtool/, and nowhere in the corpus. + const seen = files.find((f) => f.rel.endsWith("seen.mjs")); + assert.match(seen.text, /reportsRoot, "\.umtool", "posts-library\.json"/); + assert.ok(!/channels|trending\//.test(seen.text.replace(/^\/\/.*$/gm, ""))); +}); + +test("posts-library: the media route's resolver serves a marked library's captured picture, and refuses the same file of a channel that is no library", async () => { + const channels = await mkdtemp(path.join(tmpdir(), "umtool-x-trending-media-")); + try { + for (const [slug, config] of [["trending-lib", { handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }], ["kettle-org-x", { handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/kettle_org" }]]) { + await mkdir(path.join(channels, slug, "trending", "posts-media", "1900000000000006001"), { recursive: true }); + await mkdir(path.join(channels, slug, "posts-media", "1900000000000006001"), { recursive: true }); + await writeFile(path.join(channels, slug, "config.json"), JSON.stringify(config)); + await writeFile(path.join(channels, slug, "trending", "posts-media", "1900000000000006001", "shot.png"), "shot trendshotmarkert6b"); + await writeFile(path.join(channels, slug, "trending", "posts-media", "1900000000000006001", "capture.json"), "{}"); + await writeFile(path.join(channels, slug, "posts-media", "1900000000000006001", "shot.png"), "an ordinary capture"); + } + const ask = (lib, name = "shot.png") => resolveLibraryMedia({ channelsDir: channels, lib, id: "1900000000000006001", name }); + assert.equal((await ask("trending-lib")).ok, true); + assert.deepEqual(await ask("kettle-org-x"), { ok: false, status: 404 }); + assert.equal((await ask("trending-lib", "capture.json")).ok, false); + // It reaches only trending/posts-media: an ordinary channel's own captures are not its to serve. + assert.match((await ask("trending-lib")).abs, /trending[\\/]posts-media[\\/]1900000000000006001[\\/]shot\.png$/); + // And the readers a video project uses still find nothing of the library. + assert.deepEqual((await postChannels(channels, null)).map((c) => c.slug), []); + assert.deepEqual(await readPostsArchive(channels, "trending-lib"), []); + } finally { + await rm(channels, { recursive: true, force: true }); + } +});