Archilyzer · Source

archilyzer

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

commit 4a83b2472310d9ac16d1f6aa488e4eb75dc28746
parent 220fe7082b2e430922f6c01151f5c718e8c0e04c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 06:36:42 -0500

common, editor, ops: `purge-trending` removes the captures of a library's dropped posts, in two steps -- a dry run counts the posts, files and bytes by the same walk the removal makes and answers a digest of the exact posts; the removal carries that digest and is the operator's (an agent's is refused, a set that changed is refused with nothing removed); only posts whose judgement in force is drop are taken, a blob another post carries is left, the judgements stay, and it is refused while a capture of the library is queued or running; `removeXTrendingPostCaptures` takes several posts together so a blob two dropped posts share goes with them; the watch's help says a failing watch waits for the operator; COMMANDS.md regenerated

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

Diffstat:
MCOMMANDS.md | 7+++++--
Mcommon/lib/xTrending/mediaStore.ts | 84++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Acommon/lib/xTrending/purge.test.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/purge.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/purge-trending/route.test.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/purge-trending/route.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/xTrendingActions.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 31+++++++++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 15++++++++++++++-
9 files changed, 574 insertions(+), 27 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 (their own, or their thread's) are taken, never one marked later, kept or undecided; an id named that is not a dropped post is listed in skipped. 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, gone, media, author, q, since, 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/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,66 @@ 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 }, +): 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++; + // 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 +395,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,148 @@ +// 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 { 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.match(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\.$/); + 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 dropped post 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 }); +}); diff --git a/common/lib/xTrending/purge.ts b/common/lib/xTrending/purge.ts @@ -0,0 +1,125 @@ +// 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 — their own, or their thread's — in one topic or +// the whole library, or of the ids named among them. 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 later keep captures the post again. +// +// 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. +// +// 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, 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 dropped posts with 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; + // Ids named that are not dropped posts of 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.`; + +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 dropped = (await listXTrending(channelRoot, { ...(ask.topic ? { topic: ask.topic } : {}), ids: true, filter: { state: "drop" } })).ids ?? []; + const isDropped = new Set(dropped); + const skipped: XTrendingPurgeResult["skipped"] = []; + let wanted = dropped; + if (ask.ids) { + wanted = []; + for (const id of new Set(ask.ids)) { + if (isDropped.has(id)) wanted.push(id); + else skipped.push({ id, reason: ask.topic ? "not a dropped post of that topic" : "not a dropped post of the library" }); + } + } + const ids: string[] = []; + for (const id of wanted) { + const st = await stat(path.join(xTrendingPostsMediaDir(channelRoot), id)).catch(() => null); + if (st?.isDirectory()) ids.push(id); + } + ids.sort(); + const confirm = xTrendingPurgeConfirm(ask.slug, ids); + if (!ask.dryRun && ask.confirm !== confirm) return { ok: false, error: PURGE_SET_CHANGED(ids.length) }; + const inFlight = ask.dryRun ? await ask.captureInFlight() : false; + let removed; + try { + removed = await removeXTrendingPostCaptures(channelRoot, ids, { captureInFlight: ask.captureInFlight, dryRun: ask.dryRun }); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const bytes = removed.bytesFreed + removed.ownBytes; + const what = `the capture${ids.length === 1 ? "" : "s"} of ${ids.length} dropped post${ids.length === 1 ? "" : "s"}: ${removed.files} file${removed.files === 1 ? "" : "s"}, ${formatPurgeBytes(bytes)}`; + const kept = removed.blobsKept ? ` ${removed.blobsKept} media file${removed.blobsKept === 1 ? "" : "s"} another post still uses ${removed.blobsKept === 1 ? "is" : "are"} left.` : ""; + const sentence = + ids.length === 0 + ? "No dropped post has a capture: nothing to remove." + : ask.dryRun + ? `Would remove ${what}.${kept} The judgements stay.` + (inFlight ? " A capture of this library is queued or running: the removal waits for it." : "") + : `Removed ${what}.${kept} The judgements stay.`; + return { + ok: true, + result: { + dryRun: ask.dryRun, + posts: ids.length, + ids, + files: removed.files, + bytes, + blobsFreed: removed.blobsFreed, + blobsKept: removed.blobsKept, + skipped, + confirm, + ...(ask.dryRun && inFlight ? { captureInFlight: true } : {}), + sentence, + }, + }; +} 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,86 @@ +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.match(dry.json.sentence, /^Would remove the capture of 1 dropped post: 1 file, 5 B\./); + 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,52 @@ +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, 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 (its own, or its thread's) — in one `topic`, the whole +// library, or the `ids` named among them (an id that is not a dropped post +// is named in `skipped`, never removed). +// +// 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. 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/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/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, gone, media, author, q, since, 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,24 @@ 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 (their own, or their thread's) are taken,", + " never one marked later, kept or undecided; an id named that is not a", + " dropped post is listed in skipped. 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 +1998,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,19 @@ 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(), /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 +1182,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/); });