Archilyzer · Source

archilyzer

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

commit cfcadd5041b93d8673af35f4491c736d7086a72a
parent a7b7f91ec8c22170008a0d496c5045310d75a853
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 03:59:29 -0500

x-trending review 1 (M2, S2, thread key): the operator's thread judgement holds; gone needs the page's end in the capture

M2: an agent's post-level write is skipped when the post has no entry of its own and its thread's is the operator's, so nothing the operator dropped by thread becomes keep (or is archived) by an agent. S2: a read that went idle is not a read that reached the page's end; gone is asserted only when no answer failed or was dropped and the parser finds the end in the capture (the last timeline answer brought nothing new). A post's thread key ignores a threadId that repeats its own id, is decided when the post is placed and is kept in its membership record.

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

Diffstat:
Mcommon/controller/readXTrending.test.ts | 38+++++++++++++++++++++++++++++++++++++-
Mcommon/controller/readXTrending.ts | 21++++++++++++++++++---
Mcommon/lib/xTrending/judgements.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/judgements.ts | 22++++++++++++++++------
Mcommon/lib/xTrending/store.test.ts | 28++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 53++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/social/xTrendingParse.test.ts | 27+++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.ts | 31+++++++++++++++++++++++++++++--
8 files changed, 229 insertions(+), 23 deletions(-)

diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -159,9 +159,11 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit const paths = corpus("reread"); const first = fixtureTrendingResponses(); await run(paths, { load: first.load, scrolls: [] }); + // The page's end, as the capture shows it: asked for more, the timeline had none. + const nothingMore = { url: first.scrolls[0][0].url, status: 200, body: fixtureTimelineBody([]) }; const again = await run( paths, - { load: [first.scrolls[0][0]], scrolls: [] }, + { load: [first.scrolls[0][0]], scrolls: [[nothingMore]] }, {}, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }, ); @@ -172,6 +174,10 @@ test("a re-read adds the new posts, keeps the old ones, and appends the read wit // PAGE, at the read's time, never "deleted". assert.equal(again.result.stop, "idle"); assert.deepEqual(again.result.newIds, ["1900000000000001005"]); + // Each post's thread is kept with its place: 1005 answers 1001. + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.equal(members["1900000000000001005"].thread, "1900000000000001001"); + assert.equal(members["1900000000000001004"].thread, "1900000000000001004"); assert.deepEqual([...(again.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); assert.match(again.result.sentence, /2 posts this page showed before are gone from the page at 12:00 UTC\.$/); assert.doesNotMatch(again.result.sentence, /delet/i); @@ -555,3 +561,33 @@ test("a reparse whose read is still running when the job starts parses nothing a assert.equal(done.ok, true); } }); + +// Review 1 S2: "idle" is not the page's end. +test("S2: a read that went idle without the capture showing the page's end marks nothing gone", async () => { + const first = fixtureTrendingResponses(); + const timeline = first.scrolls[0][0]; + const reread = async (name: string, second: FakeTrendingPage) => { + const paths = corpus(name); + await run(paths, { load: first.load, scrolls: [] }); + return run(paths, second, {}, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + }; + // The scrolls simply brought no further answer (a next page that never loaded looks the same). + const silent = await reread("s2-silent", { load: [timeline], scrolls: [[], []] }); + assert.equal(silent.result.stop, "idle"); + assert.equal(silent.result.outcome, "read"); + assert.equal(silent.result.gone, undefined); + assert.doesNotMatch(silent.result.sentence, /gone from the page/); + // The next page answered 500: the read still ends idle, and asserts nothing. + const failed = await reread("s2-failed", { load: [timeline], scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], []] }); + assert.equal(failed.result.stop, "idle"); + assert.equal(failed.result.gone, undefined); + // ...even when an empty page follows the failure. + const after500 = await reread("s2-failed-then-empty", { + load: [timeline], + scrolls: [[{ url: timeline.url, status: 500, text: "upstream error" }], [{ url: timeline.url, status: 200, body: fixtureTimelineBody([]) }]], + }); + assert.equal(after500.result.gone, undefined); + // Asked for more and answered "none", cleanly: the page's end. + const ended = await reread("s2-end", { load: [timeline], scrolls: [[{ url: timeline.url, status: 200, body: fixtureTimelineBody([]) }], []] }); + assert.deepEqual([...(ended.result.gone ?? [])].sort(), ["1900000000000001001", "1900000000000001002"]); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -55,7 +55,9 @@ import { ensureXTrendingReadsDir, isXTrendingReadId, readXTrendingPostIds, + readXTrendingPosts, readXTrendingReadRecord, + xTrendingThreadKey, recordXTrendingRead, topicTitleProblem, TRENDING_DIRNAME, @@ -334,8 +336,16 @@ async function ingestCapture(o: { const had = await readXTrendingPostIds(o.channelRoot); const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id)); const written = await writeXTrendingPosts(o.channelRoot, parsed.posts); + // A THREAD'S KEY IS DECIDED ONCE, when a post is first placed, and kept in + // its membership record (store.ts): it does not move as ancestors arrive. + const byId = new Map((await readXTrendingPosts(o.channelRoot)).map((p) => [p.id, p])); + const threads: Record<string, string> = {}; + for (const p of parsed.posts) threads[p.id] = xTrendingThreadKey(byId.get(p.id) ?? p, byId); const recorded = await recordXTrendingRead(o.channelRoot, { - ...(o.complete ? { complete: true } : {}), + threads, + // Only when the scrolling stopped at the page's end AND the capture shows + // it (review 1 S2: "idle" alone also follows a next page that failed). + ...(o.complete && parsed.pageEnd ? { complete: true } : {}), readId: o.readId, at: o.at, ref: o.ref, @@ -466,8 +476,13 @@ export async function runXTrendingRead(o: { ref: plan.ref, ...(plan.topic ? { topic: plan.topic } : {}), write: !plan.probe && !walled, - // "idle": the scrolling stopped because the page had no more to show. - complete: page.stop === "idle", + // "idle": two scrolls brought no new post — the page's end, OR a next + // page that did not load. So also: no answer that failed, none that was + // not kept; and the capture itself must show the end (ingestCapture). + complete: + page.stop === "idle" && + page.saved === page.responses && + Object.keys(page.statuses).every((status) => /^2\d\d$/.test(status)), }); } catch (err) { ingestError = ((err as Error)?.message ?? String(err)).split("\n")[0]; diff --git a/common/lib/xTrending/judgements.test.ts b/common/lib/xTrending/judgements.test.ts @@ -147,3 +147,35 @@ test("the ask's shape is refused with a sentence", () => { 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/); }); + +// Review 1 M2: no way round the operator through the post-over-thread precedence. +test("M2: an agent cannot override the operator's thread judgement with a post-level one, nor the operator's post with a thread-level one", async () => { + const dir = await library("precedence"); + // The operator drops the thread; an agent then tries to keep one post of it. + await judgeXTrending(dir, { by: "operator", set: [{ thread: "501", state: "drop" }] }); + const sneak = await judgeXTrending(dir, { by: "agent", set: [{ id: "502", state: "keep" }, { id: "504", state: "keep" }] }); + assert.deepEqual(sneak.skipped, [{ id: "502", reason: JUDGED_BY_OPERATOR }]); + assert.deepEqual(sneak.written, [{ id: "504", state: "keep" }]); + // Nothing of the dropped thread became keep: nothing of it would be archived. + assert.deepEqual(sneak.kept, ["504"]); + assert.equal((await readXTrendingJudgementsFile(dir)).posts["502"], undefined); + let rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); + assert.deepEqual([rows["502"].judgement?.state, rows["502"].judgement?.by], ["drop", "operator"]); + // Nor may the agent clear it at post level. + assert.deepEqual((await judgeXTrending(dir, { by: "agent", set: [{ id: "503", state: "undecided" }] })).skipped, [{ id: "503", reason: JUDGED_BY_OPERATOR }]); + // The operator may, of course. + assert.deepEqual((await judgeXTrending(dir, { by: "operator", set: [{ id: "502", state: "keep" }] })).kept, ["502"]); + + // The other direction: the operator drops ONE post; an agent keeps its thread. + const other = await library("precedence-2"); + await judgeXTrending(other, { by: "operator", set: [{ id: "502", state: "drop" }] }); + const thread = await judgeXTrending(other, { by: "agent", set: [{ thread: "501", state: "keep" }] }); + assert.deepEqual(thread.written, [{ thread: "501", state: "keep" }]); + // 502 keeps the operator's drop and is not among the kept. + assert.deepEqual(thread.kept, ["501", "503"]); + rows = Object.fromEntries((await listXTrending(other)).posts.map((p) => [p.id, p])); + assert.deepEqual([rows["502"].judgement?.state, rows["502"].judgement?.by], ["drop", "operator"]); + // And an agent's thread-level write over the operator's thread entry is skipped. + await judgeXTrending(other, { by: "operator", set: [{ thread: "501", state: "later" }] }); + assert.deepEqual((await judgeXTrending(other, { by: "agent", set: [{ thread: "501", state: "keep" }] })).skipped, [{ thread: "501", reason: JUDGED_BY_OPERATOR }]); +}); diff --git a/common/lib/xTrending/judgements.ts b/common/lib/xTrending/judgements.ts @@ -6,8 +6,12 @@ // 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. +// operator made is SKIPPED for that id and reported; nothing forces it — and +// "over" means the judgement in force: a post the operator judged through its +// THREAD is the operator's too, so an agent's post-level write for it is +// skipped. (An agent's thread-level write never reaches a post the operator +// judged itself: a post's own entry comes first.) The operator overturns +// anything. `by` is the caller's word: an agent is trusted to say "agent". // // 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. @@ -27,7 +31,7 @@ import { readXTrendingPosts, X_TRENDING_JUDGEMENT_STATES, xTrendingJudgementsPath, - xTrendingThreadKey, + xTrendingThreadOf, type XTrendingJudgement, type XTrendingJudgementState, } from "./store"; @@ -115,7 +119,7 @@ export async function judgeXTrending( const threadOf = new Map<string, string>(); const members = new Map<string, string[]>(); for (const p of byId.values()) { - const key = xTrendingThreadKey(p, byId); + const key = xTrendingThreadOf(p, membership, byId); threadOf.set(p.id, key); members.set(key, [...(members.get(key) ?? []), p.id]); } @@ -135,7 +139,13 @@ export async function judgeXTrending( } const map = isThread ? file.threads : file.posts; const have: XTrendingJudgement | undefined = map[key]; - if (ask.by === "agent" && have?.by === "operator") { + // The entry that decides this key's judgement NOW: its own, else — for + // a post — its thread's. An agent replaces neither when the operator + // made it (review 1 M2): a post in a thread the operator judged has the + // operator's judgement, and an agent's post-level entry would take + // precedence over it. + const deciding: XTrendingJudgement | undefined = have ?? (isThread ? undefined : file.threads[threadOf.get(key) ?? ""]); + if (ask.by === "agent" && deciding?.by === "operator") { skipped.push({ ...name, reason: JUDGED_BY_OPERATOR }); continue; } @@ -165,7 +175,7 @@ export async function readXTrendingKeptIds(channelRoot: string): Promise<Set<str 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; + const state = file.posts[p.id]?.state ?? file.threads[xTrendingThreadOf(p, membership, byId)]?.state; if (state === "keep") kept.add(p.id); } return kept; diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import path from "node:path"; import { + xTrendingThreadKey, listXTrending, readXTrendingMembership, readXTrendingTopics, @@ -341,3 +342,30 @@ test("a captured post's row says what its capture holds and what it is owed", as assert.deepEqual(rows["811"].capture, { at: "2026-11-17T10:05:00.000Z", state: "captured", shot: false, files: 1, mediaState: "error", mediaOwed: "kept" }); assert.equal(rows["812"].capture, undefined); }); + +// Review 1: a thread's key is decided once. +test("a thread's key ignores a threadId that only repeats the post's id, and does not move as ancestors arrive", async () => { + // Raw X posts whose answer carried no conversation id: the normalizer sets threadId = id. + const reply = (id: string, to?: string): Post => ({ ...post(id, "a", `post ${id}`), threadId: id, ...(to ? { isReply: true, replyTo: { platform: "twitter" as const, id: to } } : {}) }); + const byId = (...posts: Post[]) => new Map(posts.map((p) => [p.id, p])); + const c = reply("903", "902"); + // Its own id as threadId says nothing: the chain it answers decides. + assert.equal(xTrendingThreadKey(c, byId(c)), "902"); + assert.equal(xTrendingThreadKey(reply("901"), byId()), "901"); + // A real conversation id (another post's) is the key. + assert.equal(xTrendingThreadKey({ ...c, threadId: "900" }, byId(c)), "900"); + + const dir = root("thread-stable"); + await writeXTrendingPosts(dir, [c]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["903"], added: 1, threads: { "903": xTrendingThreadKey(c, byId(c)) } }); + assert.equal((await listXTrending(dir)).posts[0].thread, "902"); + // Its parent arrives later, itself a reply to 901: computed afresh the key would now be 901. + const b = reply("902", "901"); + await writeXTrendingPosts(dir, [b]); + assert.equal(xTrendingThreadKey(c, byId(c, b)), "901"); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "T", postIds: ["902", "903"], added: 1, threads: { "902": "901", "903": "901" } }); + const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p.thread])); + // 903 keeps the key it was placed with; 902 gets its own, decided now. + assert.deepEqual(rows, { "902": "901", "903": "902" }); + assert.equal((await readXTrendingMembership(dir))["903"].thread, "902"); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -48,8 +48,7 @@ import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; import type { Post } from "../posts"; import type { XTrendingRef } from "./config"; -// (./watch imports this module for its paths; each uses the other only inside -// functions, so the cycle is one of names, not of load order.) +// (./watch imports only TYPES of this module: no cycle.) import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch"; export const TRENDING_DIRNAME = "trending"; @@ -183,13 +182,22 @@ export async function readXTrendingJudgements(channelRoot: string): Promise<Reco 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. +// A THREAD'S KEY is its root post's id. The source's own `threadId` when it +// names ANOTHER post (X's conversation id) — a normalized X post always has +// one, and when the answer gave no conversation id it is the post's own id, +// which says nothing (review 1). Then 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. +// +// DECIDED ONCE PER POST. The walk's answer moves as ancestors arrive, so a +// post's key is computed when the post is first placed in a topic and kept in +// its membership record (`thread`); everything that asks a post's thread asks +// xTrendingThreadOf, which reads that record. export function xTrendingThreadKey(post: Post, byId: ReadonlyMap<string, Post>): string { - if (post.threadId && /^\d+$/.test(post.threadId)) return post.threadId; + const named = (p: Post) => (p.threadId && /^\d+$/.test(p.threadId) && p.threadId !== p.id ? p.threadId : undefined); + const own = named(post); + if (own) return own; let at = post; const walked = new Set<string>([post.id]); for (let hops = 0; hops < 64; hops++) { @@ -197,13 +205,24 @@ export function xTrendingThreadKey(post: Post, byId: ReadonlyMap<string, Post>): 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; + const theirs = named(next); + if (theirs) return theirs; walked.add(parent); at = next; } return at.id; } +// A post's thread: the key its membership record holds, else (a member placed +// before keys were kept) the walk's answer now. +export function xTrendingThreadOf( + post: Post, + membership: Readonly<Record<string, { thread?: string } | undefined>>, + byId: ReadonlyMap<string, Post>, +): string { + return membership[post.id]?.thread ?? xTrendingThreadKey(post, byId); +} + const IMAGE_FILE = /\.(?:jpe?g|png|webp|gif)$/i; // WHERE A LIBRARY'S CAPTURED MEDIA LIVES (review 2 N9): under trending/, as @@ -301,6 +320,8 @@ export type XTrendingGone = { at: string; read: string; trendId: string }; export type XTrendingMember = { topic: string; + // Its thread's key, decided when it was placed (xTrendingThreadKey). + thread?: string; seen: XTrendingSeen[]; media?: XTrendingMedia; gone?: XTrendingGone; @@ -369,6 +390,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { ); out[id] = { topic: m.topic, + ...(typeof m.thread === "string" && /^\d+$/.test(m.thread) ? { thread: m.thread } : {}), seen, ...(media ? { media } : {}), ...(gone ? { gone } : {}), @@ -424,6 +446,9 @@ export type RecordReadInput = { // How many of them the library did not hold before this read. added: number; media?: Readonly<Record<string, XTrendingMedia>>; + // Post id → its thread's key, for posts this read places (a member that + // has a key keeps it). + threads?: Readonly<Record<string, string>>; // The read reached the page's end (it stopped because the page had no more // to show): only then is a post it did not show marked gone from the page. complete?: boolean; @@ -497,6 +522,7 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead kept++; if (!have.seen.some((s) => s.read === input.readId)) have.seen.push(seen); if (!have.media && input.media?.[id]) have.media = input.media[id]; + if (!have.thread && input.threads?.[id]) have.thread = input.threads[id]; // Shown again, by a read later than the one that missed it. if (have.gone && input.at > have.gone.at) { (have.wasGone ??= []).push({ from: have.gone.at, to: input.at }); @@ -505,7 +531,12 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead } } else { placed++; - posts[id] = { topic: topic.id, seen: [seen], ...(input.media?.[id] ? { media: input.media[id] } : {}) }; + posts[id] = { + topic: topic.id, + ...(input.threads?.[id] ? { thread: input.threads[id] } : {}), + seen: [seen], + ...(input.media?.[id] ? { media: input.media[id] } : {}), + }; } }); if (input.complete) { @@ -695,7 +726,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); + const thread = xTrendingThreadOf(post, membership, archived); rows.push({ id, author: post.author, diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -169,3 +169,30 @@ test("media sources: a picture at its original size, a video's highest-bitrate m assert.deepEqual([...mediaSourcesInCapture([line("ExampleTrendTimeline", 200)]).keys()], ["1900000000000002003"]); assert.equal(mediaSourcesInCapture([line("HomeTimeline", 200), line("ExampleTrendTimeline", 500)]).size, 0); }); + +// Review 1 S2. +test("S2: a capture shows the page's end only when its last timeline answer brought nothing new and no answer failed", async () => { + const { parseTrendingCapture } = await import("./xTrendingParse"); + const { fixtureTimelineBody } = await import("./__fixtures__/xTrendingCapture"); + const t = (id: string) => ({ id, handle: "a", text: `post ${id}` }); + let n = 0; + type Line = import("./xTrendingParse").TrendingCaptureLine; + const line = (op: string, status: number, body?: unknown): Line => ({ n: ++n, at: "x", op, status, url: "u", bytes: 1, ...(body === undefined ? {} : { body }) }); + const page = (ids: string[]) => line("ExampleTrendTimeline", 200, fixtureTimelineBody(ids.map(t))); + const end = (lines: Line[]) => parseTrendingCapture(lines, "lib").pageEnd; + // Posts, then an answer with none: the end. + assert.equal(end([page(["1", "2"]), page([])]), true); + // The last answer repeated posts already seen and brought no new one: the end too. + assert.equal(end([page(["1", "2"]), page(["2"])]), true); + // The last answer still brought a new post: nothing says there was no more. + assert.equal(end([page(["1", "2"]), page(["3"])]), false); + assert.equal(end([page(["1", "2"])]), false); + // An answer that failed, or whose body was not kept: the capture cannot tell. + assert.equal(end([page(["1"]), line("ExampleTrendTimeline", 500), page([])]), false); + assert.equal(end([page(["1"]), { ...page([]), body: undefined, skipped: "too-large" as const }]), false); + assert.equal(end([page(["1"]), page([]), line("ExampleTrendPage", 429)]), false); + // Another surface's failure is not the page's. + assert.equal(end([page(["1"]), page([]), line("HomeTimeline", 500)]), true); + // No post at all: no page to have an end. + assert.equal(end([line("ExampleTrendPage", 200, { data: {} })]), false); +}); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -249,6 +249,15 @@ export type ParsedTrendingCapture = { operations: TrendingOperation[]; responses: number; bytes: number; + // THE CAPTURE SHOWS THE PAGE'S END (review 1 S2): every answer of the page + // was a 2xx whose body was kept, and the LAST answer of an operation that + // lists the page's posts brought no post the capture had not already seen — + // the page was asked for more and had none. False whenever the capture + // cannot tell: an answer that failed or was not kept (the next page may + // simply not have loaded), or a last answer that still brought new posts + // (nothing shows there was no more). Only a capture that shows the end may + // be read as "what this page no longer shows". + pageEnd: boolean; }; // The capture, parsed. `channelSlug` is the library's (a Post names its channel). @@ -260,6 +269,11 @@ export function parseTrendingCapture( const media: Record<string, TrendingMediaSummary> = {}; const ops = new Map<string, TrendingOperation>(); let bytes = 0; + // Per answer of the page's own operations, in order: its operation, and how + // many posts it brought that no earlier answer had. + const answers: Array<{ op: string; fresh: number }> = []; + const seenIds = new Set<string>(); + let failed = false; for (const line of lines) { const op = ops.get(line.op) ?? { op: line.op, responses: 0, bytes: 0, statuses: [], tweets: 0 }; ops.set(line.op, op); @@ -267,17 +281,29 @@ export function parseTrendingCapture( op.bytes += line.bytes; bytes += line.bytes; if (!op.statuses.includes(line.status)) op.statuses.push(line.status); - if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue; - if (line.status < 200 || line.status >= 300) continue; + if (X_TRENDING_IGNORED_OPS.includes(line.op)) continue; + if (line.body === undefined || line.status < 200 || line.status >= 300) { + failed = true; + continue; + } const found = collectTimelineTweets(line.body); op.tweets += found.length; + let fresh = 0; for (const raw of found) { raws.push(raw); const id = xIdOf(raw); + if (id && !seenIds.has(id)) { + seenIds.add(id); + fresh++; + } const summary = mediaSummaryOf(raw); if (id && summary && !media[id]) media[id] = summary; } + answers.push({ op: line.op, fresh }); } + // The last answer of an operation that ever listed posts. + const last = answers.filter((a) => (ops.get(a.op)?.tweets ?? 0) > 0).at(-1); + const pageEnd = !failed && last !== undefined && last.fresh === 0; const posts = normalizeXTweets(raws, channelSlug); const kept: Record<string, TrendingMediaSummary> = {}; for (const p of posts) if (media[p.id]) kept[p.id] = media[p.id]; @@ -287,6 +313,7 @@ export function parseTrendingCapture( operations: [...ops.values()].sort((a, b) => a.op.localeCompare(b.op)), responses: lines.length, bytes, + pageEnd, }; }