// AN X TRENDING LIBRARY'S OWN FILES (lane x-trending, slice 1): // // channels//trending/posts/.jsonl its posts (a posts // channels//trending/posts-archive channel's format, kept // HERE: see xTrendingPostsRoot) // channels//trending/topics.json the operator's topics, each with // the trending pages read into it // and every read's id and time // channels//trending/membership.json post id → its topic, the reads // that showed it, its media by kind // channels//trending/reads// one read of one page, raw: // responses.jsonl every GraphQL JSON answer the page fetched // page.png the page as it stood when it had loaded // read.json the read's record: operation NAMES and SIZES only // // THE RAW CAPTURE IS PRIVATE AND STAYS HERE: it can hold other accounts' data // and fields bound to the reading session. No route serves `reads/`, nothing // indexes it, and the listing below never returns it. A post is parsed from // the saved file only (social/xTrendingParse.ts). // // THIS MODULE IS THE ONE WRITER of topics.json and membership.json; every // write goes through the file's lock (withJsonFileLock) and is atomic. A // re-read of a page adds posts and appends a read; it never drops a post, and // never moves one out of the topic it is in. Renaming and merging topics and // moving a post between them (lib/xTrending/organise.ts) write through // mutateXTrendingTopics / mutateXTrendingMembership here, under the same locks. // // The listing reads these files and the posts shards — never the index (the // library is in no index build). It is a plain module over the corpus on // disk, with no editor-only import, so umtool's Posts library page (slice 3) // reads a library exactly as the editor does. // // channels//trending/judgements.json post id → {state: "keep" | // "drop" | "later", note?, by: "agent" | "operator", at}, and the same // per THREAD (keyed by its root post's id). No entry = undecided. // Written by ONE writer, lib/xTrending/judgements.ts (the editor's // `judge-trending`); read here, so a row carries its judgement. // channels//trending/watch.json the watched topics // (lib/xTrending/watch.ts is its one writer) // channels//trending/posts-media// a captured post: its shot, its // capture.json and its media, each media file a HARDLINK to // channels//trending/media-store/ the library's media, once per // content hash, with media-index.json (lib/xTrending/mediaStore.ts) // // SERVER-ONLY (node:fs). import path from "node:path"; import { mkdir, readFile, readdir, stat } from "node:fs/promises"; import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; import type { Post, PostEngagement, PostRef } from "../posts"; import type { XTrendingRef } from "./config"; // (./watch imports only TYPES of this module: no cycle.) import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch"; export const TRENDING_DIRNAME = "trending"; export const TRENDING_READS_DIRNAME = "reads"; export const TRENDING_RESPONSES_FILENAME = "responses.jsonl"; export const TRENDING_PAGE_SHOT_FILENAME = "page.png"; // The page after the read pressed its second tab (or tried to). export const TRENDING_TAB_SHOT_FILENAME = "page-latest.png"; export const TRENDING_READ_FILENAME = "read.json"; export function trendingDir(channelRoot: string): string { return path.join(channelRoot, TRENDING_DIRNAME); } // WHERE A LIBRARY'S POSTS LIVE (review 1): `channels//trending/posts/` // and `trending/posts-archive` — a posts channel's own shard and archive // format, one directory down. NOT `channels//posts/`: every reader of a // posts channel (reports and drafts, research, umtool's post search and reels, // the index, the availability checks) looks there, and a library must be // offered to none of them until someone publishes posts out of it on purpose. // So to all of those a library is a channel with no posts, by construction; // the library's own readers and writers below are the only way in. export function xTrendingPostsRoot(channelRoot: string): string { return trendingDir(channelRoot); } export function readXTrendingPosts(channelRoot: string): Promise { return readAllPosts(xTrendingPostsRoot(channelRoot)); } export function readXTrendingPostIds(channelRoot: string): Promise> { return readSeenPostIds(xTrendingPostsRoot(channelRoot)); } // Month shards, deduped by id against the library's archive, as writePosts does. export function writeXTrendingPosts(channelRoot: string, posts: ReadonlyArray): Promise { return writePosts(xTrendingPostsRoot(channelRoot), posts); } const READ_ID = /^tr-[0-9A-Z]{26}$/; export function isXTrendingReadId(id: unknown): id is string { return typeof id === "string" && READ_ID.test(id); } // THE CAPTURES ARE NEVER COMMITTED (review 1). The corpus is its own git // repo, and a capture holds other people's data and fields bound to the // reading session: `trending/reads/.gitignore` ignores everything under it // (itself included), written whenever the reads directory is made. export const TRENDING_READS_GITIGNORE = "# Raw captures of X pages: private, never committed.\n*\n"; export async function ensureXTrendingReadsDir(channelRoot: string): Promise { const dir = path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME); await mkdir(dir, { recursive: true }); const ignore = path.join(dir, ".gitignore"); const have = await readFile(ignore, "utf8").catch(() => null); if (have !== TRENDING_READS_GITIGNORE) await writeFileAtomic(ignore, TRENDING_READS_GITIGNORE); return dir; } // One read's directory. The id is checked here, where it becomes a path. export function trendingReadDir(channelRoot: string, readId: string): string { if (!isXTrendingReadId(readId)) throw new Error(`"${readId}" is not a trending read id`); return path.join(trendingDir(channelRoot), TRENDING_READS_DIRNAME, readId); } function topicsPath(channelRoot: string): string { return path.join(trendingDir(channelRoot), "topics.json"); } function membershipPath(channelRoot: string): string { return path.join(trendingDir(channelRoot), "membership.json"); } export type XTrendingMediaKind = "image" | "video" | "gif"; export type XTrendingMedia = { count: number; kinds: XTrendingMediaKind[] }; function judgementsPath(channelRoot: string): string { return path.join(trendingDir(channelRoot), "judgements.json"); } // "later" is a decision put off by someone; no entry is a post nobody has // judged (undecided). Clearing a judgement removes the entry. export type XTrendingJudgementState = "keep" | "drop" | "later"; export const X_TRENDING_JUDGEMENT_STATES: readonly XTrendingJudgementState[] = ["keep", "drop", "later"]; export type XTrendingJudgement = { state: XTrendingJudgementState; note?: string; by: "agent" | "operator"; at: string; }; export type XTrendingJudgementsFile = { version: 1; posts: Record; // A thread's judgement, keyed by its root post's id: what a post of the // thread with no judgement of its own is taken to be. threads: Record; }; export function xTrendingJudgementsPath(channelRoot: string): string { return judgementsPath(channelRoot); } function parseJudgements(raw: unknown): Record { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const out: Record = {}; for (const [id, j] of Object.entries(raw as Record | null>)) { if (!/^\d+$/.test(id) || !j || typeof j !== "object") continue; if (!X_TRENDING_JUDGEMENT_STATES.includes(j.state as XTrendingJudgementState)) continue; if ((j.by !== "agent" && j.by !== "operator") || typeof j.at !== "string" || !j.at) continue; out[id] = { state: j.state as XTrendingJudgementState, ...(typeof j.note === "string" && j.note ? { note: j.note } : {}), by: j.by, at: j.at, }; } return out; } // judgements.json whole, or an empty one while there is none. Ill-shaped // entries are dropped. export async function readXTrendingJudgementsFile(channelRoot: string): Promise { const read = await readJsonFile(judgementsPath(channelRoot)); const value = read.ok ? (read.value as { posts?: unknown; threads?: unknown } | null) : null; return { version: 1, posts: parseJudgements(value?.posts), threads: parseJudgements(value?.threads) }; } // The posts' own judgements. export async function readXTrendingJudgements(channelRoot: string): Promise> { return (await readXTrendingJudgementsFile(channelRoot)).posts; } // WHICH JUDGEMENT IS IN FORCE FOR A POST — the ONE rule (review 2 N2), used by // the writer, the listing and everything that asks whether a post is kept: // // - the OPERATOR's entry always outranks an agent's about the same post, // whichever was written first and whichever is the post's own: an // operator's judgement of the thread stands over an agent's entry for one // of its posts; // - between two entries of the same hand (two of the operator's, or two of // an agent's), the post's own entry outranks its thread's. // // An agent's entry the operator's outranks stays in the file, as history; it // decides nothing. export function xTrendingEffectiveJudgement( own: XTrendingJudgement | undefined, thread: XTrendingJudgement | undefined, ): (XTrendingJudgement & { from?: "thread" }) | undefined { if (own && thread && own.by === "agent" && thread.by === "operator") return { ...thread, from: "thread" }; if (own) return own; return thread ? { ...thread, from: "thread" } : undefined; } // A THREAD'S KEY is its root post's id. The source's own `threadId` when it // names ANOTHER post (X's conversation id) — a normalized X post always has // one, and when the answer gave no conversation id it is the post's own id, // which says nothing (review 1). Then the chain of posts it answers, followed // through the library's posts as far as they go: the first ancestor the // library lacks is the root as far as anyone here knows. A post that answers // nothing is its own thread. // // DECIDED ONCE PER POST. The walk's answer moves as ancestors arrive, so a // post's key is computed when the post is first placed in a topic and kept in // its membership record (`thread`); everything that asks a post's thread asks // xTrendingThreadOf, which reads that record. export function xTrendingThreadKey(post: Post, byId: ReadonlyMap): string { const named = (p: Post) => (p.threadId && /^\d+$/.test(p.threadId) && p.threadId !== p.id ? p.threadId : undefined); const own = named(post); if (own) return own; let at = post; const walked = new Set([post.id]); for (let hops = 0; hops < 64; hops++) { const parent = at.replyTo?.id; if (!parent || !/^\d+$/.test(parent)) return at.id; const next = byId.get(parent); if (!next || walked.has(parent)) return parent; const theirs = named(next); if (theirs) return theirs; walked.add(parent); at = next; } return at.id; } // A post's thread: the key its membership record holds, else (a member placed // before keys were kept) the walk's answer now. export function xTrendingThreadOf( post: Post, membership: Readonly>, byId: ReadonlyMap, ): string { return membership[post.id]?.thread ?? xTrendingThreadKey(post, byId); } const IMAGE_FILE = /\.(?:jpe?g|png|webp|gif)$/i; // WHERE A LIBRARY'S CAPTURED MEDIA LIVES (review 2 N9): under trending/, as // its posts do — `channels//trending/posts-media//` — never in the // channel's own `posts-media/`, which umtool and the report media read for an // ordinary posts channel. Slice 2 writes it; this slice only looks. const LIBRARY_MEDIA_DIRNAME = "posts-media"; const LIBRARY_SHOT_FILENAME = "shot.png"; export function xTrendingPostsMediaDir(channelRoot: string): string { return path.join(trendingDir(channelRoot), LIBRARY_MEDIA_DIRNAME); } // A captured post's first picture, as a path relative to the channel // (`trending/posts-media//`): its first attached image, else its // screenshot. Undefined while the post has no capture (archiving is slice 2). export async function firstCapturedThumbnail(channelRoot: string, id: string): Promise { if (!/^\d+$/.test(id)) return undefined; let names: string[]; try { names = (await readdir(path.join(xTrendingPostsMediaDir(channelRoot), id))).sort(); } catch { return undefined; } const media = names.find((n) => IMAGE_FILE.test(n) && !n.startsWith("shot") && !n.startsWith("article")); const pick = media ?? (names.includes(LIBRARY_SHOT_FILENAME) ? LIBRARY_SHOT_FILENAME : undefined); return pick ? `${TRENDING_DIRNAME}/${LIBRARY_MEDIA_DIRNAME}/${id}/${pick}` : undefined; } // A captured post, as the listing says it: whether it was shot, how many media // files it holds, how its media half stands ("ok", "none", "skipped", // "error") and what it is owed ("next": a later capture asks again; "kept": // once the post is marked keep). export type XTrendingCaptureSummary = { at: string; state: string; shot: boolean; files: number; mediaState: string; mediaOwed?: "next" | "kept"; }; // capture.json of a library post, read as plain JSON (its writer is // social/postCapture.ts; this module imports nothing of social/). export async function xTrendingCaptureSummary(channelRoot: string, id: string): Promise { if (!/^\d+$/.test(id)) return undefined; const read = await readJsonFile(path.join(xTrendingPostsMediaDir(channelRoot), id, "capture.json")); const r = read.ok ? (read.value as Record | null) : null; if (!r || typeof r !== "object" || typeof r.capturedAt !== "string" || typeof r.state !== "string") return undefined; return { at: r.capturedAt, state: r.state, shot: !!r.shot, files: Array.isArray(r.media) ? r.media.length : 0, mediaState: typeof r.mediaState === "string" ? r.mediaState : "skipped", ...(r.mediaOwed === "next" || r.mediaOwed === "kept" ? { mediaOwed: r.mediaOwed } : {}), }; } export type XTrendingSourceRead = { // The read's id (`reads//`), when it ran, the posts it showed and how // many of them were new to the library. id: string; at: string; posts: number; added: number; // The tab of the page whose timeline the read saw (its label, as X shows // it), when the capture says which. A read sees ONE tab: the one the page // opens on. Absent for a read saved before tabs were read, until it is // parsed again, and for a capture whose page answer or timeline id is missing. tab?: string; // A read that covered several tabs (Top, then Latest): their labels. tabs?: string[]; }; // One tab of a trending page: its label and the timeline it lists. export type XTrendingTab = { label: string; timelineId: string }; // One trending page read into a topic. `title` and `summary` are X's own // words for the page, `lastUpdatedAt` when X last rewrote them and `tabs` the // page's tabs (lane x-followups): all as the LATEST read or reparse that // carried the page's own answer found them, and kept when a later capture // lacks it. export type XTrendingSource = { trendId: string; url: string; title?: string; summary?: string; lastUpdatedAt?: string; tabs?: XTrendingTab[]; reads: XTrendingSourceRead[]; }; // THE NAME A TOPIC IS BORN WITH when nobody named it and its page gave no // title: "Trending ". A topic still carrying it takes the // page's title at the next read or reparse that finds one (recordXTrendingRead). export function xTrendingFallbackTitle(trendId: string): string { return `Trending ${trendId}`; } // Who organised (renamed, merged, moved) and when: the caller's word, as a // judgement's `by` is (lib/xTrending/organise.ts). export type XTrendingOrganiseBy = "agent" | "operator"; export type XTrendingOrganised = { what: "rename" | "merge"; by: XTrendingOrganiseBy; at: string }; export type XTrendingTopic = { id: string; // The operator's name for it (X's title is the source's). title: string; createdAt: string; sources: XTrendingSource[]; // The ids of topics merged into this one (lane x-trending-publish): an ask // that still names one — a queued read, an old address — means this topic, // and never makes a new one. aliases?: string[]; // Its last rename or merge. organised?: XTrendingOrganised; // WHERE ITS NAME CAME FROM, in a field of its own that no merge or move // writes (review 1): "ask" — a read was asked to make it under that name; // "rename" — somebody renamed it; "page" — nobody named it and it took its // trending page's title. Absent: the fallback name, or a topic from before // this field (xTrendingTitleFrom reads those). A name that was SET ("ask", // "rename") is never changed by a read. titleFrom?: XTrendingTitleFrom; }; export type XTrendingTitleFrom = "page" | "ask" | "rename"; // Whether somebody set the topic's name. A topic from before `titleFrom`: a // rename is its last organise step, or its name is not a fallback name (it was // asked for: no read gave a topic a page's title then). export function xTrendingTopicNameIsSet(t: Pick): boolean { const from = xTrendingTitleFrom(t); return from === "ask" || from === "rename"; } // Where a topic's name came from; undefined for the fallback name. export function xTrendingTitleFrom(t: Pick): XTrendingTitleFrom | undefined { if (t.titleFrom) return t.titleFrom; if (t.organised?.what === "rename") return "rename"; if (/^Trending \d+$/.test(t.title) && (t.sources.length === 0 || t.sources.some((s) => t.title === xTrendingFallbackTitle(s.trendId)))) return undefined; return "ask"; } // One sighting: the read, the page, when, its rank on the page, and the tab // of the page that showed it (as XTrendingSourceRead.tab). export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number; tab?: string }; // GONE FROM THE PAGE (lane x-trending-2): a post a page showed before, absent // from a later read of that page that reached the page's end. It says what // the page showed and NOTHING about the post — a trending page is a ranked // list, and a post leaves it by being outranked as well as by being deleted. // A read that stopped at a cap, was cancelled or failed asserts nothing. export type XTrendingGone = { at: string; read: string; trendId: string }; export type XTrendingMember = { topic: string; // Its thread's key, decided when it was placed (xTrendingThreadKey). thread?: string; seen: XTrendingSeen[]; media?: XTrendingMedia; gone?: XTrendingGone; // GONE FROM ONE TAB (lane x-followups): per tab label ("" for a read that // could not say its tab), the read of that tab that reached its end and did // not show the post. `gone` above is set only when ONE read dropped the // post from every tab that showed it (review 2, ruling R-d); marks here from // different reads never add up to it. A mark alone means "gone from that // tab at