import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { xTrendingThreadKey, listXTrending, summarizeXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, writeXTrendingPosts, topicIdFromTitle, topicTitleProblem, trendingReadDir, } from "./store"; import type { Post } from "../posts"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-store-")); after(() => rmSync(TMP, { recursive: true, force: true })); const READ_A = "tr-01JA0000000000000000000000"; const READ_B = "tr-01JB0000000000000000000000"; const READ_C = "tr-01JC0000000000000000000000"; const REF = { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }; const REF_2 = { trendId: "1900000000000000002", url: "https://x.com/i/trending/1900000000000000002" }; function post(id: string, author: string, text: string): Post { return { id, slug: `lib/${id}`, channelSlug: "lib", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], }; } function root(name: string): string { const dir = path.join(TMP, name); mkdirSync(dir, { recursive: true }); return dir; } test("a read id is checked where it becomes a path", () => { assert.equal(trendingReadDir("/c/lib", READ_A), `/c/lib/trending/reads/${READ_A}`); for (const bad of ["../x", "tr-short", "xr-01JA0000000000000000000000", ""]) { assert.throws(() => trendingReadDir("/c/lib", bad), /not a trending read id/); } }); test("a topic id comes from its title; a title is refused when empty or too long", () => { assert.equal(topicIdFromTitle(" Kettle Festival 2026! "), "kettle-festival-2026"); assert.equal(topicIdFromTitle("!!!"), ""); assert.equal(topicTitleProblem("Kettles"), null); assert.match(topicTitleProblem(" ") ?? "", /topic/); assert.match(topicTitleProblem("x".repeat(121)) ?? "", /at most 120/); }); test("the first read of a page makes a topic named for it; a re-read adds posts, keeps old ones, appends the read", async () => { const dir = root("reread"); await writeXTrendingPosts(dir, [post("101", "teapot_news", "one"), post("102", "saucer_fan", "two")]); const first = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101", "102"], added: 2, media: { "101": { count: 2, kinds: ["image"] } }, }); assert.deepEqual(first, { topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: true }, placed: 2, kept: 0, gone: [], back: [], }); await writeXTrendingPosts(dir, [post("103", "lid_watch", "three")]); const second = await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 1, }); assert.deepEqual(second, { topic: { id: `t-${REF.trendId}`, title: `Trending ${REF.trendId}`, created: false }, placed: 1, kept: 1, // 102 was not shown, but this read did not say it reached the page's end. gone: [], back: [], }); const topics = await readXTrendingTopics(dir); assert.equal(topics.length, 1); assert.deepEqual(topics[0].sources, [ { trendId: REF.trendId, url: REF.url, reads: [ { id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 2, added: 2 }, { id: READ_B, at: "2026-11-17T11:00:00.000Z", posts: 2, added: 1 }, ], }, ]); const members = await readXTrendingMembership(dir); assert.deepEqual(Object.keys(members).sort(), ["101", "102", "103"]); assert.deepEqual(members["101"].seen.map((s) => [s.read, s.rank]), [ [READ_A, 1], [READ_B, 2], ]); // 102 was not on the page the second time: it stays. assert.deepEqual(members["102"].seen.map((s) => s.read), [READ_A]); // The same read recorded twice changes nothing. await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["103", "101"], added: 0 }); assert.equal((await readXTrendingTopics(dir))[0].sources[0].reads.length, 2); assert.equal((await readXTrendingMembership(dir))["101"].seen.length, 2); }); test("a named topic is found by id or title, else made; a second page merges into it; a placed post keeps its topic", async () => { const dir = root("named"); await writeXTrendingPosts(dir, [post("201", "a", "one"), post("202", "b", "two"), post("203", "c", "three")]); const made = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettle Festival", postIds: ["201"], added: 1, }); assert.deepEqual(made.topic, { id: "kettle-festival", title: "Kettle Festival", created: true }); // Another page, into the same topic by its title in another case. const merged = await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "kettle festival", postIds: ["202", "201"], added: 1, }); assert.deepEqual(merged.topic, { id: "kettle-festival", title: "Kettle Festival", created: false }); // A third read into another topic: 201 stays where it was placed. const other = await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF_2, topic: "Saucers", postIds: ["201", "203"], added: 1, }); assert.deepEqual(other, { topic: { id: "saucers", title: "Saucers", created: true }, placed: 1, kept: 1, gone: [], back: [] }); const members = await readXTrendingMembership(dir); assert.equal(members["201"].topic, "kettle-festival"); assert.equal(members["203"].topic, "saucers"); const topics = await readXTrendingTopics(dir); assert.deepEqual(topics.map((t) => [t.id, t.sources.map((s) => s.trendId)]), [ ["kettle-festival", [REF.trendId, REF_2.trendId]], ["saucers", [REF_2.trendId]], ]); }); test("the listing gives each post's words, author, media, reads and topic — and nothing of the raw capture", async () => { const dir = root("listing"); await writeXTrendingPosts(dir, [post("301", "teapot_news", "The kettle festival opens today."), post("302", "saucer_fan", "Second.")]); mkdirSync(trendingReadDir(dir, READ_A), { recursive: true }); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["301", "302", "999"], added: 2, media: { "301": { count: 2, kinds: ["image"] } }, }); const all = await listXTrending(dir); assert.deepEqual(all.topics, [ { id: "kettles", title: "Kettles", posts: 2, sources: [{ trendId: REF.trendId, url: REF.url, reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }], }, ]); // 999 is a member with no archived post (a write that never landed): not listed. assert.deepEqual(all.posts, [ { id: "301", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", url: "https://x.com/teapot_news/status/301", text: "The kettle festival opens today.", 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", author: "saucer_fan", createdAt: "2026-11-16T12:00:00.000Z", url: "https://x.com/saucer_fan/status/302", text: "Second.", 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); assert.deepEqual(all.reads, [READ_A]); assert.equal((await listXTrending(dir, { limit: 1 })).posts.length, 1); assert.equal((await listXTrending(dir, { limit: 1 })).total, 2); assert.equal((await listXTrending(dir, { topic: "nope" })).posts.length, 0); // The files are plain JSON with a version. assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "topics.json"), "utf8")).version, 1); assert.equal(JSON.parse(readFileSync(path.join(dir, "trending", "membership.json"), "utf8")).version, 1); }); test("an empty library lists nothing", async () => { assert.deepEqual(await listXTrending(root("empty")), { topics: [], posts: [], total: 0, reads: [] }); }); test("a row carries its first captured picture and its judgement, once there are any", async () => { const dir = root("captured"); await writeXTrendingPosts(dir, [post("401", "a", "one"), post("402", "b", "two"), post("403", "c", "three")]); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["401", "402", "403"], added: 3 }); // 401: a capture with an attached image and a shot; 402: a shot alone; 403: none. // A library's media lives under trending/ (review 2 N9), never in the // channel's own posts-media/, which is planted here to prove it is not read. for (const [id, files] of [["401", ["shot.png", "401_2.jpg", "401_1.jpg", "capture.json", "shot-thread.png"]], ["402", ["shot.png", "capture.json", "402_1.mp4"]]] as const) { mkdirSync(path.join(dir, "trending", "posts-media", id), { recursive: true }); for (const f of files) writeFileSync(path.join(dir, "trending", "posts-media", id, f), "x"); } mkdirSync(path.join(dir, "posts-media", "403"), { recursive: true }); writeFileSync(path.join(dir, "posts-media", "403", "shot.png"), "x"); mkdirSync(path.join(dir, "posts-media", "402"), { recursive: true }); writeFileSync(path.join(dir, "posts-media", "402", "402_9.jpg"), "x"); writeFileSync( path.join(dir, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { "401": { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" }, "402": { state: "maybe", by: "agent", at: "2026-11-17T11:00:00.000Z" }, "403": { state: "drop", by: "nobody", at: "2026-11-17T11:00:00.000Z" }, }, }), ); const { posts } = await listXTrending(dir); const by = Object.fromEntries(posts.map((p) => [p.id, p])); assert.equal(by["401"].media.thumbnail, "trending/posts-media/401/401_1.jpg"); assert.deepEqual(by["401"].judgement, { state: "keep", note: "the opening", by: "agent", at: "2026-11-17T11:00:00.000Z" }); assert.equal(by["402"].media.thumbnail, "trending/posts-media/402/shot.png"); // An ill-shaped judgement is no judgement. assert.equal(by["402"].judgement, undefined); assert.equal(by["403"].media.thumbnail, undefined); assert.equal(by["403"].judgement, undefined); }); // Review 2 N9: nothing of the lane reads or writes channels//posts-media. test("no module of the lane reaches the channel's own posts-media: a library's media is under trending/", async () => { const { readFileSync: read } = await import("node:fs"); const repo = path.resolve(import.meta.dirname, "..", "..", ".."); const lane = [ "common/lib/xTrending/config.ts", "common/lib/xTrending/marker.mjs", "common/lib/xTrending/library-server.ts", "common/lib/xTrending/store.ts", "common/social/xTrendingParse.ts", "common/social/xTrendingRead.ts", "common/controller/readXTrending.ts", "editor/app/channels/[slug]/xTrendingActions.ts", "editor/app/channels/[slug]/components/XTrendingPanel.tsx", "editor/app/api/ops/read-x-trending/route.ts", "editor/app/api/ops/trending/route.ts", "mcp/src/xTrending.ts", ]; for (const rel of lane) { const code = read(path.join(repo, rel), "utf8") .split("\n") .filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l)) .join("\n"); assert.ok(!/postsMediaDir\(|postCaptureDir\(|social\/postCapture"/.test(code), `${rel} uses the posts channel's media layout`); // The only posts-media path the lane builds is the store's, under trending/. const mentions = code.match(/posts-media|POSTS_MEDIA/g) ?? []; if (rel !== "common/lib/xTrending/store.ts") assert.deepEqual(mentions, [], `${rel} names posts-media`); } const { xTrendingPostsMediaDir } = await import("./store"); assert.equal(xTrendingPostsMediaDir("/c/lib"), "/c/lib/trending/posts-media"); }); // Lane x-trending-2. test("gone from the page: only a read that reached the page's end says so, only of posts that page showed, and a post shown again is back", async () => { const dir = root("gone"); await writeXTrendingPosts(dir, [post("801", "a", "one"), post("802", "b", "two"), post("803", "c", "three"), post("804", "d", "four")]); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["801", "802"], added: 2, complete: true }); // Another page of the same topic showed 803; it is never judged by REF's reads. await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T10:30:00.000Z", ref: REF_2, topic: "T", postIds: ["803"], added: 1, complete: true }); // A read that stopped at its cap asserts nothing. const capped = await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0 }); assert.deepEqual(capped.gone, []); assert.equal((await readXTrendingMembership(dir))["802"].gone, undefined); // A complete one does: 802 is gone from the page; 803 (the other page's) and 804 (new) are not. const READ_D = "tr-01JD0000000000000000000000"; const done = await recordXTrendingRead(dir, { readId: READ_D, at: "2026-11-17T11:30:00.000Z", ref: REF, topic: "T", postIds: ["801", "804"], added: 1, complete: true }); assert.deepEqual(done.gone, ["802"]); let members = await readXTrendingMembership(dir); assert.deepEqual(members["802"].gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId }); assert.equal(members["803"].gone, undefined); assert.equal(members["804"].gone, undefined); const row = (await listXTrending(dir)).posts.find((p) => p.id === "802"); assert.deepEqual(row?.gone, { at: "2026-11-17T11:30:00.000Z", read: READ_D, trendId: REF.trendId }); // Recorded once: a later complete read without it does not move the time. const READ_E = "tr-01JE0000000000000000000000"; assert.deepEqual((await recordXTrendingRead(dir, { readId: READ_E, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["801"], added: 0, complete: true })).gone, ["804"]); assert.equal((await readXTrendingMembership(dir))["802"].gone?.at, "2026-11-17T11:30:00.000Z"); // Shown again: back, with the absence kept as history. const READ_F = "tr-01JF0000000000000000000000"; const back = await recordXTrendingRead(dir, { readId: READ_F, at: "2026-11-17T12:30:00.000Z", ref: REF, topic: "T", postIds: ["802", "801"], added: 0, complete: true }); assert.deepEqual(back.back, ["802"]); members = await readXTrendingMembership(dir); assert.equal(members["802"].gone, undefined); assert.deepEqual(members["802"].wasGone, [{ from: "2026-11-17T11:30:00.000Z", to: "2026-11-17T12:30:00.000Z" }]); }); test("a captured post's row says what its capture holds and what it is owed", async () => { const dir = root("capture-summary"); await writeXTrendingPosts(dir, [post("811", "a", "one"), post("812", "b", "two")]); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["811", "812"], added: 2 }); mkdirSync(path.join(dir, "trending", "posts-media", "811"), { recursive: true }); writeFileSync( path.join(dir, "trending", "posts-media", "811", "capture.json"), JSON.stringify({ version: 1, id: "811", capturedAt: "2026-11-17T10:05:00.000Z", state: "captured", mediaState: "error", mediaOwed: "kept", media: [{ name: "811_1.jpg" }] }), ); const rows = Object.fromEntries((await listXTrending(dir)).posts.map((p) => [p.id, p])); 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"); }); // ── lane posts-library: what the judge view asks of the listing ───────────── async function judgeLibrary(name: string): Promise { const dir = root(name); const reply: Post = { ...post("903", "saucer_fan", "A reply about spouts."), isReply: true, replyTo: { platform: "twitter", id: "901", author: "teapot_news" }, threadId: "901" }; await writeXTrendingPosts(dir, [ { ...post("901", "teapot_news", "The Kettle festival opens."), authorName: "Teapot News", mediaCount: 1, links: ["https://example.org/a"], engagement: { likes: 4 } }, post("902", "saucer_fan", "Saucers are underrated."), reply, post("904", "Lid_Watch", "A lid fell off a kettle."), post("905", "cup_other", "Other topic."), ]); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "902", "903"], added: 3, media: { "901": { count: 1, kinds: ["image"] } }, threads: { "903": "901" }, complete: true }); await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "903", "904"], added: 1, complete: true }); await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["905"], added: 1 }); writeFileSync( path.join(dir, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { "902": { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" }, "904": { state: "later", by: "agent", at: "2026-11-17T12:30:00.000Z" } }, threads: { "901": { state: "keep", note: "the opening", by: "operator", at: "2026-11-17T12:31:00.000Z" } }, }), ); const cap = path.join(dir, "trending", "posts-media", "901"); mkdirSync(cap, { recursive: true }); for (const [f, body] of [["shot.png", "s"], ["shot-thread.png", "st"], ["901_1.jpg", "abc"], ["901_2.mp4", "abcde"], ["article.png", "a"], ["notes.txt", "n"]] as const) writeFileSync(path.join(cap, f), body); writeFileSync( path.join(cap, "capture.json"), JSON.stringify({ version: 1, id: "901", capturedAt: "2026-11-17T12:40:00.000Z", state: "captured", mediaState: "ok", media: [], context: { readAt: "x", quoted: { text: "a quoted line", handle: "spout_co", media: [{ kind: "image", url: "https://example.org/p.jpg" }] } } }), ); return dir; } test("with no new option the listing is what it was: no detail, no counts, no authors, no ids", async () => { const dir = await judgeLibrary("judge-plain"); const plain = await listXTrending(dir); assert.deepEqual(Object.keys(plain).sort(), ["posts", "reads", "topics", "total"]); assert.ok(plain.topics.every((t) => !("counts" in t))); assert.ok(plain.posts.every((p) => !("detail" in p))); }); test("the filters: the judgement in force, gone, media, author, words, first seen since; offset pages them", async () => { const dir = await judgeLibrary("judge-filters"); const ids = async (filter: Parameters[1]) => (await listXTrending(dir, filter)).posts.map((p) => p.id).sort(); assert.deepEqual(await ids({ topic: "kettles" }), ["901", "902", "903", "904"]); // 903 has no judgement of its own: its thread's (keep) is in force. assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep" } }), ["901", "903"]); assert.deepEqual(await ids({ topic: "kettles", filter: { state: "drop" } }), ["902"]); assert.deepEqual(await ids({ topic: "kettles", filter: { state: "later" } }), ["904"]); assert.deepEqual(await ids({ filter: { state: "unjudged" } }), ["905"]); // 902 was on the page at the first read and not at the second, which reached its end. assert.deepEqual(await ids({ filter: { gone: true } }), ["902"]); assert.deepEqual(await ids({ filter: { media: true } }), ["901"]); assert.deepEqual(await ids({ filter: { author: "@LID_watch" } }), ["904"]); assert.deepEqual(await ids({ filter: { author: "saucer_fan" } }), ["902", "903"]); // Every word, any case, over the words, the handle and the display name. assert.deepEqual(await ids({ filter: { q: "KETTLE" } }), ["901", "904"]); assert.deepEqual(await ids({ filter: { q: "kettle lid" } }), ["904"]); assert.deepEqual(await ids({ filter: { q: "teapot news" } }), ["901"]); assert.deepEqual(await ids({ filter: { q: "nothinghere" } }), []); assert.deepEqual(await ids({ filter: { since: "2026-11-17T10:30:00.000Z" } }), ["904", "905"]); assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep", q: "spouts" } }), ["903"]); // By the hand whose judgement is in force: the operator's drops, the agent's later. assert.deepEqual(await ids({ filter: { state: "drop", by: "operator" } }), ["902"]); assert.deepEqual(await ids({ filter: { state: "drop", by: "agent" } }), []); assert.deepEqual(await ids({ filter: { by: "agent" } }), ["904"]); assert.deepEqual(await ids({ filter: { by: "operator" } }), ["901", "902", "903"]); // Pages: the same order, cut. const all = (await listXTrending(dir)).posts.map((p) => p.id); const two = await listXTrending(dir, { limit: 2, offset: 2 }); assert.deepEqual(two.posts.map((p) => p.id), all.slice(2, 4)); assert.equal(two.total, 5); assert.deepEqual((await listXTrending(dir, { offset: 99 })).posts, []); }); test("ids: every matching id in listing order, uncapped, and no rows", async () => { const dir = await judgeLibrary("judge-ids"); const all = (await listXTrending(dir, { topic: "kettles" })).posts.map((p) => p.id); const out = await listXTrending(dir, { topic: "kettles", ids: true, limit: 1 }); assert.deepEqual(out.ids, all); assert.deepEqual(out.posts, []); assert.equal(out.total, 4); assert.deepEqual((await listXTrending(dir, { ids: true, filter: { state: "drop" } })).ids, ["902"]); }); test("detail: a topic's counts, the accounts, the rest of the record, the first sighting, the own judgement and the capture's files by name", async () => { const dir = await judgeLibrary("judge-detail"); const out = await listXTrending(dir, { topic: "kettles", detail: true }); const topics = Object.fromEntries(out.topics.map((t) => [t.id, t.counts])); assert.deepEqual(topics.kettles, { unjudged: 0, keep: 2, drop: 1, later: 1, gone: 1 }); assert.deepEqual(topics.cups, { unjudged: 1, keep: 0, drop: 0, later: 0, gone: 0 }); assert.deepEqual(out.authors, [ { author: "saucer_fan", posts: 2 }, { author: "Lid_Watch", posts: 1 }, { author: "teapot_news", posts: 1 }, ]); const by = Object.fromEntries(out.posts.map((p) => [p.id, p])); assert.deepEqual(by["901"].detail?.post, { isReply: false, isRepost: false, links: ["https://example.org/a"], engagement: { likes: 4 }, mediaCount: 1 }); assert.deepEqual(by["903"].detail?.post.replyTo, { platform: "twitter", id: "901", author: "teapot_news" }); assert.equal(by["901"].detail?.firstSeenAt, "2026-11-17T10:00:00.000Z"); assert.equal(by["904"].detail?.firstSeenAt, "2026-11-17T11:00:00.000Z"); // 903: the thread's judgement is in force, and it has none of its own. assert.equal(by["903"].judgement?.from, "thread"); assert.equal(by["903"].detail?.ownJudgement, undefined); assert.equal(by["902"].detail?.ownJudgement?.state, "drop"); assert.equal(by["903"].detail?.threadJudgement?.note, "the opening"); assert.equal(by["902"].detail?.threadJudgement, undefined); // The capture: names and sizes, pictures and videos only; the context without its media addresses. assert.deepEqual(by["901"].detail?.capture, { shot: "shot.png", threadShot: "shot-thread.png", media: [ { name: "901_1.jpg", kind: "image", bytes: 3 }, { name: "901_2.mp4", kind: "video", bytes: 5 }, ], context: { quoted: { text: "a quoted line", handle: "spout_co" } }, }); assert.equal(by["902"].detail?.capture, undefined); assert.doesNotMatch(JSON.stringify(out), /example\.org\/p\.jpg|notes\.txt|capture\.json/); }); test("detail with the topics' seen marks: each topic's new posts in the same pass; a topic never marked is new in full", async () => { const dir = await judgeLibrary("judge-fresh"); const fresh = async (seen?: Record) => Object.fromEntries((await listXTrending(dir, { detail: true, limit: 1, ...(seen ? { seen } : {}) })).topics.map((t) => [t.id, t.fresh])); // No marks handed in: no `fresh` at all. assert.deepEqual(await fresh(), { kettles: undefined, cups: undefined }); assert.deepEqual(await fresh({}), { kettles: 4, cups: 1 }); // 904 was first shown at 11:00, the rest of kettles at 10:00; cups' post at 12:00. assert.deepEqual(await fresh({ kettles: "2026-11-17T10:30:00.000Z" }), { kettles: 1, cups: 1 }); assert.deepEqual(await fresh({ kettles: "2026-11-17T11:00:00.000Z", cups: "2026-11-17T12:00:00.000Z" }), { kettles: 0, cups: 0 }); // The count is of the whole topic, whatever the posts asked for. const narrowed = await listXTrending(dir, { detail: true, topic: "cups", filter: { state: "keep" }, seen: { kettles: "2026-11-17T10:30:00.000Z" } }); assert.equal(narrowed.topics.find((t) => t.id === "kettles")?.fresh, 1); // A mark that is no time counts nothing as seen; and never without detail. assert.deepEqual(await fresh({ kettles: "soon" }), { kettles: 4, cups: 1 }); assert.ok((await listXTrending(dir, { seen: {} })).topics.every((t) => !("fresh" in t))); }); test("a library in one line: its topics, its posts and how many are undecided", async () => { assert.deepEqual(await summarizeXTrending(await judgeLibrary("judge-summary")), { topics: 2, posts: 5, unjudged: 1 }); assert.deepEqual(await summarizeXTrending(root("judge-summary-empty")), { topics: 0, posts: 0, unjudged: 0 }); }); // ── lane x-followups: the page's own words, the topic's name, the tab ────── const PAGE = { title: "Kettle festival opens", summary: "The annual kettle festival opened this morning.", lastUpdatedAt: "2026-11-16T11:30:00.000Z", tabs: [ { label: "Top", timelineId: "tl-top" }, { label: "Latest", timelineId: "tl-latest" }, ], }; test("a topic nobody named is born with the page's title; the source keeps X's title, summary, last update and tabs; the listing says them", async () => { const dir = root("page-born"); const made = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); // The id stays the page's: a name can change, an id cannot. assert.deepEqual(made.topic, { id: `t-${REF.trendId}`, title: "Kettle festival opens", created: true }); const [topic] = await readXTrendingTopics(dir); assert.deepEqual(topic.sources, [ { trendId: REF.trendId, url: REF.url, ...PAGE, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1, tab: "Top" }] }, ]); assert.deepEqual((await readXTrendingMembership(dir))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: "2026-11-17T10:00:00.000Z", rank: 1, tab: "Top" }]); const listing = await listXTrending(dir); assert.deepEqual(listing.topics[0].sources, [ { trendId: REF.trendId, url: REF.url, title: PAGE.title, summary: PAGE.summary, lastUpdatedAt: PAGE.lastUpdatedAt, tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, lastReadAt: "2026-11-17T10:00:00.000Z" }, ]); // No page in the capture: the fallback name, as before, and nothing invented on the source. const bare = root("page-none"); assert.equal((await recordXTrendingRead(bare, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 })).topic.title, `Trending ${REF.trendId}`); assert.deepEqual((await readXTrendingTopics(bare))[0].sources[0], { trendId: REF.trendId, url: REF.url, reads: [{ id: READ_A, at: "2026-11-17T10:00:00.000Z", posts: 1, added: 1 }] }); // A title of several lines, or longer than a topic's name may be, is one line and cut; the source keeps X's whole title. const long = root("page-long"); const title = `Kettle\n festival ${"x".repeat(200)}`; const cut = await recordXTrendingRead(long, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title } }); assert.equal(cut.topic.title.length, 120); assert.match(cut.topic.title, /^Kettle festival x+…$/); assert.equal(topicTitleProblem(cut.topic.title), null); assert.equal((await readXTrendingTopics(long))[0].sources[0].title, `Kettle festival ${"x".repeat(200)}`); }); test("a topic still carrying the fallback name takes the page's title on a later pass; a topic somebody named never does", async () => { const { renameXTrendingTopic } = await import("./organise"); const IDLE = () => false; const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE, tab: "Top" }; const fallback = `Trending ${REF.trendId}`; // Made before titles were read: the next read names it — and the SAME read parsed again (a reparse) does too. const dir = root("name-fallback"); await recordXTrendingRead(dir, first); const read = await recordXTrendingRead(dir, later); assert.deepEqual(read.topic, { id: `t-${REF.trendId}`, title: PAGE.title, created: false, renamed: { was: fallback } }); // Once named so, a later pass renames nothing (and says nothing). assert.equal((await recordXTrendingRead(dir, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z", page: { ...PAGE, title: "Another headline" } })).topic.renamed, undefined); assert.equal((await readXTrendingTopics(dir))[0].title, PAGE.title); // …while the SOURCE follows X's words. assert.equal((await readXTrendingTopics(dir))[0].sources[0].title, "Another headline"); const reparsed = root("name-reparse"); await recordXTrendingRead(reparsed, first); const again = await recordXTrendingRead(reparsed, { ...first, added: 0, page: PAGE, tab: "Top", tabs: { "101": "Top" } }); assert.deepEqual(again.topic.renamed, { was: fallback }); assert.equal((await readXTrendingTopics(reparsed))[0].sources[0].reads[0].tab, "Top"); // The reparse fills the tab its sighting could not say before, and adds no second sighting. assert.deepEqual((await readXTrendingMembership(reparsed))["101"].seen, [{ read: READ_A, trendId: REF.trendId, at: first.at, rank: 1, tab: "Top" }]); // A name asked for at the read stays. const asked = root("name-asked"); await recordXTrendingRead(asked, { ...first, topic: "Kettles" }); assert.equal((await recordXTrendingRead(asked, later)).topic.title, "Kettles"); // Renamed by an agent or by the operator: never renamed by a read — even renamed back to the fallback's own words. for (const by of ["agent", "operator"] as const) { const named = root(`name-renamed-${by}`); await recordXTrendingRead(named, first); assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: "My kettles", by, readInFlight: IDLE })).ok, true); assert.equal((await recordXTrendingRead(named, later)).topic.title, "My kettles"); assert.equal((await renameXTrendingTopic(named, { topic: `t-${REF.trendId}`, title: fallback, by, readInFlight: IDLE })).ok, true); const kept = await recordXTrendingRead(named, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); assert.equal(kept.topic.title, fallback); assert.equal(kept.topic.renamed, undefined); // X's title is on the source all the same. assert.equal((await readXTrendingTopics(named))[0].sources[0].title, PAGE.title); } // The fallback of ANOTHER page is somebody's choice of words here: a second page read into the topic does not rename it. const other = root("name-other-page"); await recordXTrendingRead(other, first); assert.equal((await recordXTrendingRead(other, { ...later, ref: REF_2, topic: `t-${REF.trendId}` })).topic.title, fallback); // A title another topic already answers to is not taken: a topic's name is its own. const taken = root("name-taken"); await recordXTrendingRead(taken, { ...first, ref: REF_2, topic: "kettle FESTIVAL opens" }); await recordXTrendingRead(taken, { ...first, readId: READ_B }); const refused = await recordXTrendingRead(taken, { ...later, readId: READ_C, at: "2026-11-17T12:00:00.000Z" }); assert.equal(refused.topic.title, fallback); assert.equal(refused.topic.renamed, undefined); assert.equal((await readXTrendingTopics(taken)).find((t) => t.id === `t-${REF.trendId}`)?.sources[0].title, PAGE.title); // …and a NEW topic is not born with a name another answers to either. const born = root("name-born-taken"); await recordXTrendingRead(born, { ...first, ref: REF_2, topic: PAGE.title }); assert.equal((await recordXTrendingRead(born, { ...later })).topic.title, fallback); }); test("an older read parsed again does not put its words over a newer read's", async () => { const dir = root("page-order"); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 1, page: { title: "Morning headline", summary: "Morning." } }); await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Noon headline", summary: "Noon." } }); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "T", postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." }, tab: "Top" }); const source = (await readXTrendingTopics(dir))[0].sources[0]; assert.equal(source.title, "Noon headline"); assert.equal(source.summary, "Noon."); // The read's own tab is the read's, whenever it is learned. assert.equal(source.reads[0].tab, "Top"); }); test("gone from the page is said per tab: a post only the other tab showed is not missing from this one", async () => { const dir = root("gone-tabs"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; // 701 and 702 on Top; 703 on Latest only; 704 by a read from before tabs were read. await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["704"], added: 1 }); await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", postIds: ["701", "702"], added: 2, tab: "Top" }); await recordXTrendingRead(dir, { readId: READ_C, at: at(11), ref: REF, topic: "T", postIds: ["703"], added: 1, tab: "Latest" }); // A complete read of Top that shows 701 only: 702 is gone (Top showed it), 704 too (untagged: the opening tab's), 703 is not. const top = await recordXTrendingRead(dir, { readId: "tr-01JD0000000000000000000000", at: at(12), ref: REF, topic: "T", postIds: ["701"], added: 0, tab: "Top", complete: true }); assert.deepEqual([...top.gone].sort(), ["702", "704"]); const members = await readXTrendingMembership(dir); assert.equal(members["703"].gone, undefined); // The listing says which tab showed a post. await writeXTrendingPosts(dir, ["701", "702", "703", "704"].map((id) => post(id, "a", `post ${id}`))); const listing = await listXTrending(dir); assert.deepEqual(listing.posts.find((p) => p.id === "703")?.reads, [{ read: READ_C, trendId: REF.trendId, at: at(11), tab: "Latest" }]); assert.deepEqual(listing.posts.find((p) => p.id === "704")?.reads, [{ read: READ_A, trendId: REF.trendId, at: at(9) }]); assert.equal(listing.topics[0].sources[0].lastReadTab, "Top"); // A complete read that cannot say its tab judges only sightings that name none: 703, seen on Latest, is not its to judge. const unknown = await recordXTrendingRead(dir, { readId: "tr-01JE0000000000000000000000", at: at(13), ref: REF, topic: "T", postIds: ["701"], added: 0, complete: true }); assert.deepEqual(unknown.gone, []); assert.equal((await readXTrendingMembership(dir))["703"].gone, undefined); }); // ── review 1: S4 and the set-name field ──────────────────────────────────── test("S4: an older read parsed again never names a topic by a title older than the one its source holds", async () => { const { renameXTrendingTopic } = await import("./organise"); const dir = root("s4-age"); const fallback = `Trending ${REF.trendId}`; // Another topic answers to the noon title, so the page's topic keeps its fallback at the noon read… await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T08:00:00.000Z", ref: REF_2, topic: "Noon headline", postIds: ["201"], added: 1 }); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }); const noon = await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Noon headline" } }); assert.equal(noon.topic.title, fallback); // …then that other topic is renamed away, and the MORNING read is parsed again: its title is older than the source's. assert.equal((await renameXTrendingTopic(dir, { topic: "noon-headline", title: "Something else", by: "operator", readInFlight: () => false })).ok, true); const morning = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." } }); assert.deepEqual(morning.topic.renamed, { was: fallback }); assert.equal(morning.topic.title, "Noon headline"); const topic = (await readXTrendingTopics(dir)).find((t) => t.id === `t-${REF.trendId}`)!; assert.equal(topic.title, "Noon headline"); assert.equal(topic.titleFrom, "page"); assert.equal(topic.sources[0].title, "Noon headline"); // What the source did not have yet is taken even from the older read: there is nothing newer to keep. assert.equal(topic.sources[0].summary, "Morning."); }); test("a name that was SET is recorded in a field no merge or move writes, and a read never changes it afterwards", async () => { const { mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } = await import("./organise"); const { xTrendingTitleFrom, xTrendingTopicNameIsSet } = await import("./store"); const IDLE = () => false; const fallback = `Trending ${REF.trendId}`; const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE }; const topicOf = async (dir: string, id = `t-${REF.trendId}`) => (await readXTrendingTopics(dir)).find((t) => t.id === id)!; // A name ASKED FOR that is literally the fallback's words is a set name. const asked = root("set-asked-fallback"); const made = await recordXTrendingRead(asked, { ...first, topic: fallback }); assert.equal((await topicOf(asked, made.topic.id)).titleFrom, "ask"); assert.equal((await recordXTrendingRead(asked, { ...later, topic: made.topic.id })).topic.title, fallback); // Renamed, then MERGED INTO (which overwrites `organised`): still a set name. const merged = root("set-rename-then-merge"); await recordXTrendingRead(merged, first); await recordXTrendingRead(merged, { readId: READ_C, at: "2026-11-17T09:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["201"], added: 1 }); assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback + " ", by: "agent", readInFlight: IDLE })).ok, true); assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: "Kettles", by: "agent", readInFlight: IDLE })).ok, true); assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback, by: "agent", readInFlight: IDLE })).ok, true); const m = await mergeXTrendingTopics(merged, { into: `t-${REF.trendId}`, from: ["cups"], by: "operator", readInFlight: IDLE }); assert.equal(m.ok, true, m.ok ? "" : m.error); const after = await topicOf(merged); assert.equal(after.organised?.what, "merge"); assert.equal(after.titleFrom, "rename"); assert.equal(xTrendingTopicNameIsSet(after), true); assert.equal((await recordXTrendingRead(merged, later)).topic.title, fallback); // A topic made by a move, under the name given, is a set name too. const moved = root("set-move"); await recordXTrendingRead(moved, first); const mv = await moveXTrendingPosts(moved, { ids: ["101"], to: "Picked", create: true, by: "agent" }); assert.equal(mv.ok, true, mv.ok ? "" : mv.error); assert.equal((await readXTrendingTopics(moved)).find((t) => t.title === "Picked")?.titleFrom, "ask"); // A topic that took its page's title says so, and is not "set". const page = root("set-page"); await recordXTrendingRead(page, { ...first, page: PAGE }); assert.equal((await topicOf(page)).titleFrom, "page"); assert.equal(xTrendingTopicNameIsSet(await topicOf(page)), false); // Topics from before the field: a rename as the last organise step, a name that is no fallback (asked), a fallback. const legacy = (title: string, organised?: { what: "rename" | "merge"; by: "agent"; at: string }) => ({ title, sources: [{ trendId: REF.trendId, url: REF.url, reads: [] }], ...(organised ? { organised } : {}) }); assert.equal(xTrendingTitleFrom(legacy("Kettles")), "ask"); assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "rename", by: "agent", at: "x" })), "rename"); assert.equal(xTrendingTitleFrom(legacy(fallback)), undefined); assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "merge", by: "agent", at: "x" })), undefined); }); test("a listing gives at most 600 characters of X's summary, cut at a word; the source keeps all of it", async () => { const { listedXTrendingSummary, X_TRENDING_SUMMARY_LIST_MAX } = await import("./store"); assert.equal(X_TRENDING_SUMMARY_LIST_MAX, 600); const dir = root("summary-cap"); const summary = Array.from({ length: 150 }, (_, i) => `word${i}`).join(" "); assert.ok(summary.length > 900); await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title: "T", summary } }); assert.equal((await readXTrendingTopics(dir))[0].sources[0].summary, summary); const listed = (await listXTrending(dir)).topics[0].sources[0].summary!; assert.ok(listed.length <= 600, String(listed.length)); assert.match(listed, /^word0 word1 .* word\d+…$/); assert.ok(summary.startsWith(listed.slice(0, -1))); // A short one is given whole; one unbroken run is cut hard. assert.equal(listedXTrendingSummary("Short."), "Short."); assert.equal(listedXTrendingSummary("x".repeat(700)).length, 600); }); // ── added scope R3: one read, two tabs ───────────────────────────────────── test("R3: a read of two tabs records each tab's sightings and ranks; gone is said tab by tab, and of the page once every tab that showed the post has stopped", async () => { const dir = root("two-tabs"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; const id = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; const read = (n: number, top: string[], latest: string[], complete: { top?: boolean; latest?: boolean } = { top: true, latest: true }, page = true) => recordXTrendingRead(dir, { readId: id(n), at: at(8 + n), ref: REF, topic: "T", postIds: [...new Set([...top, ...latest])], added: 0, ...(page ? { page: PAGE } : {}), tabReads: [ // Named by the capture's page answer, or only by the timeline id the requests carried. { ...(page ? { tab: "Top" } : {}), timelineId: "tl-top", postIds: top, ...(complete.top ? { complete: true } : {}) }, { ...(page ? { tab: "Latest" } : {}), timelineId: "tl-latest", postIds: latest, ...(complete.latest ? { complete: true } : {}) }, ], }); await writeXTrendingPosts(dir, ["901", "902", "903", "904"].map((p) => post(p, "a", `post ${p}`))); // Read 1: 901 and 902 on both tabs, 903 on Top only, 904 on Latest only. const first = await read(1, ["901", "902", "903"], ["904", "902", "901"]); assert.deepEqual(first.tabs, ["Top", "Latest"]); assert.deepEqual([first.placed, first.kept, first.gone], [4, 0, []]); let members = await readXTrendingMembership(dir); assert.deepEqual(members["902"].seen, [ { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Top" }, { read: id(1), trendId: REF.trendId, at: at(9), rank: 2, tab: "Latest" }, ]); assert.deepEqual(members["904"].seen.map((s) => [s.tab, s.rank]), [["Latest", 1]]); assert.deepEqual((await readXTrendingTopics(dir))[0].sources[0].reads[0].tabs, ["Top", "Latest"]); assert.deepEqual((await listXTrending(dir)).topics[0].sources[0].lastReadTabs, ["Top", "Latest"]); // Read 2: Latest no longer shows 902 (Top still does) nor 904 (which only Latest showed). const second = await read(2, ["901", "902", "903"], ["901"]); assert.deepEqual(second.gone, ["904"]); assert.deepEqual(second.goneFromTab, [{ id: "902", tab: "Latest" }]); members = await readXTrendingMembership(dir); assert.equal(members["902"].gone, undefined); assert.deepEqual(Object.keys(members["902"].goneTabs ?? {}), ["Latest"]); assert.deepEqual(members["904"].gone, { at: at(10), read: id(2), trendId: REF.trendId }); let listing = await listXTrending(dir); assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs, [{ tab: "Latest", at: at(10), read: id(2) }]); assert.equal(listing.posts.find((p) => p.id === "902")?.gone, undefined); // Gone from the page says it all: no per-tab line beside it. assert.equal(listing.posts.find((p) => p.id === "904")?.goneTabs, undefined); assert.ok(listing.posts.find((p) => p.id === "904")?.gone); // Read 3: Top was capped (not read to its end), Latest to its end again: nothing new is said of Top's posts. const third = await read(3, ["901"], ["901"], { latest: true }); assert.deepEqual([third.gone, third.goneFromTab], [[], undefined]); // Read 4: Top to its end without 902: now gone from every tab that showed it — gone from the page. 903 too (Top only). const fourth = await read(4, ["901"], ["901"]); assert.deepEqual([...fourth.gone].sort(), ["902", "903"]); // Read 5 names no tab in its capture (no page answer): the source's known tabs name them by timeline id. 902 is back on Latest. const fifth = await read(5, ["901"], ["901", "902"], { top: true, latest: true }, false); assert.deepEqual(fifth.tabs, ["Top", "Latest"]); assert.deepEqual(fifth.back, ["902"]); members = await readXTrendingMembership(dir); assert.equal(members["902"].gone, undefined); assert.deepEqual(members["902"].wasGone, [{ from: at(12), to: at(13) }]); // Still gone from Top, shown again by Latest: said so. listing = await listXTrending(dir); assert.deepEqual(listing.posts.find((p) => p.id === "902")?.goneTabs?.map((g) => g.tab), ["Top"]); assert.equal(members["902"].seen.at(-1)?.tab, "Latest"); }); // ── review 2 (lane x-followups): M2 and ruling R-d ───────────────────────── test("M2: a post seen only by reads from before tabs is not marked gone by a complete Latest read while Top stopped at its cap", async () => { const dir = root("m2-untagged"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; await writeXTrendingPosts(dir, ["601", "602"].map((p) => post(p, "a", `post ${p}`))); // A read from before tabs were read: its sightings name no tab (the page opened on Top). await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["601", "602"], added: 2 }); // A two-tab read: Top stopped at its post cap (it shows 602 only), Latest read to its end, and neither shows 601. const twoTabs = (readId: string, h: number, topComplete: boolean) => recordXTrendingRead(dir, { readId, at: at(h), ref: REF, topic: "T", page: PAGE, postIds: ["602"], added: 0, tabReads: [ { tab: "Top", timelineId: "tl-top", postIds: ["602"], ...(topComplete ? { complete: true } : {}) }, { tab: "Latest", timelineId: "tl-latest", postIds: [], complete: true }, ], }); const capped = await twoTabs(READ_B, 10, false); assert.deepEqual([capped.gone, capped.goneFromTab], [[], undefined]); let members = await readXTrendingMembership(dir); assert.equal(members["601"].gone, undefined); assert.equal(members["601"].goneTabs, undefined, "Latest never showed it: it is not Latest's to judge"); // Only a complete read of the tab the page opens on judges it: then it is gone from Top, which was the only tab that showed it. const READ_D = "tr-01JD0000000000000000000000"; const complete = await twoTabs(READ_D, 11, true); assert.deepEqual(complete.gone, ["601"]); members = await readXTrendingMembership(dir); assert.deepEqual(Object.keys(members["601"].goneTabs ?? {}), ["Top"]); assert.deepEqual(members["601"].gone, { at: at(11), read: READ_D, trendId: REF.trendId }); }); test("M2: a read that cannot name its tab still judges sightings that name none; a named read of another tab never does", async () => { const dir = root("m2-unnamed"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["611", "612"], added: 2 }); // Latest, named, read to its end: not its to judge. const latest = await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", postIds: ["612"], added: 0, tab: "Latest", complete: true }); assert.deepEqual(latest.gone, []); // An unnamed complete read: it is. const unnamed = await recordXTrendingRead(dir, { readId: READ_C, at: at(11), ref: REF, topic: "T", postIds: ["612"], added: 0, complete: true }); assert.deepEqual(unnamed.gone, ["611"]); }); test("R-d: gone from the PAGE needs every tab that showed the post to drop it IN THE SAME READ; marks from different reads stay per tab", async () => { const dir = root("rd-same-read"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; const id = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; const read = (n: number, top: string[], latest: string[], complete: { top?: boolean; latest?: boolean }) => recordXTrendingRead(dir, { readId: id(n), at: at(8 + n), ref: REF, topic: "T", page: PAGE, postIds: [...new Set([...top, ...latest])], added: 0, tabReads: [ { tab: "Top", timelineId: "tl-top", postIds: top, ...(complete.top ? { complete: true } : {}) }, { tab: "Latest", timelineId: "tl-latest", postIds: latest, ...(complete.latest ? { complete: true } : {}) }, ], }); await writeXTrendingPosts(dir, ["621", "622"].map((p) => post(p, "a", `post ${p}`))); // Read 1: both tabs show 621 and 622. await read(1, ["621", "622"], ["621", "622"], { top: true, latest: true }); // Read 2: Latest to its end without 621; Top capped (it showed 622 only). const second = await read(2, ["622"], ["622"], { latest: true }); assert.deepEqual([second.gone, second.goneFromTab], [[], [{ id: "621", tab: "Latest" }]]); // Read 3: Top to its end without 621; Latest capped. Gone from Top now, and from Latest since read 2 — two reads: not gone from the page. const third = await read(3, ["622"], ["622"], { top: true }); assert.deepEqual([third.gone, third.goneFromTab], [[], [{ id: "621", tab: "Top" }]]); let members = await readXTrendingMembership(dir); assert.equal(members["621"].gone, undefined); assert.deepEqual(Object.keys(members["621"].goneTabs ?? {}).sort(), ["Latest", "Top"]); assert.deepEqual(members["621"].goneTabs?.Latest?.read, id(2)); assert.deepEqual(members["621"].goneTabs?.Top?.read, id(3)); // The listing says each tab, with its own time — never "gone from the page". const listing = await listXTrending(dir); assert.equal(listing.posts.find((p) => p.id === "621")?.gone, undefined); assert.deepEqual(listing.posts.find((p) => p.id === "621")?.goneTabs?.map((g) => [g.tab, g.read]), [["Latest", id(2)], ["Top", id(3)]]); // Read 4: both tabs to their end, neither shows 621: gone from the page, by this read. const fourth = await read(4, ["622"], ["622"], { top: true, latest: true }); assert.deepEqual(fourth.gone, ["621"]); members = await readXTrendingMembership(dir); assert.deepEqual(members["621"].gone, { at: at(12), read: id(4), trendId: REF.trendId }); // A post one tab still shows in the same read is never gone from the page, whatever the other tab says. const fifth = await read(5, ["622"], [], { top: true, latest: true }); assert.deepEqual([fifth.gone, fifth.goneFromTab], [[], [{ id: "622", tab: "Latest" }]]); }); test("review 3 S7: the opening tab is the one named Top, wherever the page's answer lists it; else the first", async () => { const dir = root("s7-opening"); const at = (h: number) => `2026-11-17T${String(h).padStart(2, "0")}:00:00.000Z`; await writeXTrendingPosts(dir, ["621", "622"].map((p) => post(p, "a", `post ${p}`))); // A read from before tabs: its sightings name none (the page opened on Top). await recordXTrendingRead(dir, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["621", "622"], added: 2 }); // The page's answer lists Latest FIRST. Top stopped at its cap; Latest read to its end; neither shows 621. const latestFirst = { ...PAGE, tabs: [PAGE.tabs[1], PAGE.tabs[0]] }; const r = await recordXTrendingRead(dir, { readId: READ_B, at: at(10), ref: REF, topic: "T", page: latestFirst, postIds: ["622"], added: 0, tabReads: [ { tab: "Top", timelineId: "tl-top", postIds: ["622"] }, { tab: "Latest", timelineId: "tl-latest", postIds: [], complete: true }, ], }); assert.deepEqual(r.gone, [], "Latest is not the opening tab because it is listed first"); const members = await readXTrendingMembership(dir); assert.equal(members["621"].goneTabs, undefined); // A page whose tabs name no Top: its first tab opens. const dir2 = root("s7-first"); await writeXTrendingPosts(dir2, ["631", "632"].map((p) => post(p, "a", `post ${p}`))); await recordXTrendingRead(dir2, { readId: READ_A, at: at(9), ref: REF, topic: "T", postIds: ["631", "632"], added: 2 }); const other = { ...PAGE, tabs: [{ label: "For you", timelineId: "tl-a" }, { label: "Newest", timelineId: "tl-b" }] }; const r2 = await recordXTrendingRead(dir2, { readId: READ_B, at: at(10), ref: REF, topic: "T", page: other, postIds: ["632"], added: 0, tabReads: [ { tab: "For you", timelineId: "tl-a", postIds: ["632"], complete: true }, { tab: "Newest", timelineId: "tl-b", postIds: [] }, ], }); assert.deepEqual(r2.gone, ["631"]); });