commit de872117f01380996832f1bcc51d356fa179601a
parent 939897c3946c6e1a056b51aa387288471d264245
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 08:30:27 -0500
x-trending review 1 (S1, S3, S5, S7), common and editor: a purge takes the OPERATOR's drops only -- an agent's drop is counted (`agentDropped`) and left alone, by name when an id is asked for; the posts to be removed that are gone from the page are named (`gone`) and the sentence says their capture is the only copy and removing it cannot be undone, "keeping it again captures it again" being said only of the others; the set is read again inside the media index's lock immediately before the first file goes; the listing filters by the hand whose judgement is in force (`by`) and, with the topics' seen marks (`seen`), answers every topic's new posts in the same read; a failing watch's own sentence says it waits until the operator switches it on again
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
16 files changed, 327 insertions(+), 75 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -221,7 +221,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `read-x-trending` | read-x-trending reads ONE X trending page into an X trending library: {"slug", "url": "https://x.com/i/trending/<number>"}, 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/<slug>/trending/reads/<readId>/), 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": "<readId>"} parses a saved read again OFFLINE (X is asked nothing; a read left with no record takes "url" too). No fresh jar needed. --wait prints the log's @@read-x-trending {ok, mode, read, outcome, stop, responses, operations (names and sizes, never a body), posts: {onPage, added}, topic, sentence}; a capture with no post the parser knows ends ok, "read saved, nothing recognised". Refused before a job: not a library, not a trending page URL, a cap out of range, no connected X profile, X's Connect or Refresh in flight, a stale jar. A library is made with create-channel, "platform": "x-trending" (no "url", no "sites": it is private, never on a site, in no index build; "xTrendingMaxScrolls"?, "xTrendingMaxPosts"? set its caps). | `pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","probe":true}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait`<br>`pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait` |
| `judge-trending` | judge-trending judges posts of an X trending library: {"slug", "set": \[{"id" \| "thread", "state", "note"?}, ...\], "by"?}. "id" is a post of the library; "thread" a thread's ROOT post id (get trending gives each post's thread), judging every post of it that has no judgement of its own. "state": keep, drop, later, or undecided (the judgement is removed: no entry is undecided). "note": up to 2000 characters. "by": "agent" (the default) or "operator" - the caller's word: an agent says "agent". An agent's judgement is a suggestion: an agent's write over a judgement the operator made is skipped for that id and named in skipped, and the rest is written; a post the operator judged through its thread is the operator's too. Answers {written, skipped: \[{id \| thread, reason}\], kept, archive?} - kept names the posts whose judgement BECAME keep. A keep archives them: ONE capture-posts job on X's queue (a screenshot, the context, a reply's thread shot, the media), its id in archive.jobId; "archive": false marks only. When that job is refused (a stale jar, the X alert, X cooling down) the judgements are written all the same and archive.error says why; capture-posts {slug, ids, "thread": true, "keptMedia": true} archives them later. Drop deletes nothing: the post, its capture and its media stay, and a later keep puts it back. An id the library does not hold is skipped by name, not refused. | `pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}'` |
| `watch-trending` | watch-trending watches a topic of an X trending library: {"slug", "topic", "on": true, "intervalMinutes"?, "hours"?, "shots"?, "by"?}. While a topic is watched its trending page is read again every intervalMinutes (15-1440; default the library's, else 30) until hours from now (1-168; else 48), each tick the SAME single read-x-trending job on X's queue, started by the editor's own scan (once a minute, at most one read per scan, none while a trending read or capture of ANY library waits its turn: every library's ticks are one stream). A topic of several pages reads one page per tick, in turn. At most 4 topics of a library are watched at once (its maxTopics). A new post's media is fetched at once from X's media CDN, no page opened; "shots": true also screenshots every new post. "on": false stops it. A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS UNDER ITS LIMIT (60 minutes): the editor never refreshes the jar by itself, so a watch pauses when the jar goes stale (X's jar-age alert goes up, /review lists the paused watches) and resumes at the first scan after Refresh cookies on /cookies. It does not cover a night nobody presses Refresh in. That limit is the watch's own, whatever the login source or the setting: a jar whose age cannot be read, a limit set to 0 and an unreadable settings file all pause it. The X alert, a rate-limit cooldown and a missing profile pause it the same way. Three reads in a row that do not end "read" (a rate limit, a 403, a page that will not load) pause it until the operator switches it on again ("by": "operator"; an agent's ask is refused). A post a page showed before and does not show at a read whose capture shows the page's end (asked for more, the page had none, no answer failed) is recorded gone from the page at that time (get trending: gone) - never "deleted". A page X no longer has is not read again, and ends the watch when it was the topic's last. {"slug", "settings": {"maxVideoMb"?, "intervalMinutes"?, "hours"?, "maxTopics"?}} changes the library's defaults; {"slug", "tick": true} runs one scan now (refused on an idle boot; two asks at once are one scan). get trending shows each topic's watch and what it is doing (watch.sentence). | `pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":true,"intervalMinutes":30,"hours":48}'`<br>`pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","on":false}'` |
-| `purge-trending` | purge-trending removes the captures of DROPPED posts of an X trending library, in two steps. {"slug", "dryRun": true, "topic"?, "ids"?} removes nothing: it counts the dropped posts with a capture (posts, ids, files, bytes) and answers "confirm", a digest of exactly those posts. {"slug", "confirm", "by": "operator", "topic"?, "ids"?} removes them: the screenshot, the record and the media under channels/<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. | `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"}'` |
+| `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/<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. | `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) -> {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"? -> {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"? -> {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.<fmt>; 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"? -> {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"?} -> {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` |
@@ -392,7 +392,7 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending
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. The route takes more for a judge
- view (offset, state, gone, media, author, q, since, ids, detail; no
+ 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,
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
@@ -347,7 +347,15 @@ export type RemovedCaptures = RemovedCapture & { posts: number; ownBytes: number
export async function removeXTrendingPostCaptures(
channelRoot: string,
postIds: ReadonlyArray<string>,
- o: { captureInFlight: () => boolean | Promise<boolean>; dryRun?: boolean },
+ 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;
@@ -357,6 +365,10 @@ export async function removeXTrendingPostCaptures(
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);
+ 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>();
diff --git a/common/lib/xTrending/purge.test.ts b/common/lib/xTrending/purge.test.ts
@@ -12,7 +12,7 @@ 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 { purgeSentence, purgeXTrendingDropped, xTrendingPurgeConfirm } from "./purge";
import { recordXTrendingRead, writeXTrendingPosts } from "./store";
const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-purge-"));
@@ -71,7 +71,9 @@ test("a dry run counts what would go and touches nothing; a blob two dropped pos
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\.$/);
+ 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);
});
@@ -105,7 +107,7 @@ test("the removal does what the dry run said, needs its digest, and leaves the j
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.");
+ 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 () => {
@@ -146,3 +148,94 @@ test("removeXTrendingPostCaptures: a dry run of the walk equals the walk", async
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
@@ -2,16 +2,26 @@
// 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.
+// 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.
+// 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).
@@ -20,7 +30,7 @@ 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";
+import { listXTrending, readXTrendingMembership, xTrendingPostsMediaDir } from "./store";
export const X_TRENDING_PURGE_MAX_IDS = 5000;
@@ -35,7 +45,7 @@ export type XTrendingPurgeAsk = {
export type XTrendingPurgeResult = {
dryRun: boolean;
- // The dropped posts with a capture: what is (or would be) removed.
+ // The posts the operator dropped that have a capture: what is (or would be) removed.
posts: number;
ids: string[];
files: number;
@@ -45,7 +55,12 @@ export type XTrendingPurgeResult = {
blobsFreed: number;
// Blobs another post still carries: left alone.
blobsKept: number;
- // Ids named that are not dropped posts of the scope.
+ // 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
@@ -68,58 +83,101 @@ export function formatPurgeBytes(n: number): string {
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 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 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) {
- 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 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, ids, { captureInFlight: ask.captureInFlight, dryRun: ask.dryRun });
+ 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 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,
- },
+ 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
@@ -433,6 +433,11 @@ test("the filters: the judgement in force, gone, media, author, words, first see
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 });
@@ -487,6 +492,23 @@ test("detail: a topic's counts, the accounts, the rest of the record, the first
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
@@ -718,6 +718,9 @@ export type XTrendingTopicRow = {
// 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;
@@ -821,6 +824,9 @@ export type XTrendingListFilter = {
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[] {
@@ -854,6 +860,9 @@ export async function listXTrending(
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();
@@ -874,6 +883,7 @@ export async function listXTrending(
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)) {
@@ -881,17 +891,22 @@ export async function listXTrending(
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: [] };
- const firstSeenAt = m.seen.reduce((a, s) => (a === "" || s.at < a ? s.at : a), "");
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;
@@ -953,6 +968,7 @@ export async function listXTrending(
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,
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/editor/app/api/ops/purge-trending/route.test.ts b/editor/app/api/ops/purge-trending/route.test.ts
@@ -56,7 +56,8 @@ test("the dry run counts and removes nothing; the removal is the operator's, wit
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(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.
diff --git a/editor/app/api/ops/purge-trending/route.ts b/editor/app/api/ops/purge-trending/route.ts
@@ -6,16 +6,21 @@ 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 }
+// 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 (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).
+// 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
@@ -26,7 +31,8 @@ export const dynamic = "force-dynamic";
// 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
+// 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
diff --git a/editor/app/api/ops/trending/route.test.ts b/editor/app/api/ops/trending/route.test.ts
@@ -75,6 +75,15 @@ test("filters, pages, ids and detail", async () => {
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 () => {
@@ -84,6 +93,10 @@ test("refused with a sentence: an unknown parameter, a state, a flag, an author,
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
@@ -60,6 +60,12 @@ export const dynamic = "force-dynamic";
// 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,
@@ -70,7 +76,7 @@ export const dynamic = "force-dynamic";
// threadShot?, media: [{name, kind, bytes}], context?:
// {parent?, quoted?}}}. A capture's files are NAMES under
// trending/posts-media/<id>/: this route serves no bytes.
-const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "ids", "detail"];
+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) {
@@ -134,6 +140,25 @@ export async function GET(request: Request) {
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));
@@ -144,6 +169,7 @@ export async function GET(request: Request) {
...(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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1327,7 +1327,7 @@ export function usage() {
" 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. The route takes more for a judge",
- " view (offset, state, gone, media, author, q, since, ids, detail; no",
+ " 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,",
@@ -1969,9 +1969,13 @@ export function usage() {
" 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",
+ " 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",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1168,6 +1168,7 @@ test("purge-trending posts its body; its help says the removal is the operator's
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/);
diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs
@@ -34,7 +34,7 @@ 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 someone switches it on again: ${w.paused.sentence}`;
+ 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.`;
}