Archilyzer · Source

archilyzer

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

commit 4d1188d1d88e2f7ac4af2b2296720e9a93573a33
parent 418f9361809cd2e532c40f91974fdfccc4516fb2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 01:37:31 -0500

x-trending: a keep archives the post through the capture job

judge-trending starts ONE capture-posts job for the posts that became keep (a screenshot, the context, a reply's thread shot, the media with no per-file cap and the logged-in download as the fallback); "archive": false marks only, and a refused capture leaves the judgements written and says why. capture-posts takes keptMedia, refused for an id that is not kept, and carries it through a replay. Under the e2e test server a library's capture uses the fake profile browser and a played-back CDN, and never the logged-in download.

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

Diffstat:
MCOMMANDS.md | 4++--
Mcommon/lib/xTrending/judgements.ts | 16++++++++++++++++
Mcommon/social/fakeXProfileBrowser.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 18++++++++++++++++--
Meditor/app/api/ops/judge-trending/route.test.ts | 41+++++++++++++++++++++++++++++++++++++++--
Meditor/app/api/ops/judge-trending/route.ts | 27++++++++++++++++++++-------
Meditor/app/channels/[slug]/socialActions.ts | 36+++++++++++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/xTrendingActions.ts | 29+++++++++++++++++++++++++++--
Meditor/app/jobs/jobReplayRegistry.ts | 1+
Mscripts/archilyzer-ops.mjs | 29++++++++++++++++++++++++-----
10 files changed, 211 insertions(+), 21 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -169,7 +169,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | | `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | -| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. | | +| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. An X trending library is captured by this same job, under channels/&lt;slug&gt;/trending/posts-media/&lt;id&gt;/. Its media comes from X's media CDN by the addresses in the library's saved captures: no login, one file after another 1-2 s apart, under X's cooldown, each file kept once (trending/media-store/, a hardlink per post). A file over the library's maxVideoMb (100 MB) and whatever is past the job's budget (40 files / 200 MB) is owed: asked for again by the next capture of that post. A 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or 404 marks the file; nothing retries. "keptMedia": true is for posts marked keep (refused for any other id): no per-file cap, and a post the CDN cannot serve whole is downloaded the logged-in way. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | | `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | | @@ -219,7 +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"}]}'` | +| `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, 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"}]}'` | | `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | | `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -&gt; {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` | | `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -&gt; {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` | diff --git a/common/lib/xTrending/judgements.ts b/common/lib/xTrending/judgements.ts @@ -154,3 +154,19 @@ export async function judgeXTrending( return { written, skipped, kept }; }); } + +// The posts whose judgement is keep — their own, or their thread's. +export async function readXTrendingKeptIds(channelRoot: string): Promise<Set<string>> { + const [membership, posts, file] = await Promise.all([ + readXTrendingMembership(channelRoot), + readXTrendingPosts(channelRoot), + readXTrendingJudgementsFile(channelRoot), + ]); + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + const kept = new Set<string>(); + for (const p of byId.values()) { + const state = file.posts[p.id]?.state ?? file.threads[xTrendingThreadKey(p, byId)]?.state; + if (state === "keep") kept.add(p.id); + } + return kept; +} diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -29,6 +29,7 @@ import { readFileSync, realpathSync } from "node:fs"; import path from "node:path"; import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; +import type { MediaFetch } from "./xTrendingMedia"; export type FakeTrendingResponse = { url: string; status: number; body?: unknown; text?: string }; @@ -47,6 +48,8 @@ type FixtureFile = { fail?: string; cookies?: Array<{ name: string; value: string; domain: string; path?: string; expires?: number }>; trending?: FakeTrendingPage; + // What X's media CDN answers, by address ({status?, text?}; absent: 404). + media?: Record<string, { status?: number; text?: string }>; }; // The smallest PNG there is (1×1, transparent): the fake page's "screenshot". @@ -127,6 +130,34 @@ function readFixture(file: string): FixtureFile { return JSON.parse(readFileSync(file, "utf8")) as FixtureFile; } +// X'S MEDIA CDN, PLAYED BACK (lane x-trending-2): the stand-in for the fetch a +// library's capture asks its media of (xTrendingMedia.ts MediaFetch). Under +// the e2e test server it is ALWAYS this, fixture or no fixture, so no test +// server ever opens a socket to the CDN: an address the fixture's `media` map +// does not name is answered 404. Null outside the test server. +export function fakeXMediaFetch( + transcriptsDir: string, + env: Readonly<Record<string, string | undefined>> = process.env, +): MediaFetch | null { + if (env.E2E_TEST_ROUTES !== "1") return null; + return async (url) => { + const file = fakeXProfileCookiesFile(transcriptsDir, env); + const answer = file ? readFixture(file).media?.[url] : undefined; + const status = answer?.status ?? (answer ? 200 : 404); + const bytes = Buffer.from(answer?.text ?? ""); + return { + status, + headers: { get: (name: string) => (name.toLowerCase() === "content-length" ? String(bytes.length) : null) }, + body: + status >= 200 && status < 300 + ? (async function* () { + yield new Uint8Array(bytes); + })() + : null, + }; + }; +} + // The fake, or null when the gate above says no. export function fakeXProfileChromium( transcriptsDir: string, diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,7 +10,7 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, keptMedia?, queueKey? } -> { ok: true, jobId } // // Capture specific archived posts of a social channel: a screenshot of each // (`shots`, default true) and its attached media (`media`, default true), into @@ -48,10 +48,23 @@ export const dynamic = "force-dynamic"; // is not a social one, a fetcher that cannot capture, an id not in the // channel's posts archive, `avatarsOnly` or `contextOnly` on a channel that // is not X, both of them at once. +// +// AN X TRENDING LIBRARY (lane x-trending-2) is captured by this same job, its +// captures under `channels/<slug>/trending/posts-media/<id>/`. Its MEDIA comes +// from X's media CDN, by the addresses in the library's saved captures — no +// login, one file after another 1 to 2 s apart, under X's cooldown; each file +// is kept once (`trending/media-store/`, a hardlink per post). A file over the +// library's `maxVideoMb` (100 MB) and whatever is past the job's budget (40 +// files / 200 MB) is OWED: asked for again by the next capture of that post. A +// 429 from the CDN stops the job and leaves X alone for 15 minutes; a 403 or a +// 404 marks the file; nothing retries. `keptMedia: true` is for posts marked +// keep (refused for any other id): no per-file cap, and a post the CDN cannot +// serve whole is downloaded the logged-in way. `judge-trending` runs it for +// the posts it marks keep. export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "keptMedia", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -70,6 +83,7 @@ export async function POST(request: Request) { avatarsOnly: optBool(body, "avatarsOnly"), context: optBool(body, "context"), contextOnly: optBool(body, "contextOnly"), + keptMedia: optBool(body, "keptMedia"), }, ), ); diff --git a/editor/app/api/ops/judge-trending/route.test.ts b/editor/app/api/ops/judge-trending/route.test.ts @@ -90,14 +90,15 @@ test("judge-trending refuses with a sentence", async () => { }); 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" }] }); + const first = await call({ slug: "trending", archive: false, set: [{ id: A, state: "keep", note: "the opening" }, { id: "42", state: "keep" }] }); + assert.equal(first.json.archive, undefined); 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" }] }); + const again = await call({ slug: "trending", archive: false, 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/); @@ -108,3 +109,39 @@ test("an agent's judgement is written; the operator's is not replaced by an agen 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"]]); }); + +test("a keep archives through capture-posts; a refused capture leaves the judgement written and says why", async () => { + // This corpus has no connected X profile and no cookie jar: the capture is + // refused before a job exists (nothing is asked of X), the keep stands. + const r = await call({ slug: "trending", by: "operator", set: [{ id: B, state: "keep" }] }); + assert.equal(r.status, 200); + assert.deepEqual(r.json.kept, [B]); + const archive = r.json.archive as { error?: string; jobId?: string; ids: string[] }; + assert.deepEqual(archive.ids, [B]); + assert.equal(archive.jobId, undefined); + assert.ok(archive.error && archive.error.length > 20, String(archive.error)); + const file = JSON.parse(await readFile(path.join(lib, "trending", "judgements.json"), "utf8")); + assert.equal(file.posts[B].state, "keep"); +}); + +test("capture-posts keptMedia is for a library's kept posts only", async () => { + const capture = (await import("../capture-posts/route")).POST; + const ask = async (body: Record<string, unknown>) => { + const res = await capture( + new Request("http://localhost/api/ops/capture-posts", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; + }; + // A is dropped by the operator above: not kept. + const notKept = await ask({ slug: "trending", ids: [A], keptMedia: true }); + assert.equal(notKept.status, 400); + assert.match(String(notKept.json.error), new RegExp(`not kept: ${A}`)); + const notLibrary = await ask({ slug: "account-x", ids: ["1"], keptMedia: true }); + assert.equal(notLibrary.status, 400); + // An id that is not the library's is refused as stray before anything else. + assert.match(String((await ask({ slug: "trending", ids: ["42"], keptMedia: true })).json.error), /not in trending's posts archive/); +}); diff --git a/editor/app/api/ops/judge-trending/route.ts b/editor/app/api/ops/judge-trending/route.ts @@ -1,12 +1,13 @@ import { NextResponse } from "next/server"; import { judgeXTrendingAction } from "../../../channels/[slug]/xTrendingActions"; -import { OpsInputError, ops, opsFail, reqSlug } from "../_lib"; +import { OpsInputError, ops, opsFail, optBool, reqSlug } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, set: [{id | thread, state, note?}, …], by? } +// POST { slug, set: [{id | thread, state, note?}, …], by?, archive? } // -> { ok: true, slug, written: [{id | thread, state}], -// skipped: [{id | thread, reason}], kept: [<post id>, …] } +// skipped: [{id | thread, reason}], kept: [<post id>, …], +// archive?: {jobId, ids} | {error, ids} } // // JUDGE POSTS OF AN X TRENDING LIBRARY (lane x-trending-2), written to // `channels/<slug>/trending/judgements.json` by its one writer: @@ -23,18 +24,30 @@ export const dynamic = "force-dynamic"; // 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. +// or their thread's). A KEEP ARCHIVES THEM: one `capture-posts` job on X's +// queue (a screenshot, the context, a reply's thread shot, the media — +// `archive.jobId`), unless `archive: false`. 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 nothing was started; `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. // // 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) => { + return ops(request, ["slug", "set", "by", "archive"], async (body) => { + const archive = optBool(body, "archive"); 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 }); + const result = await judgeXTrendingAction({ + slug: reqSlug(body, "slug"), + by, + set: body.set, + ...(archive !== undefined ? { archive } : {}), + }); if (!result.ok) return opsFail(result.error); return NextResponse.json(result); }); diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -24,6 +24,8 @@ import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config"; import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "yt-dlp-transcript-common/lib/xTrending/config"; import { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements"; +import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser"; import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch"; import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; @@ -357,9 +359,13 @@ export async function capturePostsAction( avatarsOnly?: boolean; context?: boolean; contextOnly?: boolean; + // An X trending library: these posts are marked KEEP, so their media has + // no per-file cap and a post the CDN cannot serve whole is downloaded the + // logged-in way. Refused for an id that is not kept. + keptMedia?: boolean; } = {}, ): Promise<StreamActionResult> { - const { thread, avatars, avatarsOnly, context, contextOnly } = more; + const { thread, avatars, avatarsOnly, context, contextOnly, keptMedia } = more; const redact = parseThreadRedact(more.threadRedact); if (!redact.ok) return { ok: false, error: redact.error }; const threadRedact = redact.value; @@ -399,6 +405,14 @@ export async function capturePostsAction( : await readSeenPostIds(path.join(paths.channelsDir, slug)), ); if (stray) return { ok: false, error: strayIdsRefusal(slug, stray) }; + if (keptMedia) { + if (!library) return { ok: false, error: `"keptMedia" is for an X trending library's kept posts; ${slug} is not a library.` }; + const kept = await readXTrendingKeptIds(path.join(paths.channelsDir, slug)); + const not = wanted.filter((id) => !kept.has(id)); + if (not.length) { + return { ok: false, error: `"keptMedia" is for posts marked keep; not kept: ${not.join(", ")} (judge-trending marks them).` }; + } + } const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey); return runManagedFunction({ @@ -417,6 +431,7 @@ export async function capturePostsAction( ...(avatarsOnly ? { avatarsOnly } : {}), ...(context !== undefined ? { context } : {}), ...(contextOnly ? { contextOnly } : {}), + ...(keptMedia ? { keptMedia } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -430,7 +445,26 @@ export async function capturePostsAction( const cooling = platform === "twitter" ? await platformCooldownRemainingMs("twitter", paths).catch(() => 0) : 0; const held = xCaptureStartRefusal({ platform, shots, avatarsOnly, contextOnly }, cooling); if (held) throw new Error(held); + // UNDER THE E2E TEST SERVER a library's capture never reaches X or its + // CDN: the fake profile browser, the played-back CDN, and no logged-in + // download (social/fakeXProfileBrowser.ts). + const testServer = process.env.E2E_TEST_ROUTES === "1"; + const fakeChromium = library ? fakeXProfileChromium(paths.transcriptsDir) : null; + const fakeFetch = library ? fakeXMediaFetch(paths.transcriptsDir) : null; + if (library && testServer && !fakeChromium && shots !== false) { + throw new Error("The test server has no fake X profile browser for this capture: nothing was opened."); + } const result = await capturePosts({ + ...(fakeChromium ? { chromium: fakeChromium } : {}), + ...(library + ? { + libraryMedia: { + fallback: keptMedia && !testServer ? ("login" as const) : ("none" as const), + ...(keptMedia ? { maxVideoBytes: null } : {}), + ...(fakeFetch ? { deps: { fetch: fakeFetch, pauseMs: () => 20 } } : {}), + }, + } + : {}), paths, slug, settings: getSettings(), diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts @@ -41,6 +41,7 @@ import { type XTrendingJudgeResult, } from "yt-dlp-transcript-common/lib/xTrending/judgements"; import { safeRevalidate } from "../../lib/safeRevalidate"; +import { capturePostsAction } from "./socialActions"; import { xPressInFlight } from "../../lib/cookieRefreshGuard"; export async function readXTrendingAction(ask: ReadXTrendingAsk): Promise<StreamActionResult> { @@ -112,10 +113,16 @@ export type JudgeXTrendingAsk = { // judge-trending` says "agent" unless told otherwise. by: unknown; set: unknown; + // false: mark only; the posts that became keep are not archived now. + archive?: boolean; }; +// What became of archiving the posts that became keep: the capture job, or +// why none was started (the judgements are written all the same). +export type JudgeArchive = { jobId: string; ids: string[] } | { error: string; ids: string[] }; + export type JudgeXTrendingActionResult = - | ({ ok: true; slug: string } & XTrendingJudgeResult) + | ({ ok: true; slug: string; archive?: JudgeArchive } & XTrendingJudgeResult) | { ok: false; error: string }; // JUDGE POSTS OF A LIBRARY (lane x-trending-2): keep / drop / later, or @@ -133,5 +140,23 @@ export async function judgeXTrendingAction(ask: JudgeXTrendingAsk): Promise<Judg set: ask.set as XTrendingJudgeItem[], }); safeRevalidate([`/channels/${ask.slug}`]); - return { ok: true, slug: ask.slug, ...result }; + // A KEEP ARCHIVES: the posts that became keep go into ONE capture-posts job + // on X's queue — a screenshot, the context, a reply's thread shot, and the + // media (from the CDN, no cap, the logged-in download as the fallback). A + // refusal (a stale jar, the X alert, X cooling down) leaves the judgements + // written and says why nothing was started. + let archive: JudgeArchive | undefined; + if (result.kept.length > 0 && ask.archive !== false) { + const started = await capturePostsAction(ask.slug, result.kept, undefined, true, true, false, true, { + thread: true, + keptMedia: true, + }); + if (started.ok) { + void started.stream.cancel(); + archive = { jobId: started.jobId, ids: result.kept }; + } else { + archive = { error: started.error, ids: result.kept }; + } + } + return { ok: true, slug: ask.slug, ...result, ...(archive ? { archive } : {}) }; } diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -484,6 +484,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { avatarsOnly: bool(p.avatarsOnly), context: bool(p.context), contextOnly: bool(p.contextOnly), + keptMedia: bool(p.keptMedia), }, ); }, diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -706,7 +706,8 @@ const ACTIONS = [ // 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?}). + // per post or per thread ({slug, set: [{id | thread, state, note?}], by?, + // archive?}); a keep archives the post through capture-posts. "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 @@ -1925,10 +1926,16 @@ export function usage() { ' "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.", + " 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.", "", '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', @@ -1988,6 +1995,18 @@ export function usage() { ' no media, article, thread shot or availability; a post whose context is', ' already read is skipped unless "force". Not with "avatarsOnly".', ' Paced like a post fetch, on its queue.', + " An X trending library is captured by this same job, under", + " channels/<slug>/trending/posts-media/<id>/. Its media comes from X's", + " media CDN by the addresses in the library's saved captures: no login,", + " one file after another 1-2 s apart, under X's cooldown, each file kept", + " once (trending/media-store/, a hardlink per post). A file over the", + " library's maxVideoMb (100 MB) and whatever is past the job's budget (40", + " files / 200 MB) is owed: asked for again by the next capture of that", + " post. A 429 from the CDN stops the job and leaves X alone for 15", + " minutes; a 403 or 404 marks the file; nothing retries. \"keptMedia\":", + " true is for posts marked keep (refused for any other id): no per-file", + " cap, and a post the CDN cannot serve whole is downloaded the logged-in", + " way.", "", 'persist-videos saves specific videos, across channels, to the saved-video', ' store: {"items": [{"slug", "id"}, ...]}. "format": "original" |',