// 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//`: 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 itself — a PROOF IN FOUR PARTS, 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; // 4. it is the very DIRECTORY this publish made (its inode and birth time, // kept in the record): a channel deleted and made again by hand, even of // the same shape and empty, is another one. // A channel that fails it is refused; a slug that is free is simply made // (again), and only where no directory of that name is left. // // 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, readdir, 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, type XTrendingPublishedIdentity, type XTrendingPublishedTopic } from "../lib/xTrending/published"; import { removeMediaFile } from "../lib/mediaTier-server"; import { listSites } from "../lib/site"; import { siteCitableChannelSlugs } from "../lib/siteSchema"; import { listXTrending, readXTrendingMembership, readXTrendingPosts, readXTrendingTopics, resolveXTrendingTopic, xTrendingTitleFrom, type XTrendingTitleFrom, xTrendingPostsMediaDir, xTrendingPostsRoot, } from "../lib/xTrending/store"; import { fileDigest, postCaptureDir, postsMediaDir, readPostCapture, writePostCapture, type ArticleCaptureRecord, type CapturedFile, type PostCaptureRecord, type PostContextPost, type ThreadCaptureRecord, } 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` 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, instagram: false, // Derived at index time from the availability sidecar, never stored. isDeleted: false, availability: false, availabilityCheckedAt: false, } as const satisfies Record; 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 = {}; for (const key of PUBLISHED_POST_FIELDS) { const value = (stored as unknown as Record)[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 === "structured" || a.extraction === "fallback" ? { 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; const quoted = contextPostOf(ctx?.quoted); const parent = contextPostOf(ctx?.parent); const parentFrom = (ctx?.parent as { from?: unknown } | undefined)?.from; const redaction = threadFile && record.thread ? redactionOf(record.thread.redaction) : undefined; return { version: 1, id: record.id, url: record.url, capturedAt: record.capturedAt, state: record.state, ...(record.sensitive ? { sensitive: true } : {}), ...(shot ? { shot } : {}), ...(shot && (record.shotScope === "item" || record.shotScope === "page") ? { shotScope: record.shotScope } : {}), ...(shot && record.trimmed ? { trimmed: true } : {}), mediaState: record.mediaState, media, ...(article ? { article } : {}), ...(threadFile && record.thread && redaction ? { thread: { ...threadFile, parentId: String(record.thread.parentId), ...(typeof record.thread.parentHandle === "string" ? { parentHandle: record.thread.parentHandle } : {}), ...(typeof record.thread.parentAuthor === "string" ? { parentAuthor: record.thread.parentAuthor } : {}), parentVerified: record.thread.parentVerified === true, ...(BADGES.includes(record.thread.parentBadge as never) ? { parentBadge: record.thread.parentBadge } : {}), parentFrom: record.thread.parentFrom === "above" ? "above" : "reply-to", redaction, }, } : {}), ...(typeof record.threadNone === "string" ? { threadNone: record.threadNone } : {}), ...(ctx && typeof ctx === "object" && typeof ctx.readAt === "string" ? { context: { readAt: ctx.readAt, ...(quoted ? { quoted } : {}), ...(parent ? { parent: { ...parent, from: parentFrom === "above" ? ("above" as const) : ("reply-to" as const) } } : {}), }, } : {}), }; } const BADGES = ["blue", "gold", "grey", "other"] as const; const REDACTION_REASONS = ["private", "blue-check", "verified", "self", "off", "forced"] as const; const REDACTED_WHAT = ["avatar", "name", "user-name", "mention"] as const; // A CONTEXT POST, FIELD BY FIELD (review 1): the quoted post or the parent as // the capture read it off the page. A key this does not name is not copied. function contextPostOf(raw: unknown): PostContextPost | undefined { if (!raw || typeof raw !== "object") return undefined; const r = raw as Record; if (typeof r.text !== "string") return undefined; const media = (Array.isArray(r.media) ? r.media : []) .filter((m): m is { kind: "image" | "video"; url: string } => !!m && typeof m === "object" && (m.kind === "image" || m.kind === "video") && typeof m.url === "string") .map((m) => ({ kind: m.kind, url: m.url })); return { ...(typeof r.id === "string" ? { id: r.id } : {}), ...(typeof r.url === "string" ? { url: r.url } : {}), ...(typeof r.handle === "string" ? { handle: r.handle } : {}), ...(typeof r.author === "string" ? { author: r.author } : {}), ...(typeof r.verified === "boolean" ? { verified: r.verified } : {}), ...(BADGES.includes(r.badge as never) ? { badge: r.badge as PostContextPost["badge"] } : {}), ...(typeof r.date === "string" ? { date: r.date } : {}), text: r.text, media, }; } // A thread shot's redaction, field by field: whether, why, and the boxes. function redactionOf(raw: unknown): ThreadCaptureRecord["redaction"] | undefined { if (!raw || typeof raw !== "object") return undefined; const r = raw as Record; if (!REDACTION_REASONS.includes(r.reason as never)) return undefined; const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); const boxes = (Array.isArray(r.boxes) ? r.boxes : []) .filter((b): b is { what: (typeof REDACTED_WHAT)[number]; box: Record } => !!b && typeof b === "object" && REDACTED_WHAT.includes(b.what as never) && !!b.box && typeof b.box === "object") .map((b) => ({ what: b.what, box: { x: num(b.box.x), y: num(b.box.y), width: num(b.box.width), height: num(b.box.height) } })); return { applied: r.applied === true, reason: r.reason as ThreadCaptureRecord["redaction"]["reason"], boxes }; } // ── 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; now?: number; }; export type PublishXTrendingResult = { dryRun: boolean; library: string; topic: { id: string; title: string }; // WHERE THE TOPIC'S NAME CAME FROM (review 1 S5): "page" — nobody named it // and it carries its trending page's title, X's words; "ask" or "rename" — // a person or an agent set it. Absent for the fallback name. The channel a // first publish makes is called by the topic's name. titleFrom?: XTrendingTitleFrom; // The channel the posts go into, and whether this publish makes it. channel: string; creates: boolean; // THE SITES THE CHANNEL IS ALREADY ON (review 1 S4): what is added to it // goes public at each one's next build. Empty for a channel on no site. sites: string[]; // 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; // Of the posts to add, those somebody MOVED into this topic (review 1 S5): // an agent may move posts, and a move changes what a publish takes. movedIn: Array<{ id: string; by: "agent" | "operator"; from: string }>; // Files to copy and their size (media, shots, an article's files). files: number; bytes: number; // Files whose bytes no longer match the digest their capture recorded // (review 1 S8): not copied, and no new digest is written for them. mismatched: Array<{ id: string; name: string }>; // 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, the channel put on a site): 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`; } // The digest a publish must carry: everything it would write, and where it // would become public. export function xTrendingPublishConfirm(o: { library: string; topic: string; channel: string; ids: ReadonlyArray; files: ReadonlyArray; sites?: ReadonlyArray; }): string { return createHash("sha256") .update(JSON.stringify([o.library, o.topic, o.channel, [...o.ids].sort(), [...o.files].sort(), [...(o.sites ?? [])].sort()])) .digest("hex") .slice(0, 24); } export function publishSentence(r: Omit): string { const would = r.dryRun; const where = r.creates ? `${would ? "would make" : "made"} the channel "${r.channel}"${r.sites.length ? "" : ", 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.`; // WHERE IT GOES PUBLIC: said first after the count, in so many words. const sites = r.sites.length && (r.posts > 0 || r.files > 0) ? ` THIS CHANNEL IS ON ${r.sites.length === 1 ? "THE SITE" : "THE SITES"} ${r.sites.join(", ")}: ${r.posts === 1 && r.files === 0 ? "this post goes" : "these posts go"} public at ${r.sites.length === 1 ? "its" : "their"} next build.` : ""; const agents = r.movedIn.filter((m) => m.by === "agent").length; const moved = r.movedIn.length ? ` ${n(r.movedIn.length, "post")} to publish ${r.movedIn.length === 1 ? "was" : "were"} moved into this topic: ${agents} by an agent, ${r.movedIn.length - agents} by the operator.` : ""; 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 bad = r.mismatched.length ? ` ${n(r.mismatched.length, "file")} no longer ${r.mismatched.length === 1 ? "matches" : "match"} the digest ${r.mismatched.length === 1 ? "its" : "their"} capture recorded and ${r.mismatched.length === 1 ? "is" : "are"} not copied (${r.mismatched.slice(0, 3).map((m) => `${m.id}/${m.name}`).join(", ")}${r.mismatched.length > 3 ? ", …" : ""}).` : ""; 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).` : ""; // A channel about to be made under X's own words for the page (review 1 S5). const named = r.creates && r.titleFrom === "page" ? ` The topic is named by X's page: "${r.topic.title}" — the channel ${would ? "would carry" : "carries"} that name. ` + (would ? `Rename the topic first to publish under your own name; "channel" names another slug than "${r.channel}".` : "A rename of the channel is its own step.") : ""; const copies = r.files > 0 ? " The files are copies: the library keeps its own." : ""; const site = r.creates && !would && r.sites.length === 0 ? " 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}${named}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; } // ── the plan ─────────────────────────────────────────────────────────────── type PlannedFile = { id: string; name: string; from: string; to: string; bytes: number; sha256: string }; type Plan = { channelRoot: string; creates: boolean; // An interrupted publish's channel, holding nothing yet: its directory is // recorded by this one. adopts: boolean; sites: string[]; kept: string[]; fresh: Post[]; movedIn: PublishXTrendingResult["movedIn"]; already: number; files: PlannedFile[]; mismatched: Array<{ id: string; name: string }>; // Kept posts with a readable capture record. captured: Map; textOnly: string[]; noLongerKept: string[]; }; type Fail = { ok: false; error: string }; async function isRegularFileInside(file: string, root: string): Promise<{ size: number; mtimeMs: number; ino: 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) ? { size: st.size, mtimeMs: st.mtimeMs, ino: st.ino } : null; } // Which directory a channel is, or null when there is none. async function identityOf(dir: string): Promise { const st = await lstat(dir).catch(() => null); return st?.isDirectory() ? { ino: st.ino, birthtimeMs: st.birthtimeMs } : null; } // The same directory: the inode, and the birth time where the file system // keeps one (an inode number is reused once its directory is gone; a birth // time is not. A file system that keeps none answers 0, and is not asked). function sameIdentity(a: XTrendingPublishedIdentity, b: XTrendingPublishedIdentity): boolean { if (a.ino !== b.ino) return false; return a.birthtimeMs > 0 && b.birthtimeMs > 0 ? a.birthtimeMs === b.birthtimeMs : true; } // The digest each file's capture record states, by name (64 hex only). function recordedDigests(record: PostCaptureRecord): Map { const out = new Map(); const take = (f: CapturedFile | undefined) => { if (f && typeof f.name === "string" && typeof f.sha256 === "string" && /^[0-9a-f]{64}$/.test(f.sha256)) out.set(f.name, f.sha256); }; take(record.shot); take(record.thread); for (const f of Array.isArray(record.media) ? record.media : []) take(f); for (const f of Array.isArray(record.article?.files) ? record.article!.files : []) take(f); return out; } // The sites whose build would carry this channel: as a member, or as a cited // channel (its cited posts). function sitesCarrying(paths: Paths, channel: string): string[] { return listSites(paths) .filter((site) => siteCitableChannelSlugs(site).has(channel)) .map((site) => site.siteId) .sort(); } // EVERYTHING A PUBLISH WOULD WRITE, READ FROM DISK AS IT STANDS: the channel // and whether it is this publish's, the sites it is on, the judgements in // force, the membership (and who moved what), the captures and their bytes. // Asked for the dry run, again before the write, and AGAIN INSIDE THE MEDIA // INDEX'S LOCK immediately before the first write, each time from disk: the // digest's inputs are all read here, so a judgement, a move or a site written // in between changes it. async function plan( paths: Paths, o: { library: string; libRoot: string; topicId: string; channel: string; record: XTrendingPublishedTopic | undefined; digests: Map }, ): Promise<{ ok: true; plan: Plan } | Fail> { const channelRoot = path.join(paths.channelsDir, o.channel); const recorded = o.record?.posts; const here = await identityOf(channelRoot); const exists = await channelExists(paths, o.channel); let have = new Set(); let adopts = false; // S3: a publish MAKES a channel only where no directory of that name is. if (!exists && (await lstat(channelRoot).catch(() => null)) !== null) { return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "a directory of that name is there, with no channel in it") }; } if (exists) { // THE PROOF, in four parts. if (!o.record || !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) => !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`) }; } // S2: the very directory this publish made. A channel deleted and made // again, of the same shape and even empty, is another directory. if (o.record.identity) { if (!here || !sameIdentity(o.record.identity, here)) { return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "it is not the channel this publish made: that one was removed, and this one was made since") }; } } else if (o.record.pending && have.size === 0) { // A publish that was cut after making the channel and before saying // which directory it was: it holds nothing yet, and is taken up. adopts = true; } else { return { ok: false, error: NOT_THIS_PUBLISHS_CHANNEL(o.channel, "the library's record does not say which channel it made") }; } } const [listing, stored, membership] = await Promise.all([ listXTrending(o.libRoot, { topic: o.topicId, ids: true, filter: { state: "keep", by: "operator" } }), readXTrendingPosts(o.libRoot), readXTrendingMembership(o.libRoot), ]); const byId = new Map(stored.map((p) => [p.id, p])); // An id becomes a path below: digits, or it is not a post of X's. const kept = [...(listing.ids ?? [])].filter((id) => /^\d{1,32}$/.test(id)).sort(); const keptSet = new Set(kept); const fresh: Post[] = []; const movedIn: Plan["movedIn"] = []; const files: PlannedFile[] = []; const mismatched: Plan["mismatched"] = []; const captured = new Map(); 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 moved = membership[id]?.moved; if (moved) movedIn.push({ id, by: moved.by, from: moved.from }); } const from = postCaptureDir(libMedia, id); const record = await readPostCapture(from); if (!record || record.id !== id) { textOnly.push(id); continue; } captured.set(id, record); const stated = recordedDigests(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 src = path.join(from, name); const st = await isRegularFileInside(src, o.libRoot); if (st === null) continue; // The source's own digest, once per file per publish (three looks). const key = `${src}\0${st.ino}\0${st.size}\0${st.mtimeMs}`; let sha256 = o.digests.get(key); if (!sha256) { sha256 = (await fileDigest(src)).sha256; o.digests.set(key, sha256); } // S8: what the capture recorded of this file, when it recorded a // digest. Bytes that are no longer those are not published. const want = stated.get(name); if (want && want !== sha256) { mismatched.push({ id, name }); continue; } files.push({ id, name, from: src, to: path.join(to, name), bytes: st.size, sha256 }); } } const noLongerKept = Object.keys(recorded ?? {}).filter((id) => have.has(id) && !keptSet.has(id)).sort(); return { ok: true, plan: { channelRoot, creates: !exists, adopts, sites: sitesCarrying(paths, o.channel), kept, fresh, movedIn, already, files, mismatched, captured, textOnly, noLongerKept }, }; } const PART = /^\.publish-[0-9a-f]{12}\.part$/; // One file, copied: to a temp name beside its place, checked against the // digest its source had when it was planned, then renamed. Never a link. async function copyChecked(f: PlannedFile): Promise { 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 copy = await fileDigest(tmp); if (copy.sha256 !== f.sha256 || copy.bytes !== f.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; } } // What an interrupted copy left in a capture directory of the channel: its // own temp names, and nothing else. Under the lock, before a file is copied. async function sweepParts(dir: string): Promise { for (const name of await readdir(dir).catch(() => [] as string[])) { if (PART.test(name)) await removeMediaFile(dir, name); } } // ── 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 first0 = (await readXTrendingPublished(libRoot))[topic.id]; if (first0 && ask.channel !== undefined && ask.channel !== first0.slug) { return { ok: false, error: `"${topic.title}" is published into the channel "${first0.slug}": a topic has one channel, fixed at its first publish.` }; } const channel = first0?.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 digests = new Map(); // The record is read with each look: never the copy read above. const look = async () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, record: (await readXTrendingPublished(libRoot))[topic.id], digests }); 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}`), sites: p.sites }); const titleFrom = xTrendingTitleFrom(topic); const answer = (p: Plan, dryRun: boolean, inFlight: boolean): PublishXTrendingResult => { const r: Omit = { dryRun, library: ask.slug, topic: { id: topic.id, title: topic.title }, ...(titleFrom ? { titleFrom } : {}), channel, creates: p.creates, sites: p.sites, kept: p.kept.length, posts: p.fresh.length, ids: p.fresh.map((x) => x.id), already: p.already, movedIn: p.movedIn, files: p.files.length, bytes: p.files.reduce((a, f) => a + f.bytes, 0), mismatched: p.mismatched, 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 () => { // THE JUDGEMENTS, THE MEMBERSHIP, THE CAPTURES, THE RECORD AND THE SITES, // READ AGAIN HERE: what is written is what this look finds, and it must // be what the operator was shown. 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. A // channel about to be made has no directory to name yet: `pending`. await mutateXTrendingPublished(libRoot, (all) => { const have: XTrendingPublishedTopic = all[topic.id] ?? { slug: channel, firstAt: at, lastAt: at, posts: {} }; for (const post of p.fresh) have.posts[post.id] ??= at; have.lastAt = at; if (p.creates) { delete have.identity; have.pending = true; } all[topic.id] = have; return { write: true, result: undefined }; }); // 2. The channel, through its own writer: on no site. Then WHICH // DIRECTORY it is, into the record. if (p.creates) await createChannel(paths, channel, { name: topic.title, handling: "transcribe", sourceKind: "social", platform: "twitter" }); if (p.creates || p.adopts) { const made = await identityOf(p.channelRoot); if (!made) return { ok: false, error: `The channel "${channel}" could not be made.` }; await mutateXTrendingPublished(libRoot, (all) => { const have = all[topic.id]; if (!have) return { write: false, result: undefined }; have.identity = made; delete have.pending; return { write: true, result: undefined }; }); } // 3. The posts, through the posts store's writer. await writePosts(p.channelRoot, p.fresh); // 4. The files (an interrupted copy's temp names swept first), then each // capture's record. for (const id of p.captured.keys()) await sweepParts(postCaptureDir(postsMediaDir(p.channelRoot), id)); 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(); 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) }; }); }