// ORGANISING A LIBRARY'S TOPICS (lane x-trending-publish, slice 4): rename a // topic, merge topics into one, move posts between topics. // // RENAME changes a topic's title and nothing else: its id stays, so its // watch, the judge view's marks and addresses keep meaning it. REFUSED WHILE // A READ OR A REPARSE OF THE LIBRARY IS QUEUED OR RUNNING, as a merge is: a // read may have been asked for by the topic's NAME, and would make a new // topic of the old name when it records. // // MOVE sets the topic of posts (by id, or a whole thread) under the // membership file's lock. It is SAFE BESIDE A READ OR A CAPTURE and is not // refused for one: a read never moves a post that has a place // (recordXTrendingRead), and a capture writes neither file. Judgements are // keyed by post and by thread, never by topic, so they travel untouched; so // do "gone from the page" marks (they are about the page, not the topic). // // MERGE puts every page, read and post of the `from` topics into `into`, and // removes them. THERE IS NO UNMERGE, so it is the OPERATOR's: an agent's ask // is refused. It is REFUSED WHILE A READ OR A REPARSE OF THE LIBRARY IS QUEUED // OR RUNNING (the caller answers that from its job registry): a queued watch // tick names its topic by id. As a second line, the merged topics' ids stay on // the target as `aliases`, so an ask that still names one means the target // and never makes a topic again (store.ts resolveXTrendingTopic). // // posts every member of a `from` topic → `into` // pages `into`'s sources, then each `from` topic's; the same page in // two topics becomes one, its reads joined by read id // judgements untouched (not keyed by topic) // published a topic has ONE channel (lib/xTrending/published.ts). The // target's record stays; when it has none, the first merged // topic's becomes its own. Any other merged topic's channel // is left as it is and never added to again; the sentence // names it. // watches ONE stands. `into`'s live watch stands with its own terms; // when `into` has none, the first `from` topic's live watch // moves to it. Every other watch entry goes. The standing // watch now reads all the pages in turn (its turn starts // over); pages X answered "gone" for stay unread. // // Written in an order a second run completes: the membership, the watches, // the publish records, then topics.json — all inside the topics file's lock, so no read records // between them. SERVER-ONLY (node:fs). import type { Post } from "../posts"; import { mutateXTrendingMembership, mutateXTrendingTopics, readXTrendingMembership, readXTrendingPosts, resolveXTrendingTopic, topicIdFromTitle, topicTitleProblem, xTrendingThreadOf, type XTrendingOrganiseBy, type XTrendingSource, type XTrendingTopic, } from "./store"; import { mutateXTrendingPublished } from "./published"; import { describeXTrendingWatch, mutateXTrendingWatches, watchIsLive, type XTrendingWatch } from "./watch"; export const X_TRENDING_MOVE_MAX = 500; export const X_TRENDING_MERGE_MAX = 20; export const MERGE_IS_THE_OPERATORS = `Merging topics is the operator's press: it cannot be undone (there is no unmerge). The operator merges on umtool's Posts library page, ` + `or with "by": "operator". An agent may rename a topic and move posts between topics.`; export const MERGE_WAITS_FOR_READS = "A read of this library is queued or running: merge its topics once it has finished (its job is on /jobs). A queued read names its topic, and a merge would take that topic away under it."; const none = (topics: ReadonlyArray) => topics.map((t) => t.id).join(", ") || "none yet"; const noTopic = (asked: string, topics: ReadonlyArray) => `This library has no topic "${asked}" (its topics: ${none(topics)}).`; const n = (k: number, what: string) => `${k} ${what}${k === 1 ? "" : "s"}`; function byProblem(by: unknown): string | null { return by === "agent" || by === "operator" ? null : `"by" is "agent" or "operator"`; } export type Refused = { ok: false; error: string }; // ── rename ───────────────────────────────────────────────────────────────── export type XTrendingRenameResult = { ok: true; op: "rename"; topic: string; title: string; was: string; changed: boolean; sentence: string } | Refused; export const RENAME_WAITS_FOR_READS = "A read of this library is queued or running: rename its topic once it has finished (its job is on /jobs). A read names its topic, by id or by name, and a name changed under it could send its posts to a new topic."; export async function renameXTrendingTopic( channelRoot: string, ask: { topic: string; title: string; by: XTrendingOrganiseBy; // A read or a reparse of this library queued or running (required, so no // door can forget it): a read asked for by a topic's NAME finds its topic // by that name when it records (review 1 S9). readInFlight: () => boolean | Promise; now?: number; }, ): Promise { const bad = byProblem(ask.by) ?? (typeof ask.topic !== "string" || !ask.topic.trim() ? `"topic" is the topic's id` : null); if (bad) return { ok: false, error: bad }; if (typeof ask.title !== "string" || !ask.title.trim()) return { ok: false, error: `"title" is the topic's new name` }; const problem = topicTitleProblem(ask.title); if (problem) return { ok: false, error: problem }; const title = ask.title.trim(); const at = new Date(ask.now ?? Date.now()).toISOString(); if (await ask.readInFlight()) return { ok: false, error: RENAME_WAITS_FOR_READS }; return mutateXTrendingTopics(channelRoot, async (topics) => { const topic = resolveXTrendingTopic(topics, ask.topic); if (!topic) return { write: false, result: { ok: false, error: noTopic(ask.topic, topics) } }; // Asked again inside the lock: a read queued since the first look. if (await ask.readInFlight()) return { write: false, result: { ok: false, error: RENAME_WAITS_FOR_READS } }; // A name another topic answers to (its title, its id, an id merged into // it) would make "which topic" depend on the order of the file. const other = resolveXTrendingTopic(topics.filter((t) => t !== topic), title); if (other) { return { write: false, result: { ok: false, error: `Topic "${other.title}" (${other.id}) already answers to "${title}": a topic's name is its own. Merge the two, or choose another name.` } }; } const was = topic.title; if (was === title) { return { write: false, result: { ok: true, op: "rename", topic: topic.id, title, was, changed: false, sentence: `Topic ${topic.id} is already named "${title}".` } }; } topic.title = title; topic.organised = { what: "rename", by: ask.by, at }; // Its own field: a merge into this topic overwrites `organised`, and a // read must still know the name was set. topic.titleFrom = "rename"; return { write: true, result: { ok: true, op: "rename", topic: topic.id, title, was, changed: true, sentence: `Topic "${was}" is now "${title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }, }; }); } // ── move ─────────────────────────────────────────────────────────────────── export type XTrendingMoveResult = | { ok: true; op: "move"; to: { id: string; title: string; created: boolean }; moved: string[]; skipped: Array<{ id: string; reason: string }>; sentence: string; } | Refused; export async function moveXTrendingPosts( channelRoot: string, ask: { to: string; ids?: ReadonlyArray; thread?: string; // `to` may name a topic that does not exist yet: it is made, with no page. create?: boolean; by: XTrendingOrganiseBy; now?: number; posts?: ReadonlyArray; // A test's seam: called after a topic made for this move is on disk and // before any post is put in it. betweenWrites?: () => void | Promise; }, ): Promise { const bad = byProblem(ask.by); if (bad) return { ok: false, error: bad }; if (typeof ask.to !== "string" || !ask.to.trim()) return { ok: false, error: `"to" is the topic the posts go to` }; const hasIds = ask.ids !== undefined; const hasThread = ask.thread !== undefined; if (hasIds === hasThread) return { ok: false, error: `a move names posts ("ids") or one thread ("thread"), one of them` }; if (hasIds && (!Array.isArray(ask.ids) || ask.ids.length === 0 || !ask.ids.every((id) => typeof id === "string" && /^\d+$/.test(id)))) { return { ok: false, error: `"ids" is a list of post ids` }; } if (hasIds && ask.ids!.length > X_TRENDING_MOVE_MAX) return { ok: false, error: `"ids" holds at most ${X_TRENDING_MOVE_MAX} post ids` }; if (hasThread && (typeof ask.thread !== "string" || !/^\d+$/.test(ask.thread))) return { ok: false, error: `"thread" is a thread's root post id` }; const at = new Date(ask.now ?? Date.now()).toISOString(); // The thread's posts, by the key each was placed with. let wanted: string[] = hasIds ? [...new Set(ask.ids)] : []; if (hasThread) { const [membership, posts] = await Promise.all([readXTrendingMembership(channelRoot), ask.posts ?? readXTrendingPosts(channelRoot)]); // THE LISTING'S OWN RULE (store.ts listXTrending): every member's key is // the one kept in its membership record, else derived over ALL the // library's posts — so "the thread" here is the thread the page shows. const archived = new Map(posts.map((p) => [p.id, p])); wanted = Object.keys(membership).filter((id) => { const post = archived.get(id); return !!post && xTrendingThreadOf(post, membership, archived) === ask.thread; }); if (wanted.length === 0) return { ok: false, error: `This library has no thread "${ask.thread}".` }; } return mutateXTrendingTopics(channelRoot, async (topics, save) => { let target = resolveXTrendingTopic(topics, ask.to); let created = false; if (!target) { if (!ask.create) return { write: false, result: { ok: false, error: `${noTopic(ask.to, topics)} To move posts into a new topic, say "create": true.` } }; const problem = topicTitleProblem(ask.to); if (problem) return { write: false, result: { ok: false, error: problem } }; const title = ask.to.trim(); const base = topicIdFromTitle(title) || "topic"; let id = base; for (let k = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); k++) id = `${base}-${k}`; target = { id, title, createdAt: at, sources: [], titleFrom: "ask" }; topics.push(target); created = true; // THE TOPIC FIRST, THEN THE POSTS (review 1 S6): cut between the two // writes, the library holds an empty topic — never a post whose topic // does not exist. await save(); await ask.betweenWrites?.(); } const to = target; const out = await mutateXTrendingMembership(channelRoot, (members) => { const moved: string[] = []; const skipped: Array<{ id: string; reason: string }> = []; for (const id of wanted) { const m = members[id]; if (!m) skipped.push({ id, reason: "not in this library" }); else if (m.topic === to.id) skipped.push({ id, reason: `already in "${to.title}"` }); else { m.moved = { from: m.topic, by: ask.by, at }; m.topic = to.id; moved.push(id); } } return { write: moved.length > 0, result: { moved, skipped } }; }); // A topic made for a move that moved nothing is taken back. const unmade = created && out.moved.length === 0; if (unmade) topics.pop(); const skippedSentence = out.skipped.length ? ` ${n(out.skipped.length, "post")} skipped: ${out.skipped[0].reason}.` : ""; return { write: unmade, result: { ok: true, op: "move", to: { id: to.id, title: to.title, created: created && out.moved.length > 0 }, moved: out.moved, skipped: out.skipped, sentence: `${n(out.moved.length, "post")} moved to "${to.title}"${created && out.moved.length > 0 ? " (a new topic, with no trending page yet)" : ""}.${skippedSentence}` + (out.moved.length ? " Their judgements and captures are untouched." : ""), }, }; }); } // ── merge ────────────────────────────────────────────────────────────────── export type XTrendingMergeResult = | { ok: true; op: "merge"; into: { id: string; title: string }; merged: Array<{ id: string; title: string; posts: number; pages: number }>; posts: number; pages: number; // What became of the watches: which one stands, and whose were dropped. watch: { stands?: { from: string; sentence: string }; dropped: string[] }; // What became of the merged topics' PUBLISHED channels (review 1 S7): // `carried` is now the target's (the next publish adds to it); `left` // stay as they are and are never added to again. published: { carried?: string; left: string[] }; sentence: string; } | Refused; function joinSources(into: XTrendingSource[], add: ReadonlyArray): void { for (const s of add) { const have = into.find((x) => x.trendId === s.trendId); if (!have) { into.push({ ...s, reads: [...s.reads] }); continue; } if (!have.title && s.title) have.title = s.title; if (!have.summary && s.summary) have.summary = s.summary; for (const r of s.reads) if (!have.reads.some((x) => x.id === r.id)) have.reads.push(r); have.reads.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0)); } } export async function mergeXTrendingTopics( channelRoot: string, ask: { into: string; from: ReadonlyArray; by: XTrendingOrganiseBy; // A read or a reparse of this library queued or running (required, so no // door can forget it). readInFlight: () => boolean | Promise; now?: number; }, ): Promise { const bad = byProblem(ask.by); if (bad) return { ok: false, error: bad }; if (ask.by !== "operator") return { ok: false, error: MERGE_IS_THE_OPERATORS }; if (typeof ask.into !== "string" || !ask.into.trim()) return { ok: false, error: `"into" is the topic that stays` }; if (!Array.isArray(ask.from) || ask.from.length === 0 || !ask.from.every((t) => typeof t === "string" && t.trim())) { return { ok: false, error: `"from" is a list of the topics merged into it` }; } if (ask.from.length > X_TRENDING_MERGE_MAX) return { ok: false, error: `"from" holds at most ${X_TRENDING_MERGE_MAX} topics` }; if (await ask.readInFlight()) return { ok: false, error: MERGE_WAITS_FOR_READS }; const nowMs = ask.now ?? Date.now(); const at = new Date(nowMs).toISOString(); return mutateXTrendingTopics(channelRoot, async (topics) => { const into = resolveXTrendingTopic(topics, ask.into); if (!into) return { write: false, result: { ok: false, error: noTopic(ask.into, topics) } }; const from: XTrendingTopic[] = []; for (const name of ask.from) { const t = resolveXTrendingTopic(topics, name); if (!t) return { write: false, result: { ok: false, error: noTopic(name, topics) } }; if (t === into) return { write: false, result: { ok: false, error: `"${name}" is the topic that stays ("${into.title}"): a topic is not merged into itself.` } }; if (!from.includes(t)) from.push(t); } // Asked again inside the lock: a read queued since the first look. if (await ask.readInFlight()) return { write: false, result: { ok: false, error: MERGE_WAITS_FOR_READS } }; const gone = new Set(from.map((t) => t.id)); // 1. the posts const counts = await mutateXTrendingMembership(channelRoot, (members) => { const per = new Map(); for (const m of Object.values(members)) { if (!gone.has(m.topic)) continue; per.set(m.topic, (per.get(m.topic) ?? 0) + 1); m.moved = { from: m.topic, by: ask.by, at }; m.topic = into.id; } return { write: per.size > 0, result: per }; }); // 2. the watches: one stands const pagesAfter = new Set([...into.sources, ...from.flatMap((t) => t.sources)].map((s) => s.trendId)); type Standing = { from: string; watch: XTrendingWatch }; const watch = await mutateXTrendingWatches<{ dropped: string[]; stands?: Standing }>(channelRoot, (watches) => { const dropped: string[] = []; let stands: Standing | undefined; if (watchIsLive(watches[into.id])) stands = { from: into.id, watch: watches[into.id] }; for (const t of from) { const w = watches[t.id]; if (!w) continue; if (!stands && watchIsLive(w)) stands = { from: t.id, watch: w }; else if (watchIsLive(w)) dropped.push(t.id); } const touched = from.some((t) => watches[t.id]) || !!stands; if (!touched) return { write: false, result: { dropped } }; const unread = new Set(); for (const id of [into.id, ...gone]) for (const g of watches[id]?.goneSources ?? []) if (pagesAfter.has(g)) unread.add(g); for (const id of gone) delete watches[id]; if (stands) { stands.watch.goneSources = [...unread]; stands.watch.nextSource = 0; watches[into.id] = stands.watch; } return { write: true, result: { dropped, ...(stands ? { stands } : {}) } }; }); // 3. what was published: a topic has ONE channel. The target's own stays // its own; with none, the first merged topic's becomes the target's. // Any other merged topic's channel is left as it is: no record names // it any more, so no publish adds to it again. const published = await mutateXTrendingPublished(channelRoot, (all) => { const left: string[] = []; let carried: string | undefined; let write = false; for (const t of from) { const rec = all[t.id]; if (!rec) continue; write = true; if (!all[into.id]) { all[into.id] = rec; carried = rec.slug; } else left.push(rec.slug); delete all[t.id]; } return { write, result: { ...(carried ? { carried } : {}), left } }; }); // 4. the topics const merged = from.map((t) => ({ id: t.id, title: t.title, posts: counts.get(t.id) ?? 0, pages: t.sources.length })); for (const t of from) { joinSources(into.sources, t.sources); into.aliases = [...new Set([...(into.aliases ?? []), t.id, ...(t.aliases ?? [])])].filter((a) => a !== into.id); topics.splice(topics.indexOf(t), 1); } into.organised = { what: "merge", by: ask.by, at }; const posts = merged.reduce((a, m) => a + m.posts, 0); const names = merged.map((m) => `"${m.title}"`).join(", "); const title = (id: string) => (id === into.id ? into.title : merged.find((m) => m.id === id)?.title ?? id); let watchSentence = ""; const standing = watch.stands; if (standing) { const what = describeXTrendingWatch(standing.watch, nowMs); const whose = standing.from === into.id ? `The watch of "${into.title}" stands with its own terms` : `The watch of "${title(standing.from)}" is now the watch of "${into.title}"`; const others = watch.dropped.length ? ` The watch${watch.dropped.length === 1 ? "" : "es"} of ${watch.dropped.map((id) => `"${title(id)}"`).join(", ")} ${watch.dropped.length === 1 ? "is" : "are"} gone: one topic has one watch.` : ""; watchSentence = ` ${whose} and reads its ${n(into.sources.length, "page")} in turn: ${what}${others}`; } return { write: true, result: { ok: true, op: "merge", into: { id: into.id, title: into.title }, merged, posts, pages: into.sources.length, watch: { ...(standing ? { stands: { from: standing.from, sentence: describeXTrendingWatch(standing.watch, nowMs) } } : {}), dropped: watch.dropped }, published, sentence: `${names} ${merged.length === 1 ? "is" : "are"} now part of "${into.title}": ${n(posts, "post")} moved, ${n(into.sources.length, "trending page")} in the topic. ` + `The judgements are untouched. This cannot be undone.${watchSentence}` + (published.carried ? ` The channel "${published.carried}", which a merged topic was published into, is now the channel of "${into.title}": its next publish adds to it.` : "") + (published.left.length ? ` The channel${published.left.length === 1 ? "" : "s"} ${published.left.map((c) => `"${c}"`).join(", ")}, published from a merged topic, ${published.left.length === 1 ? "stays as it is" : "stay as they are"} and will not be added to again: "${into.title}" has a channel of its own.` : ""), }, }; }); }