import test from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/publish-trending/route.test.ts" // // publish-trending, organise-trending and the accounts listing over ops (lane // x-trending-publish), against a temp corpus: the dry run that writes // nothing, the publish that is the operator's, the channel it makes (on no // site, with a slug of the topic's name), a merge that is the operator's, and // the library's accounts with the lead action's dry run. const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-publish-route-")); process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); const READ = "tr-01JA0000000000000000000000"; const A = "1900000000000001001"; const B = "1900000000000001002"; const C = "1900000000000001003"; async function channel(slug: string, config: Record): Promise { const dir = path.join(ROOT, "channels", slug); await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); return dir; } const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {} }); const row = (id: string, author: string) => JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: `post ${id}`, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] }); await writeFile(path.join(lib, "trending", "posts", "2026-11.jsonl"), `${row(A, "teapot_news")}\n${row(B, "teapot_news")}\n${row(C, "saucer_fan")}\n`); await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\ntwitter ${C}\n`); const seen = [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank: 1 }]; const src = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}`, reads: [] }); await writeFile( path.join(lib, "trending", "topics.json"), JSON.stringify({ version: 1, topics: [{ id: "kettles", title: "Kettle Festival 2026", createdAt: "2026-11-17T10:00:00.000Z", sources: [src(1)] }, { id: "cups", title: "Cups", createdAt: "2026-11-17T10:00:00.000Z", sources: [src(2)] }] }), ); await writeFile(path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen }, [B]: { topic: "kettles", seen }, [C]: { topic: "cups", seen } } })); await writeFile( path.join(lib, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { [A]: { state: "keep", note: "why", by: "operator", at: "2026-11-17T12:00:00.000Z" }, [B]: { state: "keep", by: "agent", at: "2026-11-17T12:00:00.000Z" } }, threads: {} }), ); await mkdir(path.join(lib, "trending", "posts-media", A), { recursive: true }); await writeFile(path.join(lib, "trending", "posts-media", A, "shot.png"), "12345"); await writeFile(path.join(lib, "trending", "posts-media", A, "capture.json"), JSON.stringify({ version: 1, id: A, url: `https://x.com/i/status/${A}`, capturedAt: "2026-11-18T10:00:00.000Z", state: "captured", shot: { name: "shot.png", bytes: 5, sha256: "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5" }, mediaState: "none", media: [] })); const PUBLISH = (await import("./route")).POST; const ORGANISE = (await import("../organise-trending/route")).POST; const LIST = (await import("../trending/route")).GET; const LEAD = (await import("../x-search-lead/route")).POST; test.after(() => rm(ROOT, { recursive: true, force: true })); const exists = (p: string) => access(p).then(() => true, () => false); async function post(handler: (r: Request) => Promise, name: string, body: Record, token = "test-token") { const res = await handler(new Request(`http://localhost/api/ops/${name}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) })); return { status: res.status, json: (await res.json()) as Record }; } async function get(query: string) { const res = await LIST(new Request(`http://localhost/api/ops/trending?${query}`, { headers: { authorization: "Bearer test-token" } })); return { status: res.status, json: (await res.json()) as Record }; } test("publish-trending: the dry run writes nothing; the publish is the operator's with the dry run's digest; the channel is on no site", async () => { assert.equal((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }, "wrong")).status, 401); const dry = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }); assert.equal(dry.status, 200); assert.deepEqual( { channel: dry.json.channel, creates: dry.json.creates, kept: dry.json.kept, posts: dry.json.posts, ids: dry.json.ids, files: dry.json.files, bytes: dry.json.bytes, dryRun: dry.json.dryRun }, { channel: "kettle-festival-2026", creates: true, kept: 1, posts: 1, ids: [A], files: 1, bytes: 5, dryRun: true }, ); assert.match(dry.json.sentence, /would make the channel "kettle-festival-2026", on no site, writing 1 post and 1 file \(5 B\)/); // Review 1: where it would go public, who moved what in, and what no longer matches its capture. assert.deepEqual({ sites: dry.json.sites, movedIn: dry.json.movedIn, mismatched: dry.json.mismatched }, { sites: [], movedIn: [], mismatched: [] }); assert.deepEqual(await readdir(path.join(ROOT, "channels")), ["trending"]); for (const body of [{ confirm: dry.json.confirm }, { confirm: dry.json.confirm, by: "agent" }]) { const no = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", ...body }); assert.equal(no.status, 400); assert.match(no.json.error, /Publishing a topic is the operator's press/); } const stale = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", confirm: "nope", by: "operator" }); assert.match(stale.json.error, /has changed since it was counted/); assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", by: "operator" })).json.error, /two steps/); assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "nope", dryRun: true })).json.error, /has no topic "nope"/); assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "cups", dryRun: true })).json.error, /The operator has kept no post in "Cups"/); assert.match((await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true, extra: 1 })).json.error, /extra/); assert.deepEqual(await readdir(path.join(ROOT, "channels")), ["trending"]); const done = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", confirm: dry.json.confirm, by: "operator" }); assert.equal(done.status, 200, JSON.stringify(done.json)); assert.equal(done.json.dryRun, false); const chan = path.join(ROOT, "channels", "kettle-festival-2026"); assert.deepEqual(JSON.parse(await readFile(path.join(chan, "config.json"), "utf8")), { name: "Kettle Festival 2026", handling: "transcribe", sourceKind: "social", platform: "twitter" }); const lines = (await readFile(path.join(chan, "posts", "2026-11.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(lines.map((p) => [p.id, p.slug, p.channelSlug]), [[A, `kettle-festival-2026/${A}`, "kettle-festival-2026"]]); assert.equal(await readFile(path.join(chan, "posts-media", A, "shot.png"), "utf8"), "12345"); assert.equal(await exists(path.join(ROOT, "sites")), false, "on no site"); // The judge view's listing says where the topic went. const listed = await get("slug=trending&detail=1"); assert.deepEqual(listed.json.topics.find((t: any) => t.id === "kettles").published.channel, "kettle-festival-2026"); assert.equal((await get("slug=trending")).json.topics.find((t: any) => t.id === "kettles").published, undefined, "asked as before it answers as before"); }); test("organise-trending: rename and move are anyone's and recorded; a merge is the operator's", async () => { const renamed = await post(ORGANISE, "organise-trending", { slug: "trending", op: "rename", topic: "cups", title: "Cups and saucers" }); assert.equal(renamed.status, 200); assert.deepEqual([renamed.json.topic, renamed.json.title, renamed.json.changed], ["cups", "Cups and saucers", true]); const moved = await post(ORGANISE, "organise-trending", { slug: "trending", op: "move", to: "cups", ids: [B] }); assert.deepEqual([moved.json.moved, moved.json.to.id], [[B], "cups"]); const topics = JSON.parse(await readFile(path.join(lib, "trending", "topics.json"), "utf8")).topics; assert.deepEqual(topics.find((t: any) => t.id === "cups").organised.by, "agent", "by is \"agent\" unless told"); const agent = await post(ORGANISE, "organise-trending", { slug: "trending", op: "merge", into: "kettles", from: ["cups"] }); assert.equal(agent.status, 400); assert.match(agent.json.error, /Merging topics is the operator's press/); assert.match((await post(ORGANISE, "organise-trending", { slug: "trending", op: "split" })).json.error, /"op"/); assert.match((await post(ORGANISE, "organise-trending", { slug: "nope", op: "rename", topic: "a", title: "b" })).json.error, /No such channel/); const merged = await post(ORGANISE, "organise-trending", { slug: "trending", op: "merge", into: "kettles", from: ["cups"], by: "operator" }); assert.equal(merged.status, 200, JSON.stringify(merged.json)); assert.deepEqual([merged.json.into.id, merged.json.posts, merged.json.pages], ["kettles", 2, 2]); // The merged topic's id still names the target. const byOld = await get("slug=trending&topic=cups"); assert.equal(byOld.status, 200); assert.equal(byOld.json.total, 3); // A published topic that was renamed keeps its channel. await post(ORGANISE, "organise-trending", { slug: "trending", op: "rename", topic: "kettles", title: "Teapots", by: "operator" }); const again = await post(PUBLISH, "publish-trending", { slug: "trending", topic: "kettles", dryRun: true }); assert.deepEqual([again.json.channel, again.json.creates, again.json.posts], ["kettle-festival-2026", false, 0]); }); test("the library's accounts, and Archive this account as a dry run: -x, nothing of the library", async () => { const view = await get("slug=trending&accounts=1"); assert.equal(view.status, 200); assert.deepEqual(view.json.accounts.map((a: any) => [a.handle, a.posts, a.kept, a.keptByOperator, a.topics]), [["teapot_news", 2, 2, 1, ["kettles"]], ["saucer_fan", 1, 0, 0, ["kettles"]]]); assert.match((await get("slug=trending&accounts=1&detail=1")).json.error, /takes slug, topic and limit only/); assert.match((await get("slug=kettle-festival-2026&accounts=1")).json.error, /is not an X trending library/); const plan = await post(LEAD, "x-search-lead", { slug: "trending", handle: "saucer_fan", action: "archive", dryRun: true }); assert.equal(plan.status, 200); assert.deepEqual([plan.json.slug, plan.json.fields.url, plan.json.dryRun], ["saucer_fan-x", "https://x.com/saucer_fan", true]); assert.doesNotMatch(JSON.stringify(plan.json), /trending/); assert.match((await post(LEAD, "x-search-lead", { slug: "trending", handle: "nobody_here", action: "archive", dryRun: true })).json.error, /holds no post by @nobody_here/); assert.match((await post(LEAD, "x-search-lead", { slug: "trending", handle: "saucer_fan", action: "never" })).json.error, /is not an X search channel/); assert.equal(await exists(path.join(ROOT, "channels", "saucer_fan-x")), false, "a dry run creates nothing"); }); // Review 1 M2 and S1: the published channel cannot be given a fetcher, and no door builds an address for one of its posts. test("the published channel: Scraping method is refused and writes nothing; a Wayback lookup and transcribe-one of one of its posts are refused", async () => { const SLUG = "kettle-festival-2026"; const SAYS = `${SLUG} holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it.`; const { setPostFetcherAction } = await import("../../../channels/[slug]/socialActions"); const before = await readFile(path.join(ROOT, "channels", SLUG, "config.json"), "utf8"); for (const fetcher of ["x-gallery-dl", "x-playwright", "nope"]) { assert.deepEqual(await setPostFetcherAction(SLUG, fetcher), { ok: false, error: SAYS }); } assert.equal(await readFile(path.join(ROOT, "channels", SLUG, "config.json"), "utf8"), before, "no key was written"); const WAYBACK = (await import("../wayback-lookup/route")).POST; const looked = await post(WAYBACK, "wayback-lookup", { slug: SLUG, id: A }); assert.equal(looked.status, 400); assert.equal(looked.json.error, SAYS); const TRANSCRIBE = (await import("../transcribe-one/route")).POST; const transcribed = await post(TRANSCRIBE, "transcribe-one", { slug: SLUG, id: A }); assert.ok(transcribed.status >= 400, JSON.stringify(transcribed.json)); assert.equal(transcribed.json.jobId, undefined, "no job was made"); });