import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { judgeXTrending } from "./judgements"; import { MERGE_IS_THE_OPERATORS, MERGE_WAITS_FOR_READS, RENAME_WAITS_FOR_READS, mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } from "./organise"; import { mutateXTrendingPublished, readXTrendingPublished } from "./published"; import { listXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, writeXTrendingPosts } from "./store"; import { readXTrendingWatches, setXTrendingWatch } from "./watch"; import type { Post } from "../posts"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-organise-")); after(() => rmSync(TMP, { recursive: true, force: true })); const READ = (c: string) => `tr-01J${c}0000000000000000000000`; const REF = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); const NOW = Date.parse("2026-11-18T10:00:00.000Z"); const IDLE = () => false; function post(id: string, author: string, text: string, replyTo?: 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", ...(replyTo ? { threadId: replyTo, replyTo: { id: replyTo, platform: "twitter" as const } } : {}), isReply: Boolean(replyTo), isRepost: false, links: [], }; } // Two topics: "Kettles" (page 1: posts 101, 102 and 103, a reply to 101) and // "Saucers" (page 2: posts 201, 202; page 1 again as its second source). async function library(name: string): Promise { const dir = path.join(TMP, name); mkdirSync(dir, { recursive: true }); await writeXTrendingPosts(dir, [ post("101", "teapot_news", "one"), post("102", "saucer_fan", "two"), post("103", "teapot_news", "three", "101"), post("201", "spoon_daily", "four"), post("202", "saucer_fan", "five"), ]); await recordXTrendingRead(dir, { readId: READ("A"), at: "2026-11-17T10:00:00.000Z", ref: REF(1), topic: "Kettles", postIds: ["101", "102", "103"], added: 3, threads: { "101": "101", "103": "101", "102": "102" } }); await recordXTrendingRead(dir, { readId: READ("B"), at: "2026-11-17T11:00:00.000Z", ref: REF(2), topic: "Saucers", postIds: ["201", "202"], added: 2 }); await recordXTrendingRead(dir, { readId: READ("C"), at: "2026-11-17T12:00:00.000Z", ref: REF(1), topic: "Saucers", postIds: ["101"], added: 0 }); return dir; } const watchOn = async (dir: string, topic: string, by: "agent" | "operator", intervalMinutes: number) => { const r = await setXTrendingWatch(dir, { topics: await readXTrendingTopics(dir), topic, on: true, intervalMinutes, hours: 48, by, maxTopics: 4, now: NOW }); assert.equal(r.ok, true); }; test("rename: the title changes, the id stays, and who renamed is recorded; a name another topic answers to is refused", async () => { const dir = await library("rename"); await watchOn(dir, "kettles", "operator", 30); const r = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: " Teapots of the week ", by: "agent", now: NOW }); assert.ok(r.ok); assert.deepEqual([r.topic, r.title, r.was, r.changed], ["kettles", "Teapots of the week", "Kettles", true]); assert.match(r.sentence, /Its id stays kettles/); const topics = await readXTrendingTopics(dir); assert.deepEqual(topics.map((t) => [t.id, t.title]), [["kettles", "Teapots of the week"], ["saucers", "Saucers"]]); assert.deepEqual(topics[0].organised, { what: "rename", by: "agent", at: "2026-11-18T10:00:00.000Z" }); assert.ok((await readXTrendingWatches(dir)).kettles, "its watch is still its own"); assert.equal((await readXTrendingMembership(dir))["102"].topic, "kettles"); const same = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "Teapots of the week", by: "agent" }); assert.ok(same.ok && !same.changed); for (const taken of ["saucers", "SAUCERS", "Saucers"]) { const no = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: taken, by: "operator" }); assert.ok(!no.ok && /already answers to/.test(no.error), taken); } const missing = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "spoons", title: "x", by: "operator" }); assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); const long = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "x".repeat(121), by: "operator" }); assert.ok(!long.ok && /at most 120/.test(long.error)); const who = await renameXTrendingTopic(dir, { readInFlight: IDLE, topic: "kettles", title: "x", by: "somebody" as never }); assert.ok(!who.ok && /"by" is/.test(who.error)); }); test("move: posts by id or a whole thread change topic; judgements stay; a later read does not move them back", async () => { const dir = await library("move"); await judgeXTrending(dir, { by: "operator", set: [{ id: "102", state: "keep", note: "a note" }, { thread: "101", state: "drop" }] }); const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); const r = await moveXTrendingPosts(dir, { to: "saucers", ids: ["102", "999", "201"], by: "agent", now: NOW }); assert.ok(r.ok); assert.deepEqual(r.moved, ["102"]); assert.deepEqual(r.skipped, [{ id: "999", reason: "not in this library" }, { id: "201", reason: 'already in "Saucers"' }]); let members = await readXTrendingMembership(dir); assert.equal(members["102"].topic, "saucers"); assert.deepEqual(members["102"].moved, { from: "kettles", by: "agent", at: "2026-11-18T10:00:00.000Z" }); const t = await moveXTrendingPosts(dir, { to: "Saucers", thread: "101", by: "operator", now: NOW }); assert.ok(t.ok); assert.deepEqual([...t.moved].sort(), ["101", "103"]); assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore, "judgements are keyed by post and thread: untouched"); const listing = await listXTrending(dir, { topic: "saucers", filter: { state: "drop" }, ids: true }); assert.deepEqual([...(listing.ids ?? [])].sort(), ["101", "103"], "the thread's judgement travels with its posts"); // The page is read again into its first topic: a placed post keeps its place. await recordXTrendingRead(dir, { readId: READ("D"), at: "2026-11-18T11:00:00.000Z", ref: REF(1), topic: "kettles", postIds: ["101", "102", "103"], added: 0 }); members = await readXTrendingMembership(dir); assert.deepEqual(["101", "102", "103"].map((id) => members[id].topic), ["saucers", "saucers", "saucers"]); for (const [ask, re] of [ [{ to: "saucers", by: "agent" }, /one of them/], [{ to: "saucers", ids: ["101"], thread: "101", by: "agent" }, /one of them/], [{ to: "saucers", ids: ["x"], by: "agent" }, /list of post ids/], [{ to: "saucers", thread: "777", by: "agent" }, /no thread "777"/], [{ to: "spoons", ids: ["101"], by: "agent" }, /no topic "spoons".*"create": true/], [{ to: "", ids: ["101"], by: "agent" }, /"to" is/], ] as const) { const no = await moveXTrendingPosts(dir, ask as never); assert.ok(!no.ok && re.test(no.error), JSON.stringify(ask)); } }); test("move with create: a new topic with no page, made only when a post went into it", async () => { const dir = await library("move-create"); const none = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["999"], create: true, by: "operator" }); assert.ok(none.ok && none.moved.length === 0 && !none.to.created); assert.equal((await readXTrendingTopics(dir)).length, 2); const r = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator" }); assert.ok(r.ok && r.to.created); assert.deepEqual(r.to, { id: "spoons", title: "Spoons", created: true }); const topics = await readXTrendingTopics(dir); assert.deepEqual(topics.map((t) => [t.id, t.sources.length]), [["kettles", 1], ["saucers", 2], ["spoons", 0]]); }); test("merge is the operator's, and waits for a read", async () => { const dir = await library("merge-refused"); const before = readFileSync(path.join(dir, "trending", "topics.json"), "utf8"); const agent = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "agent", readInFlight: () => false }); assert.deepEqual(agent, { ok: false, error: MERGE_IS_THE_OPERATORS }); const busy = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => true }); assert.deepEqual(busy, { ok: false, error: MERGE_WAITS_FOR_READS }); // A read queued between the first look and the lock refuses it too. let asked = 0; const late = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => ++asked > 1 }); assert.deepEqual(late, { ok: false, error: MERGE_WAITS_FOR_READS }); const self = await mergeXTrendingTopics(dir, { into: "kettles", from: ["Kettles"], by: "operator", readInFlight: () => false }); assert.ok(!self.ok && /not merged into itself/.test(self.error)); const missing = await mergeXTrendingTopics(dir, { into: "kettles", from: ["spoons"], by: "operator", readInFlight: () => false }); assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); assert.equal(readFileSync(path.join(dir, "trending", "topics.json"), "utf8"), before); }); test("merge: posts, pages and reads carried; the same page in both becomes one; judgements untouched; the old id means the target", async () => { const dir = await library("merge"); await judgeXTrending(dir, { by: "operator", set: [{ id: "201", state: "keep" }, { thread: "101", state: "later" }] }); const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); assert.ok(r.ok); assert.deepEqual(r.into, { id: "kettles", title: "Kettles" }); assert.deepEqual(r.merged, [{ id: "saucers", title: "Saucers", posts: 2, pages: 2 }]); assert.equal(r.posts, 2); assert.equal(r.pages, 2); assert.match(r.sentence, /"Saucers" is now part of "Kettles": 2 posts moved, 2 trending pages in the topic\. The judgements are untouched\. This cannot be undone\./); const topics = await readXTrendingTopics(dir); assert.equal(topics.length, 1); assert.deepEqual(topics[0].aliases, ["saucers"]); assert.deepEqual(topics[0].organised, { what: "merge", by: "operator", at: "2026-11-18T10:00:00.000Z" }); assert.deepEqual( topics[0].sources.map((s) => [s.trendId, s.reads.map((x) => x.id)]), [[REF(1).trendId, [READ("A"), READ("C")]], [REF(2).trendId, [READ("B")]]], ); const members = await readXTrendingMembership(dir); assert.ok(Object.values(members).every((m) => m.topic === "kettles")); assert.deepEqual(members["201"].moved, { from: "saucers", by: "operator", at: "2026-11-18T10:00:00.000Z" }); assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore); // An ask that still names the merged topic: the listing and a read. const listing = await listXTrending(dir, { topic: "saucers", ids: true }); assert.equal(listing.ids?.length, 5); assert.deepEqual(listing.topics.map((t) => [t.id, t.posts, t.aliases]), [["kettles", 5, ["saucers"]]]); await writeXTrendingPosts(dir, [post("301", "spoon_daily", "six")]); const read = await recordXTrendingRead(dir, { readId: READ("E"), at: "2026-11-18T12:00:00.000Z", ref: REF(2), topic: "saucers", postIds: ["301"], added: 1 }); assert.deepEqual(read.topic, { id: "kettles", title: "Kettles", created: false }); assert.equal((await readXTrendingTopics(dir)).length, 1, "a merged-away id never makes a topic again"); // Nor is a new topic ever given that id. const fresh = await recordXTrendingRead(dir, { readId: READ("F"), at: "2026-11-18T13:00:00.000Z", ref: REF(3), topic: "Saucers!", postIds: [], added: 0 }); assert.deepEqual(fresh.topic, { id: "saucers-2", title: "Saucers!", created: true }); }); test("merge, two live watches: the target's stands with its own terms, the other is gone, and the sentence says so", async () => { const dir = await library("merge-watches"); await watchOn(dir, "kettles", "agent", 45); await watchOn(dir, "saucers", "operator", 20); const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); assert.ok(r.ok); const watches = await readXTrendingWatches(dir); assert.deepEqual(Object.keys(watches), ["kettles"]); assert.deepEqual([watches.kettles.intervalMinutes, watches.kettles.by, watches.kettles.nextSource], [45, "agent", 0]); assert.deepEqual(r.watch.dropped, ["saucers"]); assert.equal(r.watch.stands?.from, "kettles"); assert.match(r.sentence, /The watch of "Kettles" stands with its own terms and reads its 2 pages in turn: Watched every 45 min/); assert.match(r.sentence, /The watch of "Saucers" is gone: one topic has one watch\./); }); test("merge, only the merged topic watched: its watch becomes the target's; none watched: no watch file is made", async () => { const dir = await library("merge-watch-moves"); await watchOn(dir, "saucers", "operator", 20); const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); assert.ok(r.ok); const watches = await readXTrendingWatches(dir); assert.deepEqual(Object.keys(watches), ["kettles"]); assert.equal(watches.kettles.intervalMinutes, 20); assert.match(r.sentence, /The watch of "Saucers" is now the watch of "Kettles" and reads its 2 pages in turn/); const plain = await library("merge-no-watch"); const p = await mergeXTrendingTopics(plain, { into: "saucers", from: ["kettles"], by: "operator", readInFlight: () => false, now: NOW }); assert.ok(p.ok && !p.watch.stands && p.watch.dropped.length === 0); assert.deepEqual(await readXTrendingWatches(plain), {}); assert.doesNotMatch(p.sentence, /watch/i); }); // ── review 1 ─────────────────────────────────────────────────────────────── test("S9: a rename waits for a read, as a merge does: asked before the lock and inside it; nothing is written", async () => { const dir = await library("rename-waits"); const before = readFileSync(path.join(dir, "trending", "topics.json"), "utf8"); assert.deepEqual(await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: () => true }), { ok: false, error: RENAME_WAITS_FOR_READS }); let asked = 0; assert.deepEqual(await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: () => ++asked > 1 }), { ok: false, error: RENAME_WAITS_FOR_READS }); assert.equal(readFileSync(path.join(dir, "trending", "topics.json"), "utf8"), before); // Why: a read asked for by the old NAME after a rename would make a topic of that name. assert.ok((await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots", by: "operator", readInFlight: IDLE })).ok); const read = await recordXTrendingRead(dir, { readId: READ("H"), at: "2026-11-18T15:00:00.000Z", ref: REF(5), topic: "Kettles", postIds: [], added: 0 }); assert.equal(read.topic.created, true, "which is what the refusal prevents while a read is in flight"); }); test("S6: a move into a new topic writes the topic BEFORE the posts: cut between the two, no post names a topic that does not exist", async () => { const dir = await library("move-crash"); await assert.rejects( moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator", now: NOW, betweenWrites: () => { throw new Error("cut here"); } }), /cut here/, ); let topics = await readXTrendingTopics(dir); let members = await readXTrendingMembership(dir); assert.deepEqual(topics.map((t) => t.id), ["kettles", "saucers", "spoons"], "the topic is on disk"); assert.equal(members["201"].topic, "saucers", "the post was not moved"); for (const m of Object.values(members)) assert.ok(topics.some((t) => t.id === m.topic), `every post's topic exists (${m.topic})`); // The same move again completes it; no second topic is made. const again = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator", now: NOW }); assert.ok(again.ok && again.moved.length === 1 && again.to.id === "spoons" && !again.to.created); topics = await readXTrendingTopics(dir); members = await readXTrendingMembership(dir); assert.deepEqual(topics.map((t) => t.id), ["kettles", "saucers", "spoons"]); assert.equal(members["201"].topic, "spoons"); }); test("nit: a thread is moved by the key the listing shows, the one kept in the membership record", async () => { const dir = await library("move-thread-key"); // 102 was PLACED in thread 102 (its record says so); nothing in its post names a thread. const listing = await listXTrending(dir, { topic: "kettles" }); const shown: Record = Object.fromEntries(listing.posts.map((p) => [p.id, p.thread])); const expected: Record = { "101": "101", "102": "102", "103": "101" }; assert.deepEqual(shown, expected); for (const thread of ["101", "102"]) { const twin = await library(`move-thread-key-${thread}`); const r = await moveXTrendingPosts(twin, { to: "saucers", thread, by: "agent" }); assert.ok(r.ok); // 101 itself is in "kettles" (a post already placed keeps its topic). assert.deepEqual([...r.moved, ...r.skipped.map((x) => x.id)].sort(), Object.keys(shown).filter((id) => shown[id] === thread).sort()); } }); test("S7: a merge and what was published: the merged topic's channel becomes the target's when it has none; with one of its own, the other is left and named", async () => { const rec = (slug: string, ids: string[]) => ({ slug, firstAt: "2026-11-18T09:00:00.000Z", lastAt: "2026-11-18T09:00:00.000Z", posts: Object.fromEntries(ids.map((id) => [id, "2026-11-18T09:00:00.000Z"])), identity: { ino: 7, birthtimeMs: 9 } }); const put = (dir: string, all: Record>) => mutateXTrendingPublished(dir, (topics) => { Object.assign(topics, all); return { write: true, result: undefined }; }); // The target has none: the merged topic's record is carried, whole. const carried = await library("merge-published-carried"); await put(carried, { saucers: rec("saucers-chan", ["201"]) }); const a = await mergeXTrendingTopics(carried, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); assert.ok(a.ok); assert.deepEqual(a.published, { carried: "saucers-chan", left: [] }); assert.match(a.sentence, /The channel "saucers-chan", which a merged topic was published into, is now the channel of "Kettles": its next publish adds to it\./); assert.deepEqual(await readXTrendingPublished(carried), { kettles: rec("saucers-chan", ["201"]) }); // Both have one: the target's stays; the other is left, named, and no record names it. const both = await library("merge-published-both"); await put(both, { kettles: rec("kettles-chan", ["101"]), saucers: rec("saucers-chan", ["201"]) }); const b = await mergeXTrendingTopics(both, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); assert.ok(b.ok); assert.deepEqual(b.published, { left: ["saucers-chan"] }); assert.match(b.sentence, /The channel "saucers-chan", published from a merged topic, stays as it is and will not be added to again: "Kettles" has a channel of its own\./); assert.deepEqual(await readXTrendingPublished(both), { kettles: rec("kettles-chan", ["101"]) }); // Neither: no record file is made, and the sentence says nothing of channels. const none = await library("merge-published-none"); const c = await mergeXTrendingTopics(none, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: IDLE, now: NOW }); assert.ok(c.ok); assert.deepEqual(c.published, { left: [] }); assert.doesNotMatch(c.sentence, /channel/); assert.deepEqual(await readXTrendingPublished(none), {}); });