commit 6dbd6357a4cab2d18b55eb360786b65146b473ff
parent 70ade9964e34d2ba79bda3b482842cbb8ca53baa
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 10:34:38 -0500
common, editor: x-trending slice 4, publish -- a topic's posts kept by the operator become an ordinary posts channel that names nothing of the library
publishXTrendingTopic (controller/publishXTrending.ts): two steps held by
a digest of the library, topic, slug, exact posts and exact files; the
second is the operator's. Refused while a read, a reparse or a capture of
the library is queued or running, and the set is read again inside the
media index's lock before the first write. Posts are rebuilt from an
explicit allowlist (a new Post field is a compile error there until it is
decided) with the channel's slug; captures are the files the record names
and a record rebuilt without the library's owed and error text; the
availability sidecar carries the published ids only.
Files are COPIED (COPYFILE_FICLONE: a new inode always), never linked: the
purge frees a blob only when nothing else links to it, so a link into the
channel would keep every blob and make its count untrue. Pinned: no
published inode is a library inode, a purge after a publish frees what it
would have freed, and deleting either side leaves the other whole.
"Made by this publish" is the library's record (trending/published.json,
written before the posts) and the channel's content: the record names the
slug, the channel still has the source-less shape, and it holds no post
the record does not name. The channel carries no mark.
A posts channel with no source (lib/sourcelessPosts.ts) makes no request:
fetch-posts, capture-posts, the availability check and an X run refuse it
by name with one sentence, an X run's candidates and Sync all leave it out
with a reason, and Configure says what it is instead of asking for a
handle.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
12 files changed, 1204 insertions(+), 3 deletions(-)
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -35,6 +35,7 @@
import path from "node:path";
import { isXSearchChannel } from "../lib/xSearch/config";
import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts";
import {
readXTrendingMembership,
TRENDING_RESPONSES_FILENAME,
@@ -259,6 +260,9 @@ export async function capturePosts(
const config = await readChannelConfig(paths, slug);
if (!config) return fail(`No such channel: ${slug}`);
if (!isSocialChannel(config)) return fail(`${slug} is not a social channel.`);
+ // Posts published from a private library (lane x-trending-publish): their
+ // captures came with them, and nothing is asked of X for this channel.
+ if (isSourcelessPostsChannel(config)) return fail(SOURCELESS_POSTS_CHANNEL(slug));
// A Wayback pages channel (release 37 S4): no fetcher — each record is
// rendered from its capture's replay, its images from the archive.
diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts
@@ -40,6 +40,7 @@ import "../social/xNitterFetcher";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import type { CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
import { checkPageAvailability } from "./checkPageAvailability";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts";
export type CheckPostAvailabilityMode = "stale" | "unchecked" | "all";
@@ -125,6 +126,11 @@ export async function checkPostAvailability(
if (!isSocialChannel(config)) {
return { ok: false, ...empty, error: `${slug} is not a social channel.` };
}
+ // Posts published from a private library (lane x-trending-publish): what X
+ // said of them came with them; nothing is asked of X for this channel.
+ if (isSourcelessPostsChannel(config)) {
+ return { ok: false, ...empty, error: SOURCELESS_POSTS_CHANNEL(slug) };
+ }
// A Wayback pages channel (release 37 S5): each record's ORIGINAL URL,
// asked at its own site — no fetcher, never the Wayback Machine.
if (isWaybackPagesChannel(config)) {
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -17,6 +17,7 @@ import { isSocialChannel } from "../lib/channelConfig";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { isXSearchChannel } from "../lib/xSearch/config";
import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "../lib/xTrending/config";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts";
import { fetchXSearchPosts, X_SEARCH_OLDER_REFUSAL } from "./fetchXSearch";
import {
alwaysCookies,
@@ -285,6 +286,12 @@ export async function fetchPosts(
return { ok: false, written: 0, skipped: 0, complete: false, error: X_TRENDING_NOT_FETCHED(slug) };
}
+ // Posts published from a private library (lane x-trending-publish): no
+ // account, no search, no page — nothing is asked of X for it.
+ if (isSourcelessPostsChannel(config)) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: SOURCELESS_POSTS_CHANNEL(slug) };
+ }
+
const accountUrl = config.url ?? "";
const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl);
if (!fetcher) {
diff --git a/common/controller/publishXTrending.test.ts b/common/controller/publishXTrending.test.ts
@@ -0,0 +1,407 @@
+// 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 { lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, 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 {
+ 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> = {}): 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 };
+}
+
+function capture(libRoot: string, id: string, files: Record<string, string>, record: Record<string, unknown> = {}) {
+ 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",
+ ...(files["shot.png"] ? { shot: { name: "shot.png", bytes: 1, sha256: "0".repeat(64) } } : {}),
+ mediaState: "ok",
+ media: media.map((name) => ({ name, bytes: 1, sha256: "0".repeat(64), url: `https://pbs.twimg.com/media/${name}` })),
+ ...record,
+ }),
+ );
+ return media;
+}
+
+// A library "<lib>" 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<string> {
+ 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, 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<string, { name: string; bytes: number; sha256: string }> = { "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: [] },
+ });
+});
+
+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);
+ 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" } },
+ });
+});
+
+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, { 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, { 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));
+});
diff --git a/common/controller/publishXTrending.ts b/common/controller/publishXTrending.ts
@@ -0,0 +1,540 @@
+// PUBLISHING A TOPIC OF AN X TRENDING LIBRARY (lane x-trending-publish,
+// slice 4): the topic's posts whose judgement IN FORCE is KEEP BY THE
+// OPERATOR — their own entry, or their thread's — are materialised into an
+// ORDINARY posts channel. An agent's keep is a suggestion and is not
+// published; nor is a post marked later, dropped or undecided.
+//
+// THE LIBRARY STAYS BEHIND EVERY DOOR; THE CHANNEL IS AN ORDINARY CHANNEL, on
+// NO site until the operator adds it to one (a separate, existing act). The
+// channel carries NO mark of where it came from:
+//
+// posts each record REBUILT from an explicit allowlist of fields
+// (PUBLISHED_POST_FIELDS), with `slug` and `channelSlug` the
+// channel's — a stored library post carries the library's slug
+// in both. A field not on the list is not copied.
+// captures `posts-media/<id>/`: the files the capture record NAMES (the
+// shot, the thread shot, the media, an article's files) — never
+// a directory listing — and a record rebuilt from an allowlist
+// too, without what is the library's alone (`mediaOwed`, and
+// the error text of a half that is owed).
+// sidecar the published posts' availability (X said "deleted") only.
+//
+// Never the judgements, a note, the reads, the raw capture, the watch, a
+// "gone from the page" mark, or who decided.
+//
+// FILES ARE COPIED, NEVER LINKED. A library's media is hardlinked to its
+// store, and the purge frees a blob only when nothing else links to it
+// (lib/xTrending/mediaStore.ts): a hardlink into the channel would keep
+// every blob for ever and make the purge's count untrue, and library and
+// channel would share one inode. A copy (`COPYFILE_FICLONE`: shared extents
+// where the file system can, a NEW inode always) means a purge of the library
+// and a delete of the channel can neither reach the other's bytes.
+//
+// "MADE BY THIS PUBLISH" is the library's record (lib/xTrending/published.ts)
+// and the channel's own content — a THREE-PART PROOF, asked before a byte is
+// appended to a channel that exists:
+// 1. the record names this slug for this topic;
+// 2. the channel still has the shape this publish gives one (an X posts
+// channel with no account, search or page: lib/sourcelessPosts.ts);
+// 3. every post the channel holds is one the record says was published.
+// A channel deleted and made again by hand, or one another hand wrote posts
+// into, fails it and is refused; a slug that is free is simply made (again).
+//
+// TWO STEPS, AND THE SECOND IS THE OPERATOR'S. A dry run writes nothing and
+// answers exactly what would be written (the slug, posts, files, bytes) with
+// `confirm`, a digest of the library, the topic, the slug, the exact posts
+// and the exact files. The publish carries it and `by: "operator"`; if the
+// set changed in between it is refused and nothing is written — read again
+// inside the media index's lock, immediately before the first write.
+//
+// REFUSED WHILE A READ, A REPARSE OR A CAPTURE OF THE LIBRARY IS QUEUED OR
+// RUNNING (the caller answers that from its job registry): a read can change
+// the membership the digest was computed over, and a capture writes the
+// directories this copies from, outside the lock.
+//
+// RE-PUBLISHING ADDS AND REMOVES NOTHING: newly kept posts are added; a post
+// published before and no longer kept is REPORTED (`noLongerKept`) and left;
+// a file already in the channel is never overwritten; a post published as
+// text before its capture existed gets its files at the next publish.
+//
+// SERVER-ONLY (node:fs).
+
+import { createHash, randomBytes } from "node:crypto";
+import { constants as FS } from "node:fs";
+import { copyFile, lstat, mkdir, realpath, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { withJsonFileLock } from "../lib/jsonFile-server";
+import type { Paths } from "../lib/paths";
+import { parsePost, postSlug, type Post, type PostAvailabilityMap } from "../lib/posts";
+import { readPostAvailability, readSeenPostIds, writePostAvailability, writePosts } from "../lib/posts-server";
+import { isSourcelessPostsChannel } from "../lib/sourcelessPosts";
+import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "../lib/xTrending/config";
+import { xTrendingMediaIndexPath } from "../lib/xTrending/mediaStore";
+import { mutateXTrendingPublished, readXTrendingPublished } from "../lib/xTrending/published";
+import {
+ listXTrending,
+ readXTrendingPosts,
+ readXTrendingTopics,
+ resolveXTrendingTopic,
+ xTrendingPostsMediaDir,
+ xTrendingPostsRoot,
+} from "../lib/xTrending/store";
+import {
+ fileDigest,
+ postCaptureDir,
+ postsMediaDir,
+ readPostCapture,
+ writePostCapture,
+ type ArticleCaptureRecord,
+ type CapturedFile,
+ type PostCaptureRecord,
+} from "../social/postCapture";
+import { channelExists, createChannel, isValidChannelSlug, readChannelConfig } from "./channels";
+
+// ── the allowlists ─────────────────────────────────────────────────────────
+
+// EVERY FIELD OF A POST, DECIDED: true = copied into the published record.
+// `satisfies Record<keyof Post, boolean>` makes a NEW field of Post a compile
+// error here until somebody decides it — and it is not copied until then.
+const POST_FIELDS = {
+ id: true,
+ // Rewritten, never copied: the library's slug is in both.
+ slug: false,
+ channelSlug: false,
+ author: true,
+ authorName: true,
+ createdAt: true,
+ uploadDate: true,
+ text: true,
+ url: true,
+ platform: true,
+ lang: true,
+ threadId: true,
+ replyTo: true,
+ quoted: true,
+ repostOf: true,
+ isReply: true,
+ isRepost: true,
+ links: true,
+ mediaCount: true,
+ media: true,
+ engagement: true,
+ // Not an X post's.
+ forum: false,
+ page: false,
+ // Derived at index time from the availability sidecar, never stored.
+ isDeleted: false,
+ availability: false,
+ availabilityCheckedAt: false,
+} as const satisfies Record<keyof Post, boolean>;
+
+export const PUBLISHED_POST_FIELDS: readonly string[] = Object.entries(POST_FIELDS)
+ .filter(([, copied]) => copied)
+ .map(([key]) => key);
+
+// A library post as the channel's own record, or null when it is not a post.
+export function publishedPostOf(stored: Post, channel: string): Post | null {
+ const raw: Record<string, unknown> = {};
+ for (const key of PUBLISHED_POST_FIELDS) {
+ const value = (stored as unknown as Record<string, unknown>)[key];
+ if (value !== undefined) raw[key] = value;
+ }
+ raw.channelSlug = channel;
+ raw.slug = postSlug(channel, stored.id);
+ // parsePost is the posts store's own allowlist, one level down (a ref's
+ // and an engagement's keys).
+ return parsePost(raw);
+}
+
+const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
+
+function capturedFile(f: CapturedFile | undefined): CapturedFile | undefined {
+ if (!f || typeof f !== "object" || typeof f.name !== "string" || !SAFE_NAME.test(f.name)) return undefined;
+ return {
+ name: f.name,
+ bytes: Number(f.bytes) || 0,
+ sha256: typeof f.sha256 === "string" ? f.sha256 : "",
+ ...(typeof f.url === "string" && f.url ? { url: f.url } : {}),
+ };
+}
+
+// The files a capture record names, in a fixed order: what a publish copies.
+export function captureFileNames(record: PostCaptureRecord): string[] {
+ const names = [
+ record.shot?.name,
+ record.thread?.name,
+ ...(Array.isArray(record.media) ? record.media.map((m) => m?.name) : []),
+ ...(Array.isArray(record.article?.files) ? record.article!.files.map((f) => f?.name) : []),
+ ];
+ return [...new Set(names.filter((n): n is string => typeof n === "string" && SAFE_NAME.test(n) && n !== "capture.json"))];
+}
+
+// A library capture's record as an ordinary channel's: an allowlist, and of
+// the files only those `has` says are in the channel. NOT COPIED: `mediaOwed`
+// ("owed until the post is kept" is the library's word), `error` and
+// `threadError` (a half the library still owes), and an article's `error`.
+export function publishedCaptureOf(record: PostCaptureRecord, has: (name: string) => CapturedFile | undefined): PostCaptureRecord {
+ const file = (f: CapturedFile | undefined) => {
+ const clean = capturedFile(f);
+ const there = clean ? has(clean.name) : undefined;
+ return clean && there ? { ...clean, bytes: there.bytes, sha256: there.sha256 } : undefined;
+ };
+ const shot = file(record.shot);
+ const media = (Array.isArray(record.media) ? record.media : []).map(file).filter((f): f is CapturedFile => !!f);
+ const threadFile = file(record.thread);
+ const a = record.article;
+ const article: ArticleCaptureRecord | undefined =
+ a && typeof a === "object" && typeof a.articleId === "string" && typeof a.url === "string"
+ ? {
+ articleId: a.articleId,
+ url: a.url,
+ capturedAt: a.capturedAt,
+ state: a.state,
+ ...(typeof a.title === "string" ? { title: a.title } : {}),
+ blocks: Number(a.blocks) || 0,
+ ...(a.extraction ? { extraction: a.extraction } : {}),
+ files: (Array.isArray(a.files) ? a.files : []).map(file).filter((f): f is CapturedFile => !!f),
+ ...(a.trimmed ? { trimmed: true } : {}),
+ }
+ : undefined;
+ const ctx = record.context;
+ return {
+ version: 1,
+ id: record.id,
+ url: record.url,
+ capturedAt: record.capturedAt,
+ state: record.state,
+ ...(record.sensitive ? { sensitive: true } : {}),
+ ...(shot ? { shot } : {}),
+ ...(shot && record.shotScope ? { shotScope: record.shotScope } : {}),
+ ...(shot && record.trimmed ? { trimmed: true } : {}),
+ mediaState: record.mediaState,
+ media,
+ ...(article ? { article } : {}),
+ ...(threadFile && record.thread
+ ? {
+ thread: {
+ ...threadFile,
+ parentId: record.thread.parentId,
+ ...(record.thread.parentHandle ? { parentHandle: record.thread.parentHandle } : {}),
+ ...(record.thread.parentAuthor ? { parentAuthor: record.thread.parentAuthor } : {}),
+ parentVerified: record.thread.parentVerified === true,
+ ...(record.thread.parentBadge ? { parentBadge: record.thread.parentBadge } : {}),
+ parentFrom: record.thread.parentFrom,
+ redaction: record.thread.redaction,
+ },
+ }
+ : {}),
+ ...(typeof record.threadNone === "string" ? { threadNone: record.threadNone } : {}),
+ ...(ctx && typeof ctx === "object" && typeof ctx.readAt === "string"
+ ? { context: { readAt: ctx.readAt, ...(ctx.quoted ? { quoted: ctx.quoted } : {}), ...(ctx.parent ? { parent: ctx.parent } : {}) } }
+ : {}),
+ };
+}
+
+// ── the ask and the answer ─────────────────────────────────────────────────
+
+export type PublishXTrendingAsk = {
+ // The library, and its topic (id, a merged id, or its name).
+ slug: string;
+ topic: string;
+ // The channel's slug, for a topic never published (a published topic's is
+ // fixed). Absent: `deriveSlug` of the topic's title.
+ channel?: string;
+ deriveSlug: (title: string) => string;
+ dryRun: boolean;
+ confirm?: string;
+ by?: unknown;
+ // A read, a reparse or a capture of this library queued or running
+ // (required, so no door can forget it).
+ busy: () => boolean | Promise<boolean>;
+ now?: number;
+};
+
+export type PublishXTrendingResult = {
+ dryRun: boolean;
+ library: string;
+ topic: { id: string; title: string };
+ // The channel the posts go into, and whether this publish makes it.
+ channel: string;
+ creates: boolean;
+ // The topic's posts kept by the operator; of them, the ones to add (`ids`)
+ // and the ones the channel already holds.
+ kept: number;
+ posts: number;
+ ids: string[];
+ already: number;
+ // Files to copy and their size (media, shots, an article's files).
+ files: number;
+ bytes: number;
+ // Kept posts with no capture yet: published as their words alone; a later
+ // publish adds their files.
+ textOnly: string[];
+ // Published before and no longer kept by the operator: reported, left.
+ noLongerKept: string[];
+ inFlight?: true;
+ confirm: string;
+ sentence: string;
+};
+
+export const PUBLISH_IS_THE_OPERATORS =
+ `Publishing a topic is the operator's press: an agent may ask for the dry run ("dryRun": true), which says what would be written and writes nothing. ` +
+ `The operator publishes on umtool's Posts library page, or with "by": "operator".`;
+
+export const PUBLISH_WAITS = "A read or a capture of this library is queued or running: publish once it has finished (its job is on /jobs).";
+
+export const PUBLISH_SET_CHANGED =
+ "What would be published has changed since it was counted (a post kept or dropped, a capture finished, a post moved): nothing was written. Ask for the dry run again.";
+
+export const NOT_THIS_PUBLISHS_CHANNEL = (channel: string, why: string) =>
+ `A channel "${channel}" already exists and was not made by publishing this topic (${why}): nothing is added to it. Publish under another slug ("channel"), or remove that channel first.`;
+
+const n = (k: number, what: string) => `${k} ${what}${k === 1 ? "" : "s"}`;
+
+export function formatPublishBytes(b: number): string {
+ if (b < 1024) return `${b} B`;
+ if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
+ if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`;
+ return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`;
+}
+
+export function xTrendingPublishConfirm(o: { library: string; topic: string; channel: string; ids: ReadonlyArray<string>; files: ReadonlyArray<string> }): string {
+ return createHash("sha256")
+ .update(JSON.stringify([o.library, o.topic, o.channel, [...o.ids].sort(), [...o.files].sort()]))
+ .digest("hex")
+ .slice(0, 24);
+}
+
+export function publishSentence(r: Omit<PublishXTrendingResult, "sentence">): string {
+ const would = r.dryRun;
+ const where = r.creates
+ ? `${would ? "would make" : "made"} the channel "${r.channel}", on no site,`
+ : `${would ? "would add to" : "added to"} the channel "${r.channel}"`;
+ const what = `${n(r.posts, "post")} and ${n(r.files, "file")} (${formatPublishBytes(r.bytes)})`;
+ const head =
+ r.posts === 0 && r.files === 0 && !r.creates
+ ? `Nothing to add: the channel "${r.channel}" already holds the ${n(r.kept, "post")} the operator kept in "${r.topic.title}".`
+ : `Publishing "${r.topic.title}" ${where} ${would ? "writing" : "and wrote"} ${what}; ${r.already} of the ${n(r.kept, "kept post")} ${r.already === 1 ? "is" : "are"} there already.`;
+ const text = r.textOnly.length
+ ? ` ${n(r.textOnly.length, "post")} ${r.textOnly.length === 1 ? "has" : "have"} no capture yet and ${r.textOnly.length === 1 ? "is" : "are"} published as ${r.textOnly.length === 1 ? "its" : "their"} words alone: a later publish adds the files.`
+ : "";
+ const gone = r.noLongerKept.length
+ ? ` ${n(r.noLongerKept.length, "post")} published before ${r.noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${r.noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).`
+ : "";
+ const copies = r.files > 0 ? " The files are copies: the library keeps its own." : "";
+ const site = r.creates && !would ? " Adding the channel to a site is a separate step." : "";
+ const waits = r.inFlight ? " A read or a capture of this library is queued or running: the publish waits for it." : "";
+ return `${head}${text}${gone}${copies}${site}${waits}`;
+}
+
+// ── the plan ───────────────────────────────────────────────────────────────
+
+type PlannedFile = { id: string; name: string; from: string; to: string; bytes: number };
+type Plan = {
+ channelRoot: string;
+ creates: boolean;
+ kept: string[];
+ fresh: Post[];
+ already: number;
+ files: PlannedFile[];
+ // Kept posts with a readable capture record.
+ captured: Map<string, PostCaptureRecord>;
+ textOnly: string[];
+ noLongerKept: string[];
+};
+
+type Fail = { ok: false; error: string };
+
+async function isRegularFileInside(file: string, root: string): Promise<number | null> {
+ const st = await lstat(file).catch(() => null);
+ if (!st?.isFile()) return null;
+ const [real, realRoot] = await Promise.all([realpath(file), realpath(root)]);
+ return real.startsWith(realRoot + path.sep) ? st.size : null;
+}
+
+async function plan(
+ paths: Paths,
+ o: { library: string; libRoot: string; topicId: string; channel: string; recorded: Record<string, string> | undefined },
+): Promise<{ ok: true; plan: Plan } | Fail> {
+ const channelRoot = path.join(paths.channelsDir, o.channel);
+ const exists = await channelExists(paths, o.channel);
+ let have = new Set<string>();
+ if (exists) {
+ // THE THREE-PART PROOF.
+ if (!o.recorded) return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "this library has no record of publishing into it") };
+ const config = await readChannelConfig(paths, o.channel);
+ if (!isSourcelessPostsChannel(config)) {
+ return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "it is a channel with a source of its own") };
+ }
+ have = await readSeenPostIds(channelRoot);
+ const strangers = [...have].filter((id) => !o.recorded![id]);
+ if (strangers.length > 0) {
+ return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, `it holds ${n(strangers.length, "post")} this topic never published`) };
+ }
+ }
+ const [listing, stored] = await Promise.all([
+ listXTrending(o.libRoot, { topic: o.topicId, ids: true, filter: { state: "keep", by: "operator" } }),
+ readXTrendingPosts(o.libRoot),
+ ]);
+ const byId = new Map(stored.map((p) => [p.id, p]));
+ const kept = [...(listing.ids ?? [])].sort();
+ const keptSet = new Set(kept);
+ const fresh: Post[] = [];
+ const files: PlannedFile[] = [];
+ const captured = new Map<string, PostCaptureRecord>();
+ const textOnly: string[] = [];
+ let already = 0;
+ const libMedia = xTrendingPostsMediaDir(o.libRoot);
+ for (const id of kept) {
+ const post = byId.get(id);
+ const built = post ? publishedPostOf(post, o.channel) : null;
+ if (!built) continue;
+ if (have.has(id)) already++;
+ else fresh.push(built);
+ const from = postCaptureDir(libMedia, id);
+ const record = await readPostCapture(from);
+ if (!record || record.id !== id) {
+ textOnly.push(id);
+ continue;
+ }
+ captured.set(id, record);
+ const to = postCaptureDir(postsMediaDir(channelRoot), id);
+ for (const name of captureFileNames(record)) {
+ if ((await lstat(path.join(to, name)).catch(() => null)) !== null) continue;
+ const bytes = await isRegularFileInside(path.join(from, name), o.libRoot);
+ if (bytes === null) continue;
+ files.push({ id, name, from: path.join(from, name), to: path.join(to, name), bytes });
+ }
+ }
+ const noLongerKept = Object.keys(o.recorded ?? {}).filter((id) => have.has(id) && !keptSet.has(id)).sort();
+ return { ok: true, plan: { channelRoot, creates: !exists, kept, fresh, already, files, captured, textOnly, noLongerKept } };
+}
+
+// One file, copied: to a temp name beside its place, checked against its
+// source, then renamed. Never a link.
+async function copyChecked(f: PlannedFile): Promise<void> {
+ await mkdir(path.dirname(f.to), { recursive: true });
+ const tmp = path.join(path.dirname(f.to), `.publish-${randomBytes(6).toString("hex")}.part`);
+ try {
+ await copyFile(f.from, tmp, FS.COPYFILE_FICLONE);
+ const [a, b] = await Promise.all([fileDigest(f.from), fileDigest(tmp)]);
+ if (a.sha256 !== b.sha256 || a.bytes !== b.bytes) throw new Error(`the copy of ${f.name} (post ${f.id}) does not match its source`);
+ await rename(tmp, f.to);
+ } catch (err) {
+ await rm(tmp, { force: true });
+ throw err;
+ }
+}
+
+// ── the door ───────────────────────────────────────────────────────────────
+
+export async function publishXTrendingTopic(
+ paths: Paths,
+ ask: PublishXTrendingAsk,
+): Promise<{ ok: true; result: PublishXTrendingResult } | Fail> {
+ if (ask.by !== undefined && ask.by !== "agent" && ask.by !== "operator") return { ok: false, error: `"by" is "agent" or "operator"` };
+ if (!ask.dryRun && ask.by !== "operator") return { ok: false, error: PUBLISH_IS_THE_OPERATORS };
+ if (!ask.dryRun && (typeof ask.confirm !== "string" || !ask.confirm)) {
+ return { ok: false, error: `Publishing takes two steps: ask with "dryRun": true first, then send its "confirm" back.` };
+ }
+ if (!isValidChannelSlug(ask.slug)) return { ok: false, error: `"${ask.slug}" is not a valid channel slug` };
+ const config = await readChannelConfig(paths, ask.slug);
+ if (!config) return { ok: false, error: `No such channel: ${ask.slug}` };
+ if (!isXTrendingChannel(config)) return { ok: false, error: NOT_AN_X_TRENDING_LIBRARY(ask.slug) };
+ const libRoot = path.join(paths.channelsDir, ask.slug);
+ const topics = await readXTrendingTopics(libRoot);
+ const topic = resolveXTrendingTopic(topics, ask.topic);
+ if (!topic) return { ok: false, error: `${ask.slug} has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"})` };
+
+ const record = (await readXTrendingPublished(libRoot))[topic.id];
+ if (record && ask.channel !== undefined && ask.channel !== record.slug) {
+ return { ok: false, error: `"${topic.title}" is published into the channel "${record.slug}": a topic has one channel, fixed at its first publish.` };
+ }
+ const channel = record?.slug ?? ask.channel ?? ask.deriveSlug(topic.title);
+ if (!isValidChannelSlug(channel)) {
+ return { ok: false, error: `"${channel}" is not a valid channel slug: name the channel ("channel": letters, digits, ".", "_" and "-").` };
+ }
+ if (channel === ask.slug) return { ok: false, error: `"${channel}" is the library itself: a topic is published into a channel of its own.` };
+
+ const look = () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, recorded: record?.posts });
+ const digest = (p: Plan) =>
+ xTrendingPublishConfirm({ library: ask.slug, topic: topic.id, channel, ids: p.fresh.map((x) => x.id), files: p.files.map((f) => `${f.id}/${f.name}`) });
+ const answer = (p: Plan, dryRun: boolean, inFlight: boolean): PublishXTrendingResult => {
+ const r: Omit<PublishXTrendingResult, "sentence"> = {
+ dryRun,
+ library: ask.slug,
+ topic: { id: topic.id, title: topic.title },
+ channel,
+ creates: p.creates,
+ kept: p.kept.length,
+ posts: p.fresh.length,
+ ids: p.fresh.map((x) => x.id),
+ already: p.already,
+ files: p.files.length,
+ bytes: p.files.reduce((a, f) => a + f.bytes, 0),
+ textOnly: p.textOnly,
+ noLongerKept: p.noLongerKept,
+ ...(inFlight ? { inFlight: true as const } : {}),
+ confirm: digest(p),
+ };
+ return { ...r, sentence: publishSentence(r) };
+ };
+
+ const first = await look();
+ if (!first.ok) return first;
+ if (first.plan.kept.length === 0) {
+ return { ok: false, error: `The operator has kept no post in "${topic.title}": there is nothing to publish. (An agent's keep is a suggestion and is not published.)` };
+ }
+ if (ask.dryRun) return { ok: true, result: answer(first.plan, true, await ask.busy()) };
+ if (digest(first.plan) !== ask.confirm) return { ok: false, error: PUBLISH_SET_CHANGED };
+ if (await ask.busy()) return { ok: false, error: PUBLISH_WAITS };
+
+ const at = new Date(ask.now ?? Date.now()).toISOString();
+ // Inside the media index's lock: no purge and no media adoption of this
+ // library runs beside the copy.
+ return withJsonFileLock(xTrendingMediaIndexPath(libRoot), async () => {
+ const again = await look();
+ if (!again.ok) return again;
+ const p = again.plan;
+ if (digest(p) !== ask.confirm) return { ok: false, error: PUBLISH_SET_CHANGED };
+ if (await ask.busy()) return { ok: false, error: PUBLISH_WAITS };
+
+ // 1. The record FIRST: the slug, and every post about to be written.
+ await mutateXTrendingPublished(libRoot, (all) => {
+ const have = all[topic.id] ?? { slug: channel, firstAt: at, lastAt: at, posts: {} };
+ for (const post of p.fresh) have.posts[post.id] ??= at;
+ have.lastAt = at;
+ all[topic.id] = have;
+ return { write: true, result: undefined };
+ });
+ // 2. The channel, through its own writer: on no site.
+ if (p.creates) await createChannel(paths, channel, { name: topic.title, handling: "transcribe", sourceKind: "social", platform: "twitter" });
+ // 3. The posts, through the posts store's writer.
+ await writePosts(p.channelRoot, p.fresh);
+ // 4. The files, then each capture's record.
+ for (const f of p.files) await copyChecked(f);
+ for (const [id, source] of p.captured) {
+ const dir = postCaptureDir(postsMediaDir(p.channelRoot), id);
+ const there = new Map<string, CapturedFile>();
+ for (const name of captureFileNames(source)) {
+ const st = await stat(path.join(dir, name)).catch(() => null);
+ if (st?.isFile()) there.set(name, { name, ...(await fileDigest(path.join(dir, name))) });
+ }
+ const existing = await readPostCapture(dir);
+ const next = publishedCaptureOf(source, (name) => there.get(name));
+ if (!existing || JSON.stringify(existing) !== JSON.stringify(next)) await writePostCapture(dir, next);
+ }
+ // 5. What X said of them ("deleted"), and nothing else of the sidecar.
+ const [libAvail, chanAvail] = await Promise.all([readPostAvailability(xTrendingPostsRoot(libRoot)), readPostAvailability(p.channelRoot)]);
+ const merged: PostAvailabilityMap = { ...chanAvail };
+ let changed = false;
+ for (const id of p.kept) {
+ const rec = libAvail[id];
+ if (!rec || (merged[id] && merged[id].checkedAt >= rec.checkedAt)) continue;
+ merged[id] = { availability: rec.availability, checkedAt: rec.checkedAt, ...(rec.history ? { history: rec.history.map((h) => ({ availability: h.availability, at: h.at })) } : {}) };
+ changed = true;
+ }
+ if (changed) await writePostAvailability(p.channelRoot, merged);
+ return { ok: true as const, result: answer(p, false, false) };
+ });
+}
diff --git a/common/controller/sourcelessPosts.test.ts b/common/controller/sourcelessPosts.test.ts
@@ -0,0 +1,112 @@
+// A POSTS CHANNEL WITH NO SOURCE — posts published from a private library
+// (lane x-trending-publish) — MAKES NO REQUEST ANYWHERE: every path that
+// would fetch, capture or check it refuses it by name with one sentence, and
+// every list of channels to run leaves it out. No fetcher is resolved, no
+// binary spawned, no browser opened (the suite also runs with the network
+// refused: lib/noNetwork.mjs).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/sourcelessPosts.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { chmod, mkdtemp, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "sourceless-posts-"));
+const TOUCHED = path.join(ROOT, "a-binary-ran");
+const BIN = path.join(ROOT, "fake-bin.mjs");
+await writeFile(BIN, `#!/usr/bin/env node\nimport { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(TOUCHED)}, "ran");\n`);
+await chmod(BIN, 0o755);
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+process.env.GALLERY_DL_BIN = BIN;
+process.env.YT_DLP_BIN = BIN;
+
+const { getPaths } = await import("../lib/paths");
+const { writePosts } = await import("../lib/posts-server");
+const { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL, syncSkipForShape } = await import("../lib/sourcelessPosts");
+const { registerSocialFetcher } = await import("../social/fetchers");
+const { createChannel } = await import("./channels");
+const { capturePosts } = await import("./capturePosts");
+const { checkPostAvailability } = await import("./checkPostAvailability");
+const { fetchPosts } = await import("./fetchPosts");
+const { isXPostsChannel, listXRunCandidates, planXRun } = await import("./xRun");
+const paths = getPaths();
+const settings = {} as never;
+
+// Every fetcher the registry could hand out, replaced by one that counts any
+// call made on it.
+let fetcherCalls = 0;
+const spy = (id: string) =>
+ new Proxy({ id, label: id, platform: "twitter", fields: {} } as Record<string, unknown>, {
+ get(target, prop) {
+ if (prop in target || typeof prop === "symbol") return target[prop as string];
+ return () => {
+ fetcherCalls++;
+ throw new Error(`fetcher ${id}.${String(prop)} was called`);
+ };
+ },
+ has: () => true,
+ });
+for (const id of ["x-gallery-dl", "x-playwright", "bluesky", "x"]) registerSocialFetcher(spy(id) as never);
+
+const PUBLISHED = { name: "Kettle Festival", handling: "transcribe", sourceKind: "social", platform: "twitter" } as const;
+await createChannel(paths, "kettle-festival", { ...PUBLISHED });
+await createChannel(paths, "teapot-x", { name: "Teapot (X)", handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/teapot_news", socialHandle: "teapot_news", postFetcher: "x-gallery-dl" });
+await writePosts(path.join(paths.channelsDir, "kettle-festival"), [
+ { id: "801", slug: "kettle-festival/801", channelSlug: "kettle-festival", author: "teapot_news", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: "words", url: "https://x.com/teapot_news/status/801", platform: "twitter", isReply: false, isRepost: false, links: [] },
+]);
+const SENTENCE = SOURCELESS_POSTS_CHANNEL("kettle-festival");
+
+test("the shape: an X posts channel with no account, search, page or marker — and no other", () => {
+ assert.equal(isSourcelessPostsChannel(PUBLISHED), true);
+ for (const other of [
+ { ...PUBLISHED, url: "https://x.com/teapot_news" },
+ { ...PUBLISHED, socialHandle: "teapot_news" },
+ { ...PUBLISHED, postFetcher: "x-gallery-dl" },
+ { ...PUBLISHED, xSearch: { query: "kettles" } },
+ { ...PUBLISHED, xTrending: {} },
+ { ...PUBLISHED, platform: "bluesky" },
+ { ...PUBLISHED, sourceKind: "video" },
+ { ...PUBLISHED, remoteOnly: true },
+ { ...PUBLISHED, platform: "webpage", wayback: { targets: [{ url: "https://example.org", match: "exact" }] } },
+ null,
+ ]) {
+ assert.equal(isSourcelessPostsChannel(other as never), false, JSON.stringify(other));
+ }
+ assert.match(SENTENCE, /^kettle-festival holds posts published from a private library: it has no account to fetch from/);
+});
+
+test("a direct ask is refused with the sentence: fetch-posts, capture-posts, the availability check, an X run", async () => {
+ const fetched = await fetchPosts({ paths, slug: "kettle-festival", settings } as never);
+ assert.deepEqual([fetched.ok, fetched.error, fetched.written], [false, SENTENCE, 0]);
+ for (const extra of [{}, { full: true }, { limit: 5 }]) {
+ const r = await fetchPosts({ paths, slug: "kettle-festival", settings, ...extra } as never);
+ assert.equal(r.error, SENTENCE);
+ }
+ for (const extra of [{}, { avatarsOnly: true }, { contextOnly: true }, { force: true, thread: true }]) {
+ const captured = await capturePosts({ paths, slug: "kettle-festival", settings, ids: ["801"], ...extra } as never);
+ assert.deepEqual([captured.ok, captured.error, captured.outcomes], [false, SENTENCE, []], JSON.stringify(extra));
+ }
+ for (const mode of ["stale", "all"]) {
+ const checked = await checkPostAvailability({ paths, slug: "kettle-festival", mode } as never);
+ assert.deepEqual([checked.ok, checked.error, checked.checked], [false, SENTENCE, 0]);
+ }
+ const run = await planXRun(paths, { channels: ["teapot-x", "kettle-festival"] });
+ assert.deepEqual(run, { ok: false, error: SENTENCE });
+ assert.equal(fetcherCalls, 0, "no fetcher was called");
+ assert.equal(existsSync(TOUCHED), false, "no binary was run");
+});
+
+test("where channels are listed it is left out, with its reason: an X run's candidates, Sync all", async () => {
+ assert.equal(isXPostsChannel(PUBLISHED), false);
+ assert.deepEqual((await listXRunCandidates(paths)).map((c) => c.slug), ["teapot-x"]);
+ assert.equal(syncSkipForShape(PUBLISHED), "published posts: no account to fetch from");
+ assert.equal(syncSkipForShape({ handling: "transcribe" } as never), "no url");
+ assert.equal(syncSkipForShape({ url: "https://example.org/c", remoteOnly: true } as never), "remote-only");
+ assert.equal(syncSkipForShape({ url: "https://x.com/teapot_news", sourceKind: "social", platform: "twitter" }), null);
+ assert.equal(fetcherCalls, 0);
+ assert.equal(existsSync(TOUCHED), false);
+});
diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts
@@ -61,6 +61,7 @@ import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/ne
import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap";
import { requestChannelSnapshot } from "../jobs/snapshotScheduler";
import { fetchPosts } from "./fetchPosts";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts";
export const X_RUN_JOB_KIND = "x-run";
// X's platform queue: the run serialises with every other X job (a channel's
@@ -321,7 +322,9 @@ export function isXPostsChannel(config: ConfigLike | null | undefined): boolean
config.platform === "twitter" &&
!isWaybackPagesChannel(config as Parameters<typeof isWaybackPagesChannel>[0]) &&
// A trending library has nothing an X run can fetch.
- !isXTrendingChannel(config as Parameters<typeof isXTrendingChannel>[0])
+ !isXTrendingChannel(config as Parameters<typeof isXTrendingChannel>[0]) &&
+ // Nor have posts published from one: no account, no search.
+ !isSourcelessPostsChannel(config as Parameters<typeof isSourcelessPostsChannel>[0])
);
}
@@ -442,6 +445,7 @@ export async function planXRun(paths: Paths, req: XRunRequest, now = Date.now())
if (slugs.includes(s)) return { ok: false, error: `"${s}" is named twice.` };
const config = await readChannelConfig(paths, s);
if (!config) return { ok: false, error: `No such channel: ${s}` };
+ if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(s) };
if (!isXPostsChannel(config)) return { ok: false, error: `${s} is not an X posts channel.` };
slugs.push(s);
}
diff --git a/common/controller/xTrendingGuards.test.ts b/common/controller/xTrendingGuards.test.ts
@@ -38,7 +38,10 @@ test("fetch-posts refuses a library with a sentence, before any fetcher is asked
test("the X run never lists a library among the X posts channels", () => {
assert.equal(isXPostsChannel(LIBRARY as never), false);
- assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), true);
+ assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/teapot_news", socialHandle: "teapot_news" } as never), true);
+ // With no account at all it is posts published from a library (lane
+ // x-trending-publish): nothing an X run can fetch either.
+ assert.equal(isXPostsChannel({ handling: "transcribe", sourceKind: "social", platform: "twitter" } as never), false);
});
test("read-x-trending: a network kind on X's queue that nothing replays or resumes; reparse asks nothing", () => {
diff --git a/common/lib/sourcelessPosts.ts b/common/lib/sourcelessPosts.ts
@@ -0,0 +1,37 @@
+// A POSTS CHANNEL WITH NO SOURCE (lane x-trending-publish): an X posts
+// channel that names no account, no search and no page — nothing to fetch.
+// Its posts were PUT there: a topic of a private library, published by the
+// operator (controller/publishXTrending.ts). The channel carries no mark of
+// that; it is told by its shape alone, and by this one predicate.
+//
+// SUCH A CHANNEL MAKES NO REQUEST ANYWHERE: fetch-posts, an X run, Sync all,
+// capture-posts and the availability check skip it where they list channels
+// and refuse it, with the sentence below, when asked for it by name. It is an
+// ordinary channel otherwise: indexed, built, and put on a site by the
+// operator's own act. A LEAF: types only.
+
+import { isRemoteOnlyChannel, isSocialChannel, type ChannelConfig } from "./channelConfig";
+
+type Shape = Pick<ChannelConfig, "sourceKind" | "platform"> &
+ Partial<Pick<ChannelConfig, "url" | "socialHandle" | "postFetcher" | "xSearch" | "xTrending" | "wayback" | "remoteOnly">>;
+
+export function isSourcelessPostsChannel(config: Shape | null | undefined): boolean {
+ if (!config || !isSocialChannel(config) || config.platform !== "twitter") return false;
+ if (config.url || config.socialHandle || config.postFetcher) return false;
+ if (config.xSearch || config.xTrending || config.wayback) return false;
+ return !isRemoteOnlyChannel(config);
+}
+
+// What it is, wherever a fetch, a capture or Configure is asked of it.
+export const SOURCELESS_POSTS_CHANNEL = (slug: string) =>
+ `${slug} holds posts published from a private library: it has no account to fetch from, and nothing is asked of X for it.`;
+
+// WHY SYNC ALL SKIPS A CHANNEL FOR WHAT IT IS (its shape, before its state):
+// the reason the bulk bar shows, or null. Published posts are named as such,
+// not as a channel somebody forgot to give a URL.
+export function syncSkipForShape(config: (Shape & Pick<ChannelConfig, "remoteOnly">) | null | undefined): string | null {
+ if (isSourcelessPostsChannel(config)) return "published posts: no account to fetch from";
+ if (!config?.url) return "no url";
+ if (isRemoteOnlyChannel(config)) return "remote-only";
+ return null;
+}
diff --git a/common/lib/xTrending/published.ts b/common/lib/xTrending/published.ts
@@ -0,0 +1,68 @@
+// WHAT A LIBRARY HAS PUBLISHED (lane x-trending-publish, slice 4):
+//
+// channels/<lib>/trending/published.json topic id → {slug, firstAt,
+// lastAt, posts: {post id → when it was published}}
+//
+// THE RECORD IS THE LIBRARY'S, AND THE ONLY ONE. The channel a topic is
+// published into carries no mark of it: nothing in that channel names the
+// library, a judgement, a note or a watch. "This channel was made by this
+// publish" is therefore answered from here, and from the channel's own
+// content (controller/publishXTrending.ts, the three-part proof).
+//
+// `slug` is fixed at the first publish: renaming the topic afterwards does
+// not fork its channel. `posts` is written BEFORE the posts are, so at any
+// moment the channel holds no post this record does not name.
+//
+// A library file like judgements.json: behind every door, never in a build.
+// ONE WRITER (this module), under the file's lock. SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
+
+const TRENDING_DIRNAME = "trending";
+export const X_TRENDING_PUBLISHED_FILENAME = "published.json";
+
+export type XTrendingPublishedTopic = {
+ slug: string;
+ firstAt: string;
+ lastAt: string;
+ posts: Record<string, string>;
+};
+
+type PublishedFile = { version: 1; topics: Record<string, XTrendingPublishedTopic> };
+
+export function xTrendingPublishedPath(channelRoot: string): string {
+ return path.join(channelRoot, TRENDING_DIRNAME, X_TRENDING_PUBLISHED_FILENAME);
+}
+
+const str = (v: unknown): v is string => typeof v === "string" && v !== "";
+const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+export async function readXTrendingPublished(channelRoot: string): Promise<Record<string, XTrendingPublishedTopic>> {
+ const read = await readJsonFile(xTrendingPublishedPath(channelRoot));
+ const topics = read.ok ? (read.value as { topics?: unknown } | null)?.topics : null;
+ const out: Record<string, XTrendingPublishedTopic> = {};
+ if (!topics || typeof topics !== "object" || Array.isArray(topics)) return out;
+ for (const [id, raw] of Object.entries(topics as Record<string, Partial<XTrendingPublishedTopic> | null>)) {
+ if (!id || !raw || typeof raw !== "object" || !str(raw.slug) || !SLUG.test(raw.slug) || raw.slug === "..") continue;
+ const posts: Record<string, string> = {};
+ if (raw.posts && typeof raw.posts === "object" && !Array.isArray(raw.posts)) {
+ for (const [post, at] of Object.entries(raw.posts)) if (/^\d+$/.test(post) && str(at)) posts[post] = at;
+ }
+ out[id] = { slug: raw.slug, firstAt: str(raw.firstAt) ? raw.firstAt : "", lastAt: str(raw.lastAt) ? raw.lastAt : "", posts };
+ }
+ return out;
+}
+
+// Every write: the file read under its lock, changed, written.
+export async function mutateXTrendingPublished<T>(
+ channelRoot: string,
+ change: (topics: Record<string, XTrendingPublishedTopic>) => { write: boolean; result: T },
+): Promise<T> {
+ return withJsonFileLock(xTrendingPublishedPath(channelRoot), async () => {
+ const topics = await readXTrendingPublished(channelRoot);
+ const { write, result } = change(topics);
+ if (write) await writeJsonAtomic(xTrendingPublishedPath(channelRoot), { version: 1, topics } satisfies PublishedFile, { mkdir: true });
+ return result;
+ });
+}
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -23,6 +23,7 @@ import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config";
import { isXTrendingChannel, X_TRENDING_NOT_FETCHED } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-transcript-common/lib/sourcelessPosts";
import { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store";
import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements";
import { refuseWatchJob } from "yt-dlp-transcript-common/controller/xTrendingWatch";
@@ -152,6 +153,8 @@ export async function checkPostAvailabilityAction(
if (!isSocialChannel(config)) {
return { ok: false, error: `${slug} is not a social channel.` };
}
+ // Posts published from a private library: nothing is asked of X for them.
+ if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) };
const key = resolveQueueKey(downloadQueueKey(config), queueKey);
return runManagedFunction({
kind: "check-post-availability",
@@ -246,6 +249,8 @@ export async function fetchPostsAction(
if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED };
// An X trending library has no timeline: its pages are read one at a time.
if (isXTrendingChannel(config)) return { ok: false, info: true, error: X_TRENDING_NOT_FETCHED(slug) };
+ // Posts published from a private library: no account to fetch from.
+ if (isSourcelessPostsChannel(config)) return { ok: false, info: true, error: SOURCELESS_POSTS_CHANNEL(slug) };
// An X search channel's one walk is its search windows (release 38).
if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL };
if (backfill) {
@@ -384,6 +389,8 @@ export async function capturePostsAction(
if (!isSocialChannel(config)) {
return { ok: false, error: `${slug} is not a social channel.` };
}
+ // Posts published from a private library: their captures came with them.
+ if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) };
// A Wayback pages channel has no fetcher: its records are rendered from
// their captures, on archive.org's queue (release 37 S4).
const pages = isWaybackPagesChannel(config);
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -43,6 +43,7 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site";
import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config";
import { X_TRENDING_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/xTrending/config";
+import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL, syncSkipForShape } from "yt-dlp-transcript-common/lib/sourcelessPosts";
import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings";
import {
LANES,
@@ -390,6 +391,10 @@ export async function updateChannelAction(
: `${slug} is not an X trending library, and Configure cannot make it one: create a new channel with platform "X trending library".`;
const asked = libraryProblem(String(formData.get("platform") ?? "") === "x-trending");
if (asked) return { error: asked, values };
+ // Posts published from a private library (lane x-trending-publish): the
+ // channel has no account, and the form's "a social source needs an account
+ // handle" would be the wrong thing to say of it.
+ if (isSourcelessPostsChannel(existing)) return { error: `${SOURCELESS_POSTS_CHANNEL(slug)} Configure has nothing to set for it; sites carry it like any channel (/sites).`, values };
let parsed;
try {
parsed = parseChannelForm(formData, { stored: existing });
@@ -673,7 +678,8 @@ export async function syncAllChannelsAction(
// successful sweep over a channel nothing could read.
skip: async (slug) => {
const config = bySlug.get(slug);
- if (!config?.url) return "no url";
+ const shape = syncSkipForShape(config);
+ if (shape) return shape;
if (isRemoteOnlyChannel(config)) return "remote-only";
if (isChannelPaused(priority, slug, "sync")) return "paused for sync";
if (active.has(slug)) return "already running";