Archilyzer · Source

archilyzer

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

commit a3d823bb1f7e53cd7983800a19ffcd7807765364
parent 93d8c161ff94870d4108cbf2c5dc20f0de034292
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 01:22:08 -0500

x-trending: judge-trending writes a library's judgements through one writer

keep / drop / later per post or per thread (keyed by its root post's id), with who decided, when and a note; undecided removes the entry. An agent's write over the operator's judgement is skipped for that id and reported. The listing carries each post's thread and its own judgement, else its thread's. Editor action, /api/ops/judge-trending and the pnpm ops row; COMMANDS.md regenerated.

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

Diffstat:
MCOMMANDS.md | 7+++++--
Acommon/lib/xTrending/judgements.test.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/judgements.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.test.ts | 2++
Mcommon/lib/xTrending/store.ts | 94++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Aeditor/app/api/ops/judge-trending/route.test.ts | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/judge-trending/route.ts | 41+++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/trending/route.ts | 10++++++----
Meditor/app/channels/[slug]/xTrendingActions.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/xTrending.ts | 2+-
Mscripts/archilyzer-ops.mjs | 24++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 11++++++++++-
12 files changed, 627 insertions(+), 28 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -219,6 +219,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -&gt; {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` | | `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates &lt;handle&gt;-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -&gt; {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -&gt; {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` | | `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". 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. Answers {written, skipped: \[{id \| thread, reason}\], kept} - kept names the posts whose judgement BECAME keep. 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"}]}'` | | `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` | @@ -378,8 +379,10 @@ get trending <slug> [--topic <topicId>] [--limit <n>] is an X trending judgement?}] (the newest read's first, in page order; --limit 1-500, default 100; total is the count before it) and reads (the saved reads' ids, newest first). thumbnail is a captured post's first picture - (trending/posts-media/<id>/<name>, relative to the channel); judgement - is {state: keep | drop | undecided, note?, by, at} once a post has one. Never the + (trending/posts-media/<id>/<name>, relative to the channel); thread is + the root post id of the thread a post belongs to; judgement is {state: + keep | drop | later, note?, by, at, from?} once a post has one (its own, + or its thread's: from "thread"); no judgement is undecided. Never the raw capture, a cookie or a token. 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/lib/xTrending/judgements.test.ts b/common/lib/xTrending/judgements.test.ts @@ -0,0 +1,149 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { judgeXTrending, JUDGED_BY_OPERATOR, NOT_IN_THE_LIBRARY, xTrendingJudgeProblem } from "./judgements"; +import { listXTrending, readXTrendingJudgementsFile, recordXTrendingRead, writeXTrendingPosts } from "./store"; +import type { Post } from "../posts"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-judge-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const READ = "tr-01JA0000000000000000000000"; +const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }; + +function post(id: string, extra: Partial<Post> = {}): Post { + return { + id, + slug: `lib/${id}`, + channelSlug: "lib", + author: "kettle_fan", + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text: `post ${id}`, + url: `https://x.com/kettle_fan/status/${id}`, + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + ...extra, + }; +} + +// 501 a root; 502 answers 501; 503 answers 502; 504 alone; 505 answers a post +// the library does not hold (900). +async function library(name: string): Promise<string> { + const dir = path.join(TMP, name); + const posts = [ + post("501"), + post("502", { isReply: true, replyTo: { platform: "twitter", id: "501" } }), + post("503", { isReply: true, replyTo: { platform: "twitter", id: "502" } }), + post("504"), + post("505", { isReply: true, replyTo: { platform: "twitter", id: "900" } }), + ]; + await writeXTrendingPosts(dir, posts); + await recordXTrendingRead(dir, { readId: READ, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: posts.map((p) => p.id), added: posts.length }); + return dir; +} + +const clock = (iso: string) => () => Date.parse(iso); + +test("a judgement is written with who decided and when, and the listing carries it", async () => { + const dir = await library("write"); + const r = await judgeXTrending( + dir, + { by: "agent", set: [{ id: "504", state: "keep", note: " the opening " }, { id: "501", state: "later" }] }, + { now: clock("2026-11-17T11:00:00.000Z") }, + ); + assert.deepEqual(r.written, [{ id: "504", state: "keep" }, { id: "501", state: "later" }]); + assert.deepEqual(r.skipped, []); + assert.deepEqual(r.kept, ["504"]); + const file = JSON.parse(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8")); + assert.deepEqual(file, { + version: 1, + posts: { + "504": { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" }, + "501": { state: "later", by: "agent", at: "2026-11-17T11:00:00.000Z" }, + }, + threads: {}, + }); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.equal(rows["504"].judgement?.state, "keep"); + assert.equal(rows["502"].judgement, undefined); +}); + +test("an agent never replaces the operator's judgement: skipped per id, the rest written", async () => { + const dir = await library("agent"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "501", state: "drop" }] }, { now: clock("2026-11-17T11:00:00.000Z") }); + const r = await judgeXTrending( + dir, + { by: "agent", set: [{ id: "501", state: "keep" }, { id: "504", state: "keep" }] }, + { now: clock("2026-11-17T12:00:00.000Z") }, + ); + assert.deepEqual(r.written, [{ id: "504", state: "keep" }]); + assert.deepEqual(r.skipped, [{ id: "501", reason: JUDGED_BY_OPERATOR }]); + // Nor may an agent clear it. + const cleared = await judgeXTrending(dir, { by: "agent", set: [{ id: "501", state: "undecided" }] }); + assert.deepEqual(cleared.skipped, [{ id: "501", reason: JUDGED_BY_OPERATOR }]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["501"].state, "drop"); + // The operator overturns the agent. + const over = await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "drop" }] }, { now: clock("2026-11-17T13:00:00.000Z") }); + assert.deepEqual(over.written, [{ id: "504", state: "drop" }]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["504"].by, "operator"); +}); + +test("drop is reversible, and undecided removes the entry", async () => { + const dir = await library("reverse"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "drop" }] }); + const back = await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "keep" }] }); + assert.deepEqual(back.kept, ["504"]); + // Keep again: nothing BECAME keep. + assert.deepEqual((await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "keep", note: "still" }] })).kept, []); + await judgeXTrending(dir, { by: "operator", set: [{ id: "504", state: "undecided" }] }); + assert.deepEqual((await readXTrendingJudgementsFile(dir)).posts, {}); +}); + +test("a thread is judged by its root post's id; a post's own judgement comes first", async () => { + const dir = await library("thread"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "503", state: "drop" }] }); + const r = await judgeXTrending(dir, { by: "agent", set: [{ thread: "501", state: "keep", note: "the whole exchange" }] }); + assert.deepEqual(r.written, [{ thread: "501", state: "keep" }]); + // 501 and 502 became keep through the thread; 503 has its own (drop). + assert.deepEqual(r.kept, ["501", "502"]); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.equal(rows["501"].thread, "501"); + assert.equal(rows["503"].thread, "501"); + assert.deepEqual(rows["502"].judgement && { state: rows["502"].judgement.state, from: rows["502"].judgement.from }, { state: "keep", from: "thread" }); + assert.equal(rows["503"].judgement?.state, "drop"); + assert.equal(rows["503"].judgement?.from, undefined); + // A thread whose root the library lacks is keyed by that root all the same. + assert.equal(rows["505"].thread, "900"); + const t = await judgeXTrending(dir, { by: "agent", set: [{ thread: "900", state: "later" }] }); + assert.deepEqual(t.written, [{ thread: "900", state: "later" }]); +}); + +test("an id the library does not hold is skipped by name, and nothing is written for it", async () => { + const dir = await library("stray"); + const r = await judgeXTrending(dir, { by: "agent", set: [{ id: "999", state: "keep" }, { thread: "998", state: "keep" }] }); + assert.deepEqual(r.written, []); + assert.deepEqual(r.skipped, [ + { id: "999", reason: NOT_IN_THE_LIBRARY }, + { thread: "998", reason: NOT_IN_THE_LIBRARY }, + ]); + assert.equal(existsSync(path.join(dir, "trending", "judgements.json")), false); +}); + +test("the ask's shape is refused with a sentence", () => { + const ok = { by: "agent", set: [{ id: "1", state: "keep" }] }; + assert.equal(xTrendingJudgeProblem(ok), null); + assert.match(xTrendingJudgeProblem({ ...ok, by: "someone" })!, /"by" is who decided/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [] })!, /"set" is a list/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", thread: "1", state: "keep" }] })!, /one of them/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "../x", state: "keep" }] })!, /not a post id/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "maybe" }] })!, /keep, drop, later or undecided/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "undecided", note: "x" }] })!, /carries no note/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep", topic: "t" }] })!, /unknown key/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep" }, { id: "1", state: "drop" }] })!, /judged twice/); + assert.match(xTrendingJudgeProblem({ by: "agent", set: [{ id: "1", state: "keep", note: "n".repeat(2001) }] })!, /at most 2000/); +}); diff --git a/common/lib/xTrending/judgements.ts b/common/lib/xTrending/judgements.ts @@ -0,0 +1,156 @@ +// THE ONE WRITER OF A LIBRARY'S judgements.json (lane x-trending-2) — the +// editor's `judge-trending`, for an agent and for the operator alike. +// +// keep | drop | later written as the post's (or the thread's) judgement, +// with who decided and when, and a note; +// undecided the entry is REMOVED: no entry is undecided. +// +// AN AGENT'S JUDGEMENT IS A SUGGESTION. A write `by: "agent"` over an entry the +// operator made is SKIPPED for that id and reported; nothing forces it. The +// operator overturns anything. +// +// A THREAD is judged by its root post's id (store.ts xTrendingThreadKey): a +// post of it with no judgement of its own is taken to be the thread's. +// +// DROP DELETES NOTHING. A dropped post keeps its record, its capture and its +// media, and a later keep puts it back. (Removing a capture is +// mediaStore.ts removeXTrendingPostCapture, asked for by nobody in this +// slice.) +// +// Every write is under the file's lock and atomic. SERVER-ONLY (node:fs). + +import { withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; +import type { Post } from "../posts"; +import { + readXTrendingJudgementsFile, + readXTrendingMembership, + readXTrendingPosts, + X_TRENDING_JUDGEMENT_STATES, + xTrendingJudgementsPath, + xTrendingThreadKey, + type XTrendingJudgement, + type XTrendingJudgementState, +} from "./store"; + +export const X_TRENDING_NOTE_MAX = 2000; +export const X_TRENDING_JUDGE_MAX = 500; + +export type XTrendingJudgeBy = "agent" | "operator"; +export type XTrendingJudgeState = XTrendingJudgementState | "undecided"; + +export type XTrendingJudgeItem = { + // A post's id, or a thread's root post id: one of them. + id?: string; + thread?: string; + state: XTrendingJudgeState; + note?: string; +}; + +export type XTrendingJudgeAsk = { by: XTrendingJudgeBy; set: ReadonlyArray<XTrendingJudgeItem> }; + +// Why this is not a judge ask, or null. Shape only: whether each id is in the +// library is asked of the disk, per id, by the writer. +export function xTrendingJudgeProblem(ask: { by?: unknown; set?: unknown }): string | null { + if (ask.by !== "agent" && ask.by !== "operator") return `"by" is who decided: "agent" or "operator"`; + if (!Array.isArray(ask.set) || ask.set.length === 0) { + return `"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`; + } + if (ask.set.length > X_TRENDING_JUDGE_MAX) return `"set" holds at most ${X_TRENDING_JUDGE_MAX} judgements`; + const seen = new Set<string>(); + for (const [i, raw] of ask.set.entries()) { + const at = `set[${i}]`; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${at} is not an object`; + const item = raw as Record<string, unknown>; + const unknown = Object.keys(item).filter((k) => !["id", "thread", "state", "note"].includes(k)); + if (unknown.length) return `${at}: unknown key(s) ${unknown.join(", ")} (id, thread, state, note)`; + const hasId = item.id !== undefined; + const hasThread = item.thread !== undefined; + if (hasId === hasThread) return `${at}: give "id" (a post) or "thread" (a thread's root post id), one of them`; + const key = hasId ? item.id : item.thread; + if (typeof key !== "string" || !/^\d{1,25}$/.test(key)) return `${at}: "${String(key)}" is not a post id`; + const state = item.state; + if (state !== "undecided" && !X_TRENDING_JUDGEMENT_STATES.includes(state as XTrendingJudgementState)) { + return `${at}: "state" is keep, drop, later or undecided`; + } + if (item.note !== undefined) { + if (typeof item.note !== "string") return `${at}: "note" is text`; + if (item.note.length > X_TRENDING_NOTE_MAX) return `${at}: a note is at most ${X_TRENDING_NOTE_MAX} characters`; + if (state === "undecided" && item.note.trim()) return `${at}: "undecided" removes the judgement, so it carries no note`; + } + const mark = `${hasId ? "p" : "t"}:${key}`; + if (seen.has(mark)) return `${at}: ${hasId ? "post" : "thread"} ${key} is judged twice in one ask`; + seen.add(mark); + } + return null; +} + +export type XTrendingJudged = { id?: string; thread?: string; state: XTrendingJudgeState }; +export type XTrendingJudgeSkipped = { id?: string; thread?: string; reason: string }; + +export type XTrendingJudgeResult = { + written: XTrendingJudged[]; + skipped: XTrendingJudgeSkipped[]; + // Posts whose judgement BECAME keep by this ask (their own, or their + // thread's): what a keep archives. + kept: string[]; +}; + +export const JUDGED_BY_OPERATOR = "judged by the operator: an agent's judgement does not replace it"; +export const NOT_IN_THE_LIBRARY = "not in this library"; + +// The ask applied. `posts` is the library's posts when the caller has them. +export async function judgeXTrending( + channelRoot: string, + ask: XTrendingJudgeAsk, + opts: { now?: () => number; posts?: ReadonlyArray<Post> } = {}, +): Promise<XTrendingJudgeResult> { + const problem = xTrendingJudgeProblem(ask); + if (problem) throw new Error(problem); + const at = new Date((opts.now ?? Date.now)()).toISOString(); + const [membership, posts] = await Promise.all([ + readXTrendingMembership(channelRoot), + opts.posts ?? readXTrendingPosts(channelRoot), + ]); + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + const threadOf = new Map<string, string>(); + const members = new Map<string, string[]>(); + for (const p of byId.values()) { + const key = xTrendingThreadKey(p, byId); + threadOf.set(p.id, key); + members.set(key, [...(members.get(key) ?? []), p.id]); + } + return withJsonFileLock(xTrendingJudgementsPath(channelRoot), async () => { + const file = await readXTrendingJudgementsFile(channelRoot); + const effective = (id: string) => file.posts[id]?.state ?? file.threads[threadOf.get(id) ?? ""]?.state; + const before = new Map([...byId.keys()].map((id) => [id, effective(id)])); + const written: XTrendingJudged[] = []; + const skipped: XTrendingJudgeSkipped[] = []; + for (const item of ask.set) { + const isThread = item.thread !== undefined; + const key = (isThread ? item.thread : item.id) as string; + const name = isThread ? { thread: key } : { id: key }; + if (isThread ? !members.has(key) : !byId.has(key)) { + skipped.push({ ...name, reason: NOT_IN_THE_LIBRARY }); + continue; + } + const map = isThread ? file.threads : file.posts; + const have: XTrendingJudgement | undefined = map[key]; + if (ask.by === "agent" && have?.by === "operator") { + skipped.push({ ...name, reason: JUDGED_BY_OPERATOR }); + continue; + } + if (item.state === "undecided") { + if (have) delete map[key]; + } else { + const note = item.note?.trim(); + map[key] = { state: item.state, ...(note ? { note } : {}), by: ask.by, at }; + } + written.push({ ...name, state: item.state }); + } + if (written.length > 0) { + await writeJsonAtomic(xTrendingJudgementsPath(channelRoot), file, { mkdir: true }); + } + const kept = [...byId.keys()].filter((id) => effective(id) === "keep" && before.get(id) !== "keep").sort(); + return { written, skipped, kept }; + }); +} diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -192,6 +192,7 @@ test("the listing gives each post's words, author, media, reads and topic — an media: { count: 2, kinds: ["image"] }, topic: "kettles", reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }], + thread: "301", }, { id: "302", @@ -202,6 +203,7 @@ test("the listing gives each post's words, author, media, reads and topic — an media: { count: 0, kinds: [] }, topic: "kettles", reads: [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z" }], + thread: "302", }, ]); assert.equal(all.total, 2); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -28,12 +28,17 @@ // disk, with no editor-only import, so umtool's Posts library page (slice 3) // reads a library exactly as the editor does. // -// channels/<lib>/trending/judgements.json RESERVED for slice 3: post id → -// {state: "keep" | "drop" | "undecided", note?, by: "agent" | -// "operator", at}. Written by ONE writer, the editor's `judge-trending` -// ({slug, by, set: [{id, state, note?, topic?}]}), not built yet; the -// listing already reads it, so a row carries its judgement once one -// exists. +// channels/<lib>/trending/judgements.json post id → {state: "keep" | +// "drop" | "later", note?, by: "agent" | "operator", at}, and the same +// per THREAD (keyed by its root post's id). No entry = undecided. +// Written by ONE writer, lib/xTrending/judgements.ts (the editor's +// `judge-trending`); read here, so a row carries its judgement. +// channels/<lib>/trending/watch.json the watched topics +// (lib/xTrending/watch.ts is its one writer) +// channels/<lib>/trending/posts-media/<id>/ a captured post: its shot, its +// capture.json and its media, each media file a HARDLINK to +// channels/<lib>/trending/media-store/ the library's media, once per +// content hash, with media-index.json (lib/xTrending/mediaStore.ts) // // SERVER-ONLY (node:fs). @@ -121,10 +126,11 @@ function judgementsPath(channelRoot: string): string { return path.join(trendingDir(channelRoot), "judgements.json"); } -export type XTrendingJudgementState = "keep" | "drop" | "undecided"; -export const X_TRENDING_JUDGEMENT_STATES: readonly XTrendingJudgementState[] = ["keep", "drop", "undecided"]; +// "later" is a decision put off by someone; no entry is a post nobody has +// judged (undecided). Clearing a judgement removes the entry. +export type XTrendingJudgementState = "keep" | "drop" | "later"; +export const X_TRENDING_JUDGEMENT_STATES: readonly XTrendingJudgementState[] = ["keep", "drop", "later"]; -// A post's judgement (slice 3 writes it; this slice only reads it). export type XTrendingJudgement = { state: XTrendingJudgementState; note?: string; @@ -132,13 +138,22 @@ export type XTrendingJudgement = { at: string; }; -// judgements.json, or {} while there is none. Ill-shaped entries are dropped. -export async function readXTrendingJudgements(channelRoot: string): Promise<Record<string, XTrendingJudgement>> { - const read = await readJsonFile(judgementsPath(channelRoot)); - const posts = read.ok ? (read.value as { posts?: unknown } | null)?.posts : null; - if (!posts || typeof posts !== "object" || Array.isArray(posts)) return {}; +export type XTrendingJudgementsFile = { + version: 1; + posts: Record<string, XTrendingJudgement>; + // A thread's judgement, keyed by its root post's id: what a post of the + // thread with no judgement of its own is taken to be. + threads: Record<string, XTrendingJudgement>; +}; + +export function xTrendingJudgementsPath(channelRoot: string): string { + return judgementsPath(channelRoot); +} + +function parseJudgements(raw: unknown): Record<string, XTrendingJudgement> { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const out: Record<string, XTrendingJudgement> = {}; - for (const [id, j] of Object.entries(posts as Record<string, Partial<XTrendingJudgement> | null>)) { + for (const [id, j] of Object.entries(raw as Record<string, Partial<XTrendingJudgement> | null>)) { if (!/^\d+$/.test(id) || !j || typeof j !== "object") continue; if (!X_TRENDING_JUDGEMENT_STATES.includes(j.state as XTrendingJudgementState)) continue; if ((j.by !== "agent" && j.by !== "operator") || typeof j.at !== "string" || !j.at) continue; @@ -152,6 +167,40 @@ export async function readXTrendingJudgements(channelRoot: string): Promise<Reco return out; } +// judgements.json whole, or an empty one while there is none. Ill-shaped +// entries are dropped. +export async function readXTrendingJudgementsFile(channelRoot: string): Promise<XTrendingJudgementsFile> { + const read = await readJsonFile(judgementsPath(channelRoot)); + const value = read.ok ? (read.value as { posts?: unknown; threads?: unknown } | null) : null; + return { version: 1, posts: parseJudgements(value?.posts), threads: parseJudgements(value?.threads) }; +} + +// The posts' own judgements. +export async function readXTrendingJudgements(channelRoot: string): Promise<Record<string, XTrendingJudgement>> { + return (await readXTrendingJudgementsFile(channelRoot)).posts; +} + +// A THREAD'S KEY is its root post's id: the post's own `threadId` when the +// source gave one, else the chain of posts it answers, followed through the +// library's posts as far as they go (the first ancestor the library lacks is +// the root as far as anyone here knows). A post that answers nothing is its +// own thread. +export function xTrendingThreadKey(post: Post, byId: ReadonlyMap<string, Post>): string { + if (post.threadId && /^\d+$/.test(post.threadId)) return post.threadId; + let at = post; + const walked = new Set<string>([post.id]); + for (let hops = 0; hops < 64; hops++) { + const parent = at.replyTo?.id; + if (!parent || !/^\d+$/.test(parent)) return at.id; + const next = byId.get(parent); + if (!next || walked.has(parent)) return parent; + if (next.threadId && /^\d+$/.test(next.threadId)) return next.threadId; + walked.add(parent); + at = next; + } + return at.id; +} + const IMAGE_FILE = /\.(?:jpe?g|png|webp|gif)$/i; // WHERE A LIBRARY'S CAPTURED MEDIA LIVES (review 2 N9): under trending/, as @@ -506,7 +555,10 @@ export type XTrendingPostRow = { media: XTrendingMedia & { thumbnail?: string }; topic: string; reads: Array<{ read: string; trendId: string; at: string }>; - judgement?: XTrendingJudgement; + // The thread it belongs to: its root post's id (xTrendingThreadKey). + thread: string; + // Its own judgement, else its thread's (`from: "thread"`). Absent: undecided. + judgement?: XTrendingJudgement & { from?: "thread" }; }; export type XTrendingListing = { @@ -542,7 +594,7 @@ export async function listXTrending( readXTrendingTopics(channelRoot), readXTrendingMembership(channelRoot), listXTrendingReadIds(channelRoot), - readXTrendingJudgements(channelRoot), + readXTrendingJudgementsFile(channelRoot), ]); const archived = new Map((opts.posts ?? (await readXTrendingPosts(channelRoot))).map((p) => [p.id, p])); const count = new Map<string, number>(); @@ -554,6 +606,7 @@ export async function listXTrending( if (opts.topic && m.topic !== opts.topic) continue; const post = archived.get(id); if (!post) continue; + const thread = xTrendingThreadKey(post, archived); rows.push({ id, author: post.author, @@ -564,7 +617,12 @@ export async function listXTrending( media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] }, topic: m.topic, reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })), - ...(judgements[id] ? { judgement: judgements[id] } : {}), + thread, + ...(judgements.posts[id] + ? { judgement: judgements.posts[id] } + : judgements.threads[thread] + ? { judgement: { ...judgements.threads[thread], from: "thread" as const } } + : {}), }); } const rank = (id: string) => { diff --git a/editor/app/api/ops/judge-trending/route.test.ts b/editor/app/api/ops/judge-trending/route.test.ts @@ -0,0 +1,110 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { 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/judge-trending/route.test.ts" +// +// judge-trending over ops (lane x-trending-2), against a temp corpus: the +// refusals, a write by an agent, the operator's judgement an agent cannot +// replace, and the listing carrying what was written. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-judge-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" }); +await writeFile( + path.join(lib, "trending", "posts", "2026-11.jsonl"), + [A, B] + .map((id) => + 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: [], + }), + ) + .join("\n") + "\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", "membership.json"), + JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen }, [B]: { topic: "kettles", seen } } }), +); + +const judge = (await import("./route")).POST; +const listing = (await import("../trending/route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function call(body: Record<string, unknown>, token = "test-token") { + const res = await judge( + new Request("http://localhost/api/ops/judge-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, unknown> }; +} + +test("judge-trending refuses with a sentence", async () => { + assert.equal((await call({ slug: "trending", set: [{ id: A, state: "keep" }] }, "wrong")).status, 401); + for (const [body, re] of [ + [{ slug: "nope", set: [{ id: A, state: "keep" }] }, /No such channel: nope/], + [{ slug: "account-x", set: [{ id: A, state: "keep" }] }, /not an X trending library/], + [{ slug: "trending" }, /"set" is a list of judgements/], + [{ slug: "trending", set: [] }, /"set" is a list of judgements/], + [{ slug: "trending", set: [{ id: A, state: "maybe" }] }, /keep, drop, later or undecided/], + [{ slug: "trending", set: [{ id: A, state: "keep" }], by: "someone" }, /"by" is who decided/], + [{ slug: "trending", set: [{ id: A, state: "keep" }], force: true }, /unknown key\(s\): force/], + ] as const) { + const r = await call(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.json.error), re); + } +}); + +test("an agent's judgement is written; the operator's is not replaced by an agent; the listing carries both", async () => { + const first = await call({ slug: "trending", set: [{ id: A, state: "keep", note: "the opening" }, { id: "42", state: "keep" }] }); + assert.equal(first.status, 200); + assert.deepEqual(first.json.written, [{ id: A, state: "keep" }]); + assert.deepEqual(first.json.skipped, [{ id: "42", reason: "not in this library" }]); + assert.deepEqual(first.json.kept, [A]); + const op = await call({ slug: "trending", by: "operator", set: [{ id: A, state: "drop" }, { id: B, state: "later" }] }); + assert.deepEqual(op.json.written, [{ id: A, state: "drop" }, { id: B, state: "later" }]); + const again = await call({ slug: "trending", set: [{ id: A, state: "keep" }] }); + assert.equal(again.status, 200); + assert.deepEqual(again.json.written, []); + assert.match(JSON.stringify(again.json.skipped), /judged by the operator/); + const file = JSON.parse(await readFile(path.join(lib, "trending", "judgements.json"), "utf8")); + assert.equal(file.posts[A].state, "drop"); + assert.equal(file.posts[A].by, "operator"); + const res = await listing(new Request("http://localhost/api/ops/trending?slug=trending", { headers: { authorization: "Bearer test-token" } })); + const rows = ((await res.json()) as { posts: Array<{ id: string; judgement?: { state: string } }> }).posts; + assert.deepEqual(rows.map((p) => [p.id, p.judgement?.state]).sort(), [[A, "drop"], [B, "later"]]); +}); diff --git a/editor/app/api/ops/judge-trending/route.ts b/editor/app/api/ops/judge-trending/route.ts @@ -0,0 +1,41 @@ +import { NextResponse } from "next/server"; +import { judgeXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; +import { OpsInputError, ops, opsFail, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, set: [{id | thread, state, note?}, …], by? } +// -> { ok: true, slug, written: [{id | thread, state}], +// skipped: [{id | thread, reason}], kept: [<post id>, …] } +// +// JUDGE POSTS OF AN X TRENDING LIBRARY (lane x-trending-2), written to +// `channels/<slug>/trending/judgements.json` by its one writer: +// +// id a post of the library } one of them +// thread a thread's ROOT post id: every post of the thread with no +// judgement of its own is taken to be the thread's +// state keep | drop | later, or undecided (the judgement is removed: no +// entry is undecided) +// note up to 2000 characters, kept with the judgement +// by "agent" (the default here) or "operator" (the channel page's +// buttons). 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`; the rest of the ask is written. +// +// `kept` names the posts whose judgement BECAME keep by this ask (their own, +// or their thread's). DROP DELETES NOTHING: the post, its capture and its +// media stay, and a later keep puts it back. +// +// Refused with a sentence: no such channel, not a library, an ill-shaped set +// (an unknown key, both or neither of id and thread, a state that is none of +// the four, a note on "undecided", an id judged twice). An id the library +// does not hold is not a refusal: it is skipped by name. +export async function POST(request: Request) { + return ops(request, ["slug", "set", "by"], async (body) => { + const by = body.by === undefined ? "agent" : body.by; + if (body.set === undefined) throw new OpsInputError(`"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`); + const result = await judgeXTrendingAction({ slug: reqSlug(body, "slug"), by, set: body.set }); + if (!result.ok) return opsFail(result.error); + return NextResponse.json(result); + }); +} diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -13,7 +13,7 @@ export const dynamic = "force-dynamic"; // title?, summary?, reads, lastReadAt}]}], // posts: [{id, author, authorName?, createdAt, url, text, // media: {count, kinds, thumbnail?}, topic, -// reads: [{read, trendId, at}], judgement?}], +// reads: [{read, trendId, at}], thread, judgement?}], // total, reads: [<readId>, …] } // // An X trending library's topics and posts (lane x-trending) — `pnpm ops get @@ -26,9 +26,11 @@ export const dynamic = "force-dynamic"; // Everything a list view needs per post. `media.thumbnail` is the first // captured picture's path relative to the channel // (`trending/posts-media/<id>/<name>` — a library's media is kept under trending/, -// and no route serves it yet), present once the post is captured; `judgement` ({state: keep | drop | undecided, note?, by: -// agent | operator, at}) once it has one (written by `judge-trending`, a later -// slice). NEVER the raw capture, a cookie or a token. +// and no route serves it yet), present once the post is captured; `thread` is +// the root post id of the thread it belongs to; `judgement` ({state: keep | +// drop | later, note?, by: agent | operator, at, from?}) is its own, else its +// thread's (`from: "thread"`), written by `judge-trending`; a post with none +// is undecided. NEVER the raw capture, a cookie or a token. export async function GET(request: Request) { const denied = opsAuth(request); if (denied) return denied; diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -31,6 +31,15 @@ import { type ReadXTrendingAsk, } from "yt-dlp-transcript-common/controller/readXTrending"; import { fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; +import path from "node:path"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config"; +import { + judgeXTrending, + xTrendingJudgeProblem, + type XTrendingJudgeItem, + type XTrendingJudgeResult, +} from "yt-dlp-transcript-common/lib/xTrending/judgements"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { xPressInFlight } from "../../lib/cookieRefreshGuard"; @@ -86,3 +95,43 @@ export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<Stream ), }); } + +// A library's root on disk, or the refusal's sentence. +async function libraryRoot(slug: string): Promise<{ ok: true; channelRoot: string } | { ok: false; error: string }> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${String(slug)}" is not a valid channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `No such channel: ${slug}` }; + if (!isXTrendingChannel(config)) return { ok: false, error: NOT_AN_X_TRENDING_LIBRARY(slug) }; + return { ok: true, channelRoot: path.join(paths.channelsDir, slug) }; +} + +export type JudgeXTrendingAsk = { + slug: string; + // Who decided: the channel page's buttons say "operator"; `pnpm ops + // judge-trending` says "agent" unless told otherwise. + by: unknown; + set: unknown; +}; + +export type JudgeXTrendingActionResult = + | ({ ok: true; slug: string } & XTrendingJudgeResult) + | { ok: false; error: string }; + +// JUDGE POSTS OF A LIBRARY (lane x-trending-2): keep / drop / later, or +// undecided (the judgement removed), per post or per thread — the channel +// page's buttons and `pnpm ops judge-trending`, one writer +// (lib/xTrending/judgements.ts). An agent's write over the operator's +// judgement is skipped for that id and reported. +export async function judgeXTrendingAction(ask: JudgeXTrendingAsk): Promise<JudgeXTrendingActionResult> { + const lib = await libraryRoot(ask.slug); + if (!lib.ok) return lib; + const problem = xTrendingJudgeProblem(ask); + if (problem) return { ok: false, error: problem }; + const result = await judgeXTrending(lib.channelRoot, { + by: ask.by as "agent" | "operator", + set: ask.set as XTrendingJudgeItem[], + }); + safeRevalidate([`/channels/${ask.slug}`]); + return { ok: true, slug: ask.slug, ...result }; +} diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -151,7 +151,7 @@ export const X_TRENDING_TOOLS = [ description: "The posts of an X TRENDING LIBRARY (or of one of its topics): each post's id, author, " + "date, words, media by kind and count, the reads that showed it, its topic, and — once " + - "it has them — its captured picture's path and its judgement (keep / drop / undecided) — the " + + "it has them — its captured picture's path and its judgement (keep / drop / later; none is undecided) — the " + "newest read's first, in the order the page showed them. For looking through what a " + "trending page held before anything is archived or published. PRIVATE material: never " + "quote it into a published report unless the operator says so. Read only. " + diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -178,6 +178,7 @@ // pnpm ops read-x-trending --json '{"slug":"trending","url":"https://x.com/i/trending/1900000000000000001","topic":"Kettle festival"}' --wait // pnpm ops read-x-trending --json '{"slug":"trending","reparse":"tr-01JA0000000000000000000000"}' --wait // pnpm ops get trending trending --topic kettle-festival --limit 50 +// pnpm ops judge-trending --json '{"slug":"trending","set":[{"id":"1900000000000001001","state":"keep","note":"the opening"},{"thread":"1900000000000001002","state":"drop"}]}' // 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 @@ -704,6 +705,9 @@ const ACTIONS = [ // library, as one job on X's queue ({slug, url, topic?, scrolls?, posts?, // probe?, headed?}), or a saved read parsed again offline ({slug, reparse}). "read-x-trending", + // A library's posts judged: keep / drop / later, or undecided (removed), + // per post or per thread ({slug, set: [{id | thread, state, note?}], by?}). + "judge-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), @@ -1299,8 +1303,10 @@ export function usage() { " judgement?}] (the newest read's first, in page order; --limit 1-500,", " default 100; total is the count before it) and reads (the saved reads'", " ids, newest first). thumbnail is a captured post's first picture", - " (trending/posts-media/<id>/<name>, relative to the channel); judgement", - " is {state: keep | drop | undecided, note?, by, at} once a post has one. Never the", + " (trending/posts-media/<id>/<name>, relative to the channel); thread is", + " the root post id of the thread a post belongs to; judgement is {state:", + " keep | drop | later, note?, by, at, from?} once a post has one (its own,", + " or its thread's: from \"thread\"); no judgement is undecided. Never the", " raw capture, a cookie or a token.", "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,", @@ -1910,6 +1916,20 @@ export function usage() { " in no index build; \"xTrendingMaxScrolls\"?, \"xTrendingMaxPosts\"? set", " its caps).", "", + '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". 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.", + " Answers {written, skipped: [{id | thread, reason}], kept} - kept names", + " the posts whose judgement BECAME keep. 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.", + "", 'x-run fetches several X posts channels IN SEQUENCE as ONE job on X\'s', ' queue: {"channels": [slug, ...]} in that order, each a fetch-posts sync', ' new of at most 200 posts ("limit": N, 1-200, caps it lower), X\'s queue', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1148,5 +1148,14 @@ test("read-x-trending is a POST with a result marker; get trending reads the lib assert.match(parseArgs(["get", "channel", "s", "--topic", "x"]).error, /get channel does not take --topic/); assert.match(usage(), /pnpm ops get trending <slug> \[--topic <topicId>\] \[--limit <n>\]/); assert.match(usage(), /read-x-trending reads ONE X trending page into an X trending library/); - assert.match(usage(), /Actions:.*x-search-lead, read-x-trending/); + assert.match(usage(), /Actions:.*x-search-lead, read-x-trending, judge-trending/); +}); + +test("judge-trending posts its body; its help says an agent never replaces the operator", () => { + const p = parseArgs(["judge-trending", "--json", '{"slug":"lib","set":[{"id":"1900000000000001001","state":"keep"}]}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/judge-trending"); + assert.deepEqual(p.body, { slug: "lib", set: [{ id: "1900000000000001001", state: "keep" }] }); + assert.match(usage(), /judge-trending judges posts of an X trending library/); + assert.match(usage(), /an agent's write over a judgement the operator made is\n\s+skipped/); });