// Publishing a topic of an X trending library (lane x-trending-publish): the // operator's kept posts and nothing else become an ordinary channel that // names nothing of the library; files are copies with inodes of their own; // "made by this publish" is the library's record and the channel's content. // A temp corpus; no network, no editor. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/publishXTrending.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { mkdtemp } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { Post } from "../lib/posts"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-publish-")); process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const { getPaths } = await import("../lib/paths"); const { readAllPosts, readPostAvailability, writePostAvailability, writePosts } = await import("../lib/posts-server"); const { isSourcelessPostsChannel } = await import("../lib/sourcelessPosts"); const { judgeXTrending } = await import("../lib/xTrending/judgements"); const { adoptXTrendingMedia } = await import("../lib/xTrending/mediaStore"); const { renameXTrendingTopic, moveXTrendingPosts } = await import("../lib/xTrending/organise"); const { readXTrendingPublished } = await import("../lib/xTrending/published"); const { purgeXTrendingDropped } = await import("../lib/xTrending/purge"); const { recordXTrendingRead, trendingDir, writeXTrendingPosts } = await import("../lib/xTrending/store"); const { createChannel, deleteChannel, readChannelConfig } = await import("./channels"); const { writeSite } = await import("../lib/site"); const { mutateXTrendingPublished } = await import("../lib/xTrending/published"); const { NOT_THIS_PUBLISHS_CHANNEL, PUBLISH_IS_THE_OPERATORS, PUBLISH_SET_CHANGED, PUBLISH_WAITS, PUBLISHED_POST_FIELDS, captureFileNames, publishedCaptureOf, publishedPostOf, publishXTrendingTopic, } = await import("./publishXTrending"); const paths = getPaths(); const IDLE = () => false; const derive = (title: string) => title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); 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" }; const MARK = { note: "judgenotemarkq4z", stray: "straybytesmarkw8k", owed: "owedtextmarkv3n", agentPost: "agentkeptwordsmarkb6t", dropped: "droppedwordsmarkc2m", later: "laterwordsmarkd9p", undecided: "undecidedwordsmarkf5r", otherTopic: "othertopicwordsmarkg1s" }; function post(lib: string, id: string, text: string, extra: Partial = {}): Post { return { id, slug: `${lib}/${id}`, channelSlug: lib, author: "teapot_news", authorName: "Teapot News", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/teapot_news/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra }; } const sha = (text: string) => createHash("sha256").update(text).digest("hex"); function capture(libRoot: string, id: string, files: Record, record: Record = {}) { const dir = path.join(libRoot, "trending", "posts-media", id); mkdirSync(dir, { recursive: true }); for (const [name, bytes] of Object.entries(files)) writeFileSync(path.join(dir, name), bytes); const media = Object.keys(files).filter((n) => /_\d+\.(jpg|mp4)$/.test(n)); writeFileSync( path.join(dir, "capture.json"), JSON.stringify({ version: 1, id, url: `https://x.com/i/status/${id}`, capturedAt: "2026-11-18T10:05:00.000Z", state: "captured", // As a capture job leaves it: each file's own size and digest. ...(files["shot.png"] ? { shot: { name: "shot.png", bytes: files["shot.png"].length, sha256: sha(files["shot.png"]) } } : {}), mediaState: "ok", media: media.map((name) => ({ name, bytes: files[name].length, sha256: sha(files[name]), url: `https://pbs.twimg.com/media/${name}` })), ...record, }), ); return media; } // A library "" with the topic "Kettle Festival": // 801 kept by the operator (a note), captured (a shot, a picture, a stray // file its record does not name), X said deleted, gone from the page // 802 kept by an AGENT 803 dropped by the operator, captured // 804 later 805 undecided // 806 a THREAD kept by the operator, captured, the same picture as 801 // 807 its reply: kept through the thread, no capture yet // and the topic "Cups": 808 kept by the operator. async function library(lib: string): Promise { const libRoot = path.join(paths.channelsDir, lib); await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); await writeXTrendingPosts(libRoot, [ post(lib, "801", "first words", { engagement: { likes: 3 }, links: ["https://example.org/a"] }), post(lib, "802", MARK.agentPost), post(lib, "803", MARK.dropped), post(lib, "804", MARK.later), post(lib, "805", MARK.undecided), post(lib, "806", "thread root words"), post(lib, "807", "thread reply words", { isReply: true, threadId: "806", replyTo: { platform: "twitter", id: "806" } }), post(lib, "808", MARK.otherTopic), ]); await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettle Festival", postIds: ["801", "802", "803", "804", "805", "806", "807"], added: 7, threads: { "807": "806" } }); await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["808"], added: 1 }); // A complete read that no longer shows 801: gone from the page. await recordXTrendingRead(libRoot, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF, postIds: ["802", "803", "804", "805", "806", "807"], added: 0, complete: true }); for (const name of capture(libRoot, "801", { "shot.png": "SHOT-801", "801_1.jpg": "PICTURE-SHARED", "stray.bin": MARK.stray }, { mediaOwed: "kept", error: `media ${MARK.owed}: owed until the post is kept`, threadError: `thread ${MARK.owed}`, context: { readAt: "2026-11-18T10:05:00.000Z", quoted: { text: "a quoted post", media: [] } }, })) await adoptXTrendingMedia(libRoot, { postId: "801", name }); for (const name of capture(libRoot, "803", { "803_1.jpg": "PICTURE-DROPPED" })) await adoptXTrendingMedia(libRoot, { postId: "803", name }); for (const name of capture(libRoot, "806", { "806_1.jpg": "PICTURE-SHARED" })) await adoptXTrendingMedia(libRoot, { postId: "806", name }); await judgeXTrending(libRoot, { by: "agent", set: [{ id: "802", state: "keep" }] }); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "801", state: "keep", note: `why ${MARK.note}` }, { id: "803", state: "drop" }, { id: "804", state: "later" }, { thread: "806", state: "keep" }, { id: "808", state: "keep" }], }); await writePostAvailability(trendingDir(libRoot), { "801": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" }, "803": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" }, }); return libRoot; } function walk(dir: string): string[] { const out: string[] = []; for (const e of readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) out.push(...walk(p)); else out.push(p); } return out.sort(); } const snapshot = (dir: string) => walk(dir).map((f) => `${path.relative(dir, f)}:${readFileSync(f).toString("latin1")}`); async function publish(lib: string, o: { topic?: string; channel?: string; busy?: () => boolean } = {}) { const ask = { slug: lib, topic: o.topic ?? "kettle-festival", deriveSlug: derive, busy: o.busy ?? IDLE, now: Date.parse("2026-11-18T12:00:00.000Z"), ...(o.channel ? { channel: o.channel } : {}) }; const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); if (!dry.ok) return { dry, done: dry }; const done = await publishXTrendingTopic(paths, { ...ask, dryRun: false, confirm: dry.result.confirm, by: "operator" }); return { dry, done }; } test("the allowlists: a post's unknown field, its library slug and its index-time fields are not copied; a capture's owed and error text neither", () => { const stored = { ...post("zzlib", "801", "words", { lang: "en", quoted: { platform: "twitter", id: "5", author: "saucer_fan" } }), secretField: "x", forum: { host: "h", threadId: "t" }, isDeleted: true, availability: "deleted" } as unknown as Post; const out = publishedPostOf(stored, "kettles")!; assert.deepEqual(Object.keys(out).sort(), ["author", "authorName", "channelSlug", "createdAt", "id", "isReply", "isRepost", "lang", "links", "platform", "quoted", "slug", "text", "uploadDate", "url"]); assert.deepEqual([out.slug, out.channelSlug], ["kettles/801", "kettles"]); assert.doesNotMatch(JSON.stringify(out), /zzlib|secretField/); assert.ok(!PUBLISHED_POST_FIELDS.includes("slug") && !PUBLISHED_POST_FIELDS.includes("channelSlug")); const record = { version: 1, id: "801", url: "u", capturedAt: "t", state: "captured", mediaState: "error", mediaOwed: "kept", error: "e", threadError: "te", unknown: "u", shot: { name: "shot.png", bytes: 1, sha256: "a" }, media: [{ name: "801_1.jpg", bytes: 1, sha256: "b", url: "https://pbs.twimg.com/media/x.jpg" }, { name: "../evil", bytes: 1, sha256: "c" }, { name: "801_2.jpg", bytes: 1, sha256: "d" }], article: { articleId: "9", url: "au", capturedAt: "t", state: "error", blocks: 0, extraction: "by-magic", files: [{ name: "article.json", bytes: 1, sha256: "e" }], error: "ae" }, } as never; assert.deepEqual(captureFileNames(record), ["shot.png", "801_1.jpg", "801_2.jpg", "article.json"]); const there: Record = { "shot.png": { name: "shot.png", bytes: 7, sha256: "S" }, "801_1.jpg": { name: "801_1.jpg", bytes: 9, sha256: "M" } }; const built = publishedCaptureOf(record, (name) => there[name]); assert.deepEqual(built, { version: 1, id: "801", url: "u", capturedAt: "t", state: "captured", shot: { name: "shot.png", bytes: 7, sha256: "S" }, mediaState: "error", media: [{ name: "801_1.jpg", bytes: 9, sha256: "M", url: "https://pbs.twimg.com/media/x.jpg" }], article: { articleId: "9", url: "au", capturedAt: "t", state: "error", blocks: 0, files: [] }, }); // FIELD BY FIELD (review 1): the context's two posts, a thread shot's redaction and an article's // extraction are rebuilt from named fields; a key nobody named is not copied. const rich = { version: 1, id: "802", url: "u", capturedAt: "t", state: "captured", mediaState: "none", media: [], thread: { name: "shot-thread.png", bytes: 1, sha256: "t", parentId: "700", parentHandle: "saucer_fan", parentVerified: true, parentBadge: "gold", parentFrom: "above", libraryNote: "x", redaction: { applied: true, reason: "private", boxes: [{ what: "avatar", box: { x: 1, y: 2, width: 3, height: 4, z: 9 }, why: "x" }, { what: "everything", box: {} }], secret: "x" }, }, article: { articleId: "9", url: "au", capturedAt: "t", state: "captured", blocks: 2, extraction: "structured", files: [], libraryNote: "x" }, context: { readAt: "r", topic: "kettles", quoted: { id: "5", url: "qu", handle: "h", author: "A", verified: true, badge: "blue", date: "d", text: "quoted", media: [{ kind: "image", url: "mu", note: "x" }, { kind: "audio", url: "no" }], judgement: "keep" }, parent: { text: "parent", media: [], from: "above", note: "x" }, }, } as never; const richBuilt = publishedCaptureOf(rich, (name) => (name === "shot-thread.png" ? { name, bytes: 5, sha256: "T" } : undefined)); assert.deepEqual(richBuilt, { version: 1, id: "802", url: "u", capturedAt: "t", state: "captured", mediaState: "none", media: [], article: { articleId: "9", url: "au", capturedAt: "t", state: "captured", blocks: 2, extraction: "structured", files: [] }, thread: { name: "shot-thread.png", bytes: 5, sha256: "T", parentId: "700", parentHandle: "saucer_fan", parentVerified: true, parentBadge: "gold", parentFrom: "above", redaction: { applied: true, reason: "private", boxes: [{ what: "avatar", box: { x: 1, y: 2, width: 3, height: 4 } }] }, }, context: { readAt: "r", quoted: { id: "5", url: "qu", handle: "h", author: "A", verified: true, badge: "blue", date: "d", text: "quoted", media: [{ kind: "image", url: "mu" }] }, parent: { text: "parent", media: [], from: "above" }, }, } as never); assert.doesNotMatch(JSON.stringify(richBuilt), /libraryNote|secret|judgement|kettles|"note"|"why"|"z"/); // A redaction nobody can read (no known reason) publishes no thread shot's record at all. const noReason = publishedCaptureOf({ ...(rich as object), thread: { name: "shot-thread.png", bytes: 1, sha256: "t", parentId: "7", parentVerified: false, parentFrom: "reply-to", redaction: { applied: true, reason: "because" } } } as never, (name) => ({ name, bytes: 1, sha256: "T" })); assert.equal(noReason.thread, undefined); }); test("a dry run writes nothing and says exactly what would be written; the publish is the operator's, in two steps, and waits for a read or a capture", async () => { const lib = "zzlibrarymarkq7"; const libRoot = await library(lib); const before = snapshot(libRoot); const ask = { slug: lib, topic: "Kettle Festival", deriveSlug: derive, busy: IDLE }; const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); assert.ok(dry.ok); const r = dry.result; assert.deepEqual( { channel: r.channel, creates: r.creates, kept: r.kept, posts: r.posts, ids: r.ids, already: r.already, files: r.files, bytes: r.bytes, textOnly: r.textOnly, noLongerKept: r.noLongerKept }, { channel: "kettle-festival", creates: true, kept: 3, posts: 3, ids: ["801", "806", "807"], already: 0, files: 3, bytes: "SHOT-801".length + 2 * "PICTURE-SHARED".length, textOnly: ["807"], noLongerKept: [] }, ); assert.match(r.sentence, /^Publishing "Kettle Festival" would make the channel "kettle-festival", on no site, writing 3 posts and 3 files \(36 B\); 0 of the 3 kept posts are there already\. 1 post has no capture yet and is published as its words alone: a later publish adds the files\. The files are copies: the library keeps its own\.$/); assert.deepEqual(readdirSync(paths.channelsDir), [lib], "no channel was made"); assert.deepEqual(snapshot(libRoot), before, "a dry run writes nothing in the library either"); const busyDry = await publishXTrendingTopic(paths, { ...ask, dryRun: true, busy: () => true }); assert.ok(busyDry.ok && busyDry.result.inFlight === true && /the publish waits for it/.test(busyDry.result.sentence)); for (const by of ["agent", undefined]) { assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, confirm: r.confirm, ...(by ? { by } : {}) }), { ok: false, error: PUBLISH_IS_THE_OPERATORS }); } const noConfirm = await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator" }); assert.ok(!noConfirm.ok && /two steps/.test(noConfirm.error)); assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: "0".repeat(24) }), { ok: false, error: PUBLISH_SET_CHANGED }); assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm, busy: () => true }), { ok: false, error: PUBLISH_WAITS }); // Queued between the first look and the lock. let asked = 0; assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm, busy: () => ++asked > 1 }), { ok: false, error: PUBLISH_WAITS }); // The set changed after the count: a post moved out of the topic. await moveXTrendingPosts(libRoot, { to: "cups", ids: ["807"], by: "agent" }); assert.deepEqual(await publishXTrendingTopic(paths, { ...ask, dryRun: false, by: "operator", confirm: r.confirm }), { ok: false, error: PUBLISH_SET_CHANGED }); assert.deepEqual(readdirSync(paths.channelsDir), [lib], "every refusal wrote nothing"); const none = await publishXTrendingTopic(paths, { ...ask, topic: "spoons", dryRun: true }); assert.ok(!none.ok && /has no topic "spoons"/.test(none.error)); const notLib = await publishXTrendingTopic(paths, { ...ask, slug: "nope", dryRun: true }); assert.ok(!notLib.ok && /No such channel/.test(notLib.error)); const itself = await publishXTrendingTopic(paths, { ...ask, channel: lib, dryRun: true }); assert.ok(!itself.ok && /the library itself/.test(itself.error)); const badSlug = await publishXTrendingTopic(paths, { ...ask, channel: "../x", dryRun: true }); assert.ok(!badSlug.ok && /not a valid channel slug/.test(badSlug.error)); await deleteChannel(paths, lib); }); test("THE PIN: the published channel holds the operator's keeps and nothing that names the library, a judgement, a note, a read, a watch or a gone mark; its files are copies", async () => { const lib = "zzlibrarymarkq7"; const libRoot = await library(lib); const libBefore = snapshot(libRoot).filter((l) => !l.startsWith("trending/published.json")); const { done } = await publish(lib); assert.ok(done.ok, JSON.stringify(done)); assert.match(done.result.sentence, /^Publishing "Kettle Festival" made the channel "kettle-festival", on no site, and wrote 3 posts and 3 files/); assert.match(done.result.sentence, /Adding the channel to a site is a separate step\.$/); const chan = path.join(paths.channelsDir, "kettle-festival"); // An ordinary channel: its config is four plain keys. assert.deepEqual(JSON.parse(readFileSync(path.join(chan, "config.json"), "utf8")), { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" }); assert.equal(isSourcelessPostsChannel(await readChannelConfig(paths, "kettle-festival")), true); // On no site: nothing but the two channels exists in the corpus. assert.deepEqual(readdirSync(ROOT).sort(), ["channels"]); // EXACTLY the operator's keeps: not the agent's keep, the drop, the later, // the undecided, nor a keep of another topic. const posts = await readAllPosts(chan); assert.deepEqual(posts.map((p) => p.id).sort(), ["801", "806", "807"]); for (const p of posts) assert.deepEqual([p.slug, p.channelSlug], [`kettle-festival/${p.id}`, "kettle-festival"]); assert.deepEqual(posts.find((p) => p.id === "801")?.engagement, { likes: 3 }); // The files: what the capture records name, and not the stray one. const files = walk(chan).map((f) => path.relative(chan, f)); assert.deepEqual(files, [ "config.json", "posts-archive", "posts-availability.json", "posts-media/801/801_1.jpg", "posts-media/801/capture.json", "posts-media/801/shot.png", "posts-media/806/806_1.jpg", "posts-media/806/capture.json", "posts/2026-11.jsonl", ]); // NOTHING OF THE LIBRARY, in any file's bytes or name. const forbidden = [lib, "trending", "xTrending", ...Object.values(MARK), READ_A, READ_B, READ_C, REF.trendId, "judg", "agent", "operator", "gone", "mediaOwed", "owed", "threadError", '"error"', "watch", "membership", "published.json", "media-store", "media-index", "kept", "keep", "topic"]; for (const f of walk(chan)) { const hay = `${path.relative(chan, f)}\n${readFileSync(f).toString("latin1")}`; for (const word of forbidden) assert.ok(!hay.includes(word), `${path.relative(chan, f)} carries "${word}"`); } // Every string of every published post record, too (ruling 10). for (const line of readFileSync(path.join(chan, "posts", "2026-11.jsonl"), "utf8").trim().split("\n")) assert.doesNotMatch(line, new RegExp(lib)); // The capture record: an ordinary one, describing the copies. const cap = JSON.parse(readFileSync(path.join(chan, "posts-media", "801", "capture.json"), "utf8")); assert.deepEqual(Object.keys(cap).sort(), ["capturedAt", "context", "id", "media", "mediaState", "shot", "state", "url", "version"]); assert.equal(cap.media[0].bytes, "PICTURE-SHARED".length); assert.match(cap.media[0].sha256, /^[0-9a-f]{64}$/); assert.notEqual(cap.media[0].sha256, "0".repeat(64)); // What X said of the published posts, and of no other. assert.deepEqual(await readPostAvailability(chan), { "801": { availability: "deleted", checkedAt: "2026-11-18T10:05:00.000Z" } }); // COPIES: no published file shares an inode with a library file, and each // has one name only. const libInodes = new Set(walk(libRoot).map((f) => lstatSync(f).ino)); for (const f of walk(chan)) { const st = lstatSync(f); assert.equal(st.nlink, 1, `${f} has one name`); assert.ok(!libInodes.has(st.ino), `${f} is not a library file's inode`); assert.ok(st.isFile() && !st.isSymbolicLink()); } assert.equal(readFileSync(path.join(chan, "posts-media", "806", "806_1.jpg"), "utf8"), "PICTURE-SHARED"); // The library: untouched but for its own record of the publish. assert.deepEqual(snapshot(libRoot).filter((l) => !l.startsWith("trending/published.json")), libBefore); const made = lstatSync(chan); assert.deepEqual(await readXTrendingPublished(libRoot), { "kettle-festival": { slug: "kettle-festival", firstAt: "2026-11-18T12:00:00.000Z", lastAt: "2026-11-18T12:00:00.000Z", posts: { "801": "2026-11-18T12:00:00.000Z", "806": "2026-11-18T12:00:00.000Z", "807": "2026-11-18T12:00:00.000Z" }, // Which directory it made: kept HERE, in the library. Nothing is written into the channel for it. identity: { ino: made.ino, birthtimeMs: made.birthtimeMs }, }, }); }); test("re-publishing adds the newly kept and removes nothing: a post since dropped is reported and stays; a capture that came later is topped up; a renamed topic keeps its channel", async () => { const lib = "zzlibrarymarkq7"; const libRoot = path.join(paths.channelsDir, lib); const chan = path.join(paths.channelsDir, "kettle-festival"); const again = await publishXTrendingTopic(paths, { slug: lib, topic: "kettle-festival", deriveSlug: derive, busy: IDLE, dryRun: true }); assert.ok(again.ok); assert.deepEqual([again.result.creates, again.result.posts, again.result.files, again.result.already], [false, 0, 0, 3]); assert.equal(again.result.sentence, `Nothing to add: the channel "kettle-festival" already holds the 3 posts the operator kept in "Kettle Festival". 1 post has no capture yet and is published as its words alone: a later publish adds the files.`); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "805", state: "keep" }, { id: "801", state: "drop" }] }); for (const name of capture(libRoot, "807", { "shot.png": "SHOT-807", "807_1.jpg": "PICTURE-807" })) await adoptXTrendingMedia(libRoot, { postId: "807", name }); const renamed = await renameXTrendingTopic(libRoot, { readInFlight: IDLE, topic: "kettle-festival", title: "Teapots", by: "operator" }); assert.ok(renamed.ok); const other = await publishXTrendingTopic(paths, { slug: lib, topic: "kettle-festival", channel: "teapots", deriveSlug: derive, busy: IDLE, dryRun: true }); assert.ok(!other.ok && /a topic has one channel, fixed at its first publish/.test(other.error)); const before801 = snapshot(path.join(chan, "posts-media", "801")); const { dry, done } = await publish(lib); assert.ok(dry.ok && done.ok, JSON.stringify(done)); assert.deepEqual( [done.result.channel, done.result.creates, done.result.ids, done.result.already, done.result.files, done.result.textOnly, done.result.noLongerKept], ["kettle-festival", false, ["805"], 2, 2, ["805"], ["801"]], ); assert.match(done.result.sentence, /1 post published before is no longer kept: it stays in the channel \(a publish removes nothing\)\./); assert.deepEqual((await readAllPosts(chan)).map((p) => p.id).sort(), ["801", "805", "806", "807"]); assert.deepEqual(snapshot(path.join(chan, "posts-media", "801")), before801, "the dropped post's files stay as they were"); assert.equal(readFileSync(path.join(chan, "posts-media", "807", "807_1.jpg"), "utf8"), "PICTURE-807"); assert.equal(JSON.parse(readFileSync(path.join(chan, "config.json"), "utf8")).name, "Kettle Festival", "the channel's own name is its own"); }); test("a purge of the library after a publish frees exactly what it would have freed, and the channel's copies still read; deleting either leaves the other whole", async () => { const lib = "zzlibrarymarkq7"; const libRoot = path.join(paths.channelsDir, lib); const chan = path.join(paths.channelsDir, "kettle-festival"); // The same library, never published. const twinRoot = await library("zztwinlibrary"); await judgeXTrending(twinRoot, { by: "operator", set: [{ id: "805", state: "keep" }, { id: "801", state: "drop" }] }); for (const name of capture(twinRoot, "807", { "shot.png": "SHOT-807", "807_1.jpg": "PICTURE-807" })) await adoptXTrendingMedia(twinRoot, { postId: "807", name }); await renameXTrendingTopic(twinRoot, { readInFlight: IDLE, topic: "kettle-festival", title: "Teapots", by: "operator" }); const purge = async (root: string, slug: string) => { const dry = await purgeXTrendingDropped(root, { slug, dryRun: true, captureInFlight: IDLE }); assert.ok(dry.ok); const done = await purgeXTrendingDropped(root, { slug, dryRun: false, confirm: dry.result.confirm, captureInFlight: IDLE }); assert.ok(done.ok); const { posts, files, bytes, blobsFreed, blobsKept } = done.result; return { posts, files, bytes, blobsFreed, blobsKept }; }; const chanBefore = snapshot(chan); const published = await purge(libRoot, lib); const never = await purge(twinRoot, "zztwinlibrary"); assert.deepEqual(published, never, "the published copies hold no link to the library's blobs"); assert.equal(published.posts, 2); assert.deepEqual(snapshot(chan), chanBefore, "a purge of the library reaches nothing of the channel"); assert.equal(readFileSync(path.join(chan, "posts-media", "801", "801_1.jpg"), "utf8"), "PICTURE-SHARED"); // Deleting the channel leaves the library whole… const libBefore = snapshot(libRoot); await deleteChannel(paths, "kettle-festival"); assert.deepEqual(snapshot(libRoot), libBefore); // …and its slug, free again, is simply made again with every kept post. const { done } = await publish(lib); assert.ok(done.ok && done.result.creates); assert.deepEqual(done.result.ids, ["805", "806", "807"]); // Deleting the LIBRARY leaves the published channel whole. const chanAfter = snapshot(chan); await deleteChannel(paths, lib); await deleteChannel(paths, "zztwinlibrary"); assert.deepEqual(snapshot(chan), chanAfter); await deleteChannel(paths, "kettle-festival"); }); test("the three-part proof: a slug a stranger holds is refused — never recorded, a source of its own, or posts this topic never published; a renamed channel is left alone", async () => { const lib = "zzlibrarymarkq7"; const libRoot = await library(lib); const ask = { slug: lib, topic: "kettle-festival", deriveSlug: derive, busy: IDLE, dryRun: true }; // 1. A channel of that slug that this library never published into. await createChannel(paths, "kettle-festival", { name: "Somebody's", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/somebody", socialHandle: "somebody" }); const stranger = await publishXTrendingTopic(paths, ask); assert.deepEqual(stranger, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("kettle-festival", "this library has no record of publishing into it") }); // The ask may name another slug. const elsewhere = await publish(lib, { channel: "Kettles-2026" }); assert.ok(elsewhere.done.ok && elsewhere.done.result.channel === "Kettles-2026" && elsewhere.done.result.creates); await deleteChannel(paths, "kettle-festival"); // 2. Deleted, then made again BY HAND with an account: a stranger. await deleteChannel(paths, "Kettles-2026"); await createChannel(paths, "Kettles-2026", { name: "By hand", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/somebody", socialHandle: "somebody" }); const byHand = await publishXTrendingTopic(paths, ask); assert.deepEqual(byHand, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("Kettles-2026", "it is a channel with a source of its own") }); // 3. Of the right shape, holding a post this topic never published. await deleteChannel(paths, "Kettles-2026"); await createChannel(paths, "Kettles-2026", { name: "Look-alike", handling: "transcribe", sourceKind: "social", platform: "twitter" }); await writePosts(path.join(paths.channelsDir, "Kettles-2026"), [post("Kettles-2026", "999", "a stranger's post")]); const lookAlike = await publishXTrendingTopic(paths, ask); assert.deepEqual(lookAlike, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("Kettles-2026", "it holds 1 post this topic never published") }); assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "Kettles-2026"))).map((p) => p.id), ["999"], "nothing was appended to it"); await deleteChannel(paths, "Kettles-2026"); // A RENAMED published channel: its directory moved. The record's slug is // free, so a publish makes that channel again; the renamed one is not // written to. const made = await publish(lib); assert.ok(made.done.ok && made.done.result.creates); renameSync(path.join(paths.channelsDir, "Kettles-2026"), path.join(paths.channelsDir, "renamed-by-the-operator")); const renamedBefore = snapshot(path.join(paths.channelsDir, "renamed-by-the-operator")); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "805", state: "keep" }] }); const after = await publish(lib); assert.ok(after.done.ok && after.done.result.creates && after.done.result.channel === "Kettles-2026"); assert.deepEqual(after.done.result.ids, ["801", "805", "806", "807"]); assert.deepEqual(snapshot(path.join(paths.channelsDir, "renamed-by-the-operator")), renamedBefore); // Nothing kept by the operator: nothing to publish (an agent's keep is not one). await judgeXTrending(libRoot, { by: "operator", set: [{ id: "808", state: "undecided" }] }); await judgeXTrending(libRoot, { by: "agent", set: [{ id: "808", state: "keep" }] }); const empty = await publishXTrendingTopic(paths, { ...ask, topic: "cups" }); assert.ok(!empty.ok && /The operator has kept no post in "Cups"/.test(empty.error)); }); // ── review 1 ─────────────────────────────────────────────────────────────── // A small library for one question each: topic "Kettle Festival", posts by id. async function small(lib: string, ids: string[], threads: Record = {}): Promise { const libRoot = path.join(paths.channelsDir, lib); await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); await writeXTrendingPosts(libRoot, ids.map((id) => post(lib, id, `words ${id}`, threads[id] ? { isReply: true, threadId: threads[id], replyTo: { platform: "twitter", id: threads[id] } } : {}))); await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettle Festival", postIds: ids, added: ids.length, threads }); return libRoot; } const ask = (lib: string, channel: string) => ({ slug: lib, topic: "kettle-festival", deriveSlug: () => channel, busy: IDLE, now: Date.parse("2026-11-18T12:00:00.000Z") }); async function go(lib: string, channel: string) { const dry = await publishXTrendingTopic(paths, { ...ask(lib, channel), dryRun: true }); if (!dry.ok) return dry; return publishXTrendingTopic(paths, { ...ask(lib, channel), dryRun: false, confirm: dry.result.confirm, by: "operator" }); } test("S10: which judgement is in force decides what is published: the operator's entry, own or thread's, outranks an agent's; the operator's own outranks the operator's thread", async () => { // Thread 911: the OPERATOR dropped the thread; an AGENT kept its reply 912 itself. // Thread 921: the OPERATOR kept the thread; the OPERATOR dropped its reply 922 itself; 923 has no entry of its own. const libRoot = await small("zzlibs10", ["911", "912", "921", "922", "923"], { "912": "911", "922": "921", "923": "921" }); await judgeXTrending(libRoot, { by: "agent", set: [{ id: "912", state: "keep" }] }); await judgeXTrending(libRoot, { by: "operator", set: [{ thread: "911", state: "drop" }, { thread: "921", state: "keep" }, { id: "922", state: "drop" }] }); const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs10", "s10-channel"), dryRun: true }); assert.ok(dry.ok); // 921 and 923: the operator's thread keep, with no entry of their own. Not 912 (an agent's own keep under // the operator's thread drop), not 922 (the operator's own drop under the operator's thread keep), not 911. assert.deepEqual(dry.result.ids, ["921", "923"]); const done = await go("zzlibs10", "s10-channel"); assert.ok(done.ok); assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "s10-channel"))).map((p) => p.id).sort(), ["921", "923"]); await deleteChannel(paths, "zzlibs10"); await deleteChannel(paths, "s10-channel"); }); test("S2, S3: the channel must be the very directory this publish made: one made again by hand, even empty and of the same shape, is refused; so is a bare directory of the slug", async () => { const libRoot = await small("zzlibs2", ["931", "932"]); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "931", state: "keep" }] }); const chan = path.join(paths.channelsDir, "s2-channel"); // S3: a directory of that name with no channel in it: a publish makes a channel only where there is nothing. mkdirSync(chan, { recursive: true }); const bare = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); assert.deepEqual(bare, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "a directory of that name is there, with no channel in it") }); rmSync(chan, { recursive: true }); const first = await go("zzlibs2", "s2-channel"); assert.ok(first.ok && first.result.creates); const made = lstatSync(chan); const record = (await readXTrendingPublished(libRoot))["kettle-festival"]; assert.deepEqual(record.identity, { ino: made.ino, birthtimeMs: made.birthtimeMs }); assert.equal(record.pending, undefined); // The channel's own config rewritten (as any edit of it does): still this publish's channel. writeFileSync(path.join(chan, "config.json.tmp"), readFileSync(path.join(chan, "config.json"))); renameSync(path.join(chan, "config.json.tmp"), path.join(chan, "config.json")); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "932", state: "keep" }] }); const second = await go("zzlibs2", "s2-channel"); assert.ok(second.ok && !second.result.creates, JSON.stringify(second)); // DELETED, THEN MADE AGAIN BY HAND: the same slug, the same shape, EMPTY. Not this publish's. await deleteChannel(paths, "s2-channel"); await createChannel(paths, "s2-channel", { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" }); const again = lstatSync(chan); assert.ok(again.ino !== made.ino || again.birthtimeMs !== made.birthtimeMs, "the test's file system tells the two directories apart"); const refused = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); assert.deepEqual(refused, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "it is not the channel this publish made: that one was removed, and this one was made since") }); assert.deepEqual(readdirSync(chan), ["config.json"], "nothing was added to it"); // A record that says neither which directory nor that a publish was cut: refused. await mutateXTrendingPublished(libRoot, (all) => { delete all["kettle-festival"].identity; return { write: true, result: undefined }; }); const unsaid = await publishXTrendingTopic(paths, { ...ask("zzlibs2", "s2-channel"), dryRun: true }); assert.deepEqual(unsaid, { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL("s2-channel", "the library's record does not say which channel it made") }); // A PUBLISH CUT after it made the channel and before it recorded which: `pending`, and the channel holds // nothing. The next publish takes it up and records the directory. await mutateXTrendingPublished(libRoot, (all) => { all["kettle-festival"].pending = true; return { write: true, result: undefined }; }); const resumed = await go("zzlibs2", "s2-channel"); assert.ok(resumed.ok && !resumed.result.creates, JSON.stringify(resumed)); assert.deepEqual((await readAllPosts(chan)).map((p) => p.id).sort(), ["931", "932"]); const after = (await readXTrendingPublished(libRoot))["kettle-festival"]; assert.deepEqual([after.identity, after.pending], [{ ino: again.ino, birthtimeMs: again.birthtimeMs }, undefined]); await deleteChannel(paths, "zzlibs2"); await deleteChannel(paths, "s2-channel"); }); test("S4: the dry run names the sites the channel is on, and the confirm covers it: put on a site after the count, the publish is refused", async () => { const libRoot = await small("zzlibs4", ["941", "942"]); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "941", state: "keep" }] }); const first = await go("zzlibs4", "s4-channel"); assert.ok(first.ok); assert.deepEqual(first.result.sites, []); assert.match(first.result.sentence, /made the channel "s4-channel", on no site,/); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "942", state: "keep" }] }); const offSite = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: true }); assert.ok(offSite.ok); assert.deepEqual(offSite.result.sites, []); // The operator's separate act, made between the count and the press. const site = (siteId: string, channels: string[]) => ({ siteId, siteTitle: siteId, siteDescription: "fixture", headerTitle: siteId, homeTagline: "", socialLinks: [], groups: [{ id: "default", name: "All channels", selectedByDefault: true }], defaultGroupId: "default", channels: channels.map((slug) => ({ slug, groupId: "default" })), siteUrl: `https://${siteId}.example.test`, archives: false, }); await writeSite(site("kettle-site", ["s4-channel"]) as never, paths); assert.deepEqual(await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: false, confirm: offSite.result.confirm, by: "operator" }), { ok: false, error: PUBLISH_SET_CHANGED }); assert.deepEqual((await readAllPosts(path.join(paths.channelsDir, "s4-channel"))).map((p) => p.id), ["941"], "nothing was written"); const onSite = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: true }); assert.ok(onSite.ok); assert.deepEqual(onSite.result.sites, ["kettle-site"]); assert.notEqual(onSite.result.confirm, offSite.result.confirm); assert.equal( onSite.result.sentence, 'Publishing "Kettle Festival" would add to the channel "s4-channel" writing 1 post and 0 files (0 B); 1 of the 2 kept posts is there already. ' + "THIS CHANNEL IS ON THE SITE kettle-site: this post goes public at its next build. " + "2 posts have no capture yet and are published as their words alone: a later publish adds the files.", ); const done = await publishXTrendingTopic(paths, { ...ask("zzlibs4", "s4-channel"), dryRun: false, confirm: onSite.result.confirm, by: "operator" }); assert.ok(done.ok); await deleteChannel(paths, "zzlibs4"); await deleteChannel(paths, "s4-channel"); rmSync(paths.sitesDir, { recursive: true, force: true }); }); test("S5: the dry run says how many of the posts to publish were moved into the topic, and by whom", async () => { const libRoot = await small("zzlibs5", ["951", "952", "953", "954"]); await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["955"], added: 0 }); await moveXTrendingPosts(libRoot, { to: "cups", ids: ["952", "953", "954"], by: "operator" }); // Back into the topic: two by an agent, one by the operator. 951 never moved. await moveXTrendingPosts(libRoot, { to: "kettle-festival", ids: ["952", "953"], by: "agent" }); await moveXTrendingPosts(libRoot, { to: "kettle-festival", ids: ["954"], by: "operator" }); await judgeXTrending(libRoot, { by: "operator", set: ["951", "952", "953", "954"].map((id) => ({ id, state: "keep" as const })) }); const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs5", "s5-channel"), dryRun: true }); assert.ok(dry.ok); assert.deepEqual(dry.result.movedIn, [{ id: "952", by: "agent", from: "cups" }, { id: "953", by: "agent", from: "cups" }, { id: "954", by: "operator", from: "cups" }]); assert.match(dry.result.sentence, / 3 posts to publish were moved into this topic: 2 by an agent, 1 by the operator\./); // Once published they are not "to publish" any more. const done = await go("zzlibs5", "s5-channel"); assert.ok(done.ok); const again = await publishXTrendingTopic(paths, { ...ask("zzlibs5", "s5-channel"), dryRun: true }); assert.ok(again.ok); assert.deepEqual(again.result.movedIn, []); await deleteChannel(paths, "zzlibs5"); await deleteChannel(paths, "s5-channel"); }); test("S8: a file whose bytes are no longer what its capture recorded is not published, is reported, and gets no new digest; an interrupted copy's temp files are swept", async () => { const libRoot = await small("zzlibs8", ["961"]); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "961", state: "keep" }] }); capture(libRoot, "961", { "shot.png": "SHOT-961", "961_1.jpg": "PICTURE-961", "961_2.jpg": "PICTURE-TWO" }); // After the capture, one picture's bytes changed under the library. writeFileSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"), "NOT WHAT WAS CAPTURED"); const dry = await publishXTrendingTopic(paths, { ...ask("zzlibs8", "s8-channel"), dryRun: true }); assert.ok(dry.ok); assert.deepEqual(dry.result.mismatched, [{ id: "961", name: "961_2.jpg" }]); assert.equal(dry.result.files, 2); assert.equal(dry.result.bytes, "SHOT-961".length + "PICTURE-961".length); assert.match(dry.result.sentence, / 1 file no longer matches the digest its capture recorded and is not copied \(961\/961_2\.jpg\)\./); const done = await go("zzlibs8", "s8-channel"); assert.ok(done.ok); const dir = path.join(paths.channelsDir, "s8-channel", "posts-media", "961"); assert.deepEqual(readdirSync(dir).sort(), ["961_1.jpg", "capture.json", "shot.png"]); const cap = JSON.parse(readFileSync(path.join(dir, "capture.json"), "utf8")); assert.deepEqual(cap.media.map((m: { name: string; sha256: string }) => [m.name, m.sha256]), [["961_1.jpg", sha("PICTURE-961")]], "no record, and no digest, of the file that was not copied"); assert.doesNotMatch(JSON.stringify(cap), /961_2|NOT WHAT/); // The bytes put right: the next publish copies it. Temp names an interrupted copy left are swept; nothing else is. writeFileSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"), "PICTURE-TWO"); writeFileSync(path.join(dir, ".publish-0123456789ab.part"), "half a copy"); writeFileSync(path.join(dir, ".publish-notours.part"), "somebody else's"); const fixed = await go("zzlibs8", "s8-channel"); assert.ok(fixed.ok); assert.deepEqual(fixed.result.mismatched, []); assert.deepEqual(readdirSync(dir).sort(), [".publish-notours.part", "961_1.jpg", "961_2.jpg", "capture.json", "shot.png"]); assert.equal(readFileSync(path.join(dir, "961_2.jpg"), "utf8"), "PICTURE-TWO"); assert.ok(existsSync(path.join(libRoot, "trending", "posts-media", "961", "961_2.jpg"))); await deleteChannel(paths, "zzlibs8"); await deleteChannel(paths, "s8-channel"); }); // Review 1 S5. test("S5: a dry run says when the topic is named by X's page, not by a person; the slug is still the caller's to name; a rename ends it", async () => { const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); const lib = "zzpagetitledlib"; const libRoot = path.join(paths.channelsDir, lib); await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); await writeXTrendingPosts(libRoot, [post(lib, "901", "words of 901"), post(lib, "902", "words of 902")]); // Nobody named the topic: it took the page's title. await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["901"], added: 1, page: { title: "Kettle festival opens" } }); await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["902"], added: 1 }); await judgeXTrending(libRoot, { by: "operator", set: [{ id: "901", state: "keep" }, { id: "902", state: "keep" }] }); const ask = { slug: lib, topic: `t-${REF.trendId}`, deriveSlug: derive, busy: IDLE }; const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); assert.ok(dry.ok, dry.ok ? "" : dry.error); assert.equal(dry.result.titleFrom, "page"); assert.equal(dry.result.channel, "kettle-festival-opens"); assert.equal( dry.result.sentence, 'Publishing "Kettle festival opens" would make the channel "kettle-festival-opens", on no site, writing 1 post and 0 files (0 B); 0 of the 1 kept post are there already. ' + `The topic is named by X's page: "Kettle festival opens" — the channel would carry that name. Rename the topic first to publish under your own name; "channel" names another slug than "kettle-festival-opens".` + " 1 post has no capture yet and is published as its words alone: a later publish adds the files.", ); // The slug is the caller's to name, as before. const named = await publishXTrendingTopic(paths, { ...ask, channel: "my-kettles", dryRun: true }); assert.ok(named.ok && named.result.channel === "my-kettles" && named.result.titleFrom === "page"); // A topic made under a name asked for: said to be so, and no such sentence. const cups = await publishXTrendingTopic(paths, { ...ask, topic: "cups", dryRun: true }); assert.ok(cups.ok); assert.equal(cups.result.titleFrom, "ask"); assert.doesNotMatch(cups.result.sentence, /named by X's page/); // Renamed by a person: the name is theirs. assert.equal((await renameXTrendingTopic(libRoot, { topic: `t-${REF.trendId}`, title: "Kettles, my pick", by: "operator", readInFlight: IDLE })).ok, true); const after = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); assert.ok(after.ok); assert.equal(after.result.titleFrom, "rename"); assert.doesNotMatch(after.result.sentence, /named by X's page/); rmSync(libRoot, { recursive: true, force: true }); });