Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 70ade9964e34d2ba79bda3b482842cbb8ca53baa
parent 9a4990136abff0fdfe3fa01dfe9c7fb402fe49f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 10:11:50 -0500

common: x-trending slice 4, organise -- a topic is renamed (its id stays), posts move between topics by id or by thread, and topics merge into one

Rename and move are open to an agent and the operator and record who; a
merge is the operator's (there is no unmerge) and is refused while a read
or a reparse of the library is queued or running, since a queued watch
tick names its topic by id. The merged topics' ids stay on the target as
aliases, which a read and the listing resolve, so an old id never makes a
topic again. A merge carries posts, pages and reads (the same page in two
topics becomes one, its reads joined), leaves the judgements alone (they
are keyed by post and thread) and keeps ONE watch: the target's live watch
stands with its own terms, else the first merged topic's moves to it; the
sentence says which. A move is safe beside a read (a read never moves a
placed post) and is not refused for one.

topics.json and membership.json keep one writer: organise.ts writes
through mutateXTrendingTopics / mutateXTrendingMembership in store.ts,
under the files' locks.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Acommon/lib/xTrending/organise.test.ts | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/organise.ts | 351+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
3 files changed, 665 insertions(+), 7 deletions(-)

diff --git a/common/lib/xTrending/organise.test.ts b/common/lib/xTrending/organise.test.ts @@ -0,0 +1,223 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { judgeXTrending } from "./judgements"; +import { MERGE_IS_THE_OPERATORS, MERGE_WAITS_FOR_READS, mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } from "./organise"; +import { listXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, writeXTrendingPosts } from "./store"; +import { readXTrendingWatches, setXTrendingWatch } from "./watch"; +import type { Post } from "../posts"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-organise-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const READ = (c: string) => `tr-01J${c}0000000000000000000000`; +const REF = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); +const NOW = Date.parse("2026-11-18T10:00:00.000Z"); + +function post(id: string, author: string, text: string, replyTo?: string): Post { + return { + id, + slug: `lib/${id}`, + channelSlug: "lib", + author, + createdAt: "2026-11-16T12:00:00.000Z", + uploadDate: "20261116", + text, + url: `https://x.com/${author}/status/${id}`, + platform: "twitter", + ...(replyTo ? { threadId: replyTo, replyTo: { id: replyTo, platform: "twitter" as const } } : {}), + isReply: Boolean(replyTo), + isRepost: false, + links: [], + }; +} + +// Two topics: "Kettles" (page 1: posts 101, 102 and 103, a reply to 101) and +// "Saucers" (page 2: posts 201, 202; page 1 again as its second source). +async function library(name: string): Promise<string> { + const dir = path.join(TMP, name); + mkdirSync(dir, { recursive: true }); + await writeXTrendingPosts(dir, [ + post("101", "teapot_news", "one"), + post("102", "saucer_fan", "two"), + post("103", "teapot_news", "three", "101"), + post("201", "spoon_daily", "four"), + post("202", "saucer_fan", "five"), + ]); + await recordXTrendingRead(dir, { readId: READ("A"), at: "2026-11-17T10:00:00.000Z", ref: REF(1), topic: "Kettles", postIds: ["101", "102", "103"], added: 3, threads: { "101": "101", "103": "101", "102": "102" } }); + await recordXTrendingRead(dir, { readId: READ("B"), at: "2026-11-17T11:00:00.000Z", ref: REF(2), topic: "Saucers", postIds: ["201", "202"], added: 2 }); + await recordXTrendingRead(dir, { readId: READ("C"), at: "2026-11-17T12:00:00.000Z", ref: REF(1), topic: "Saucers", postIds: ["101"], added: 0 }); + return dir; +} + +const watchOn = async (dir: string, topic: string, by: "agent" | "operator", intervalMinutes: number) => { + const r = await setXTrendingWatch(dir, { topics: await readXTrendingTopics(dir), topic, on: true, intervalMinutes, hours: 48, by, maxTopics: 4, now: NOW }); + assert.equal(r.ok, true); +}; + +test("rename: the title changes, the id stays, and who renamed is recorded; a name another topic answers to is refused", async () => { + const dir = await library("rename"); + await watchOn(dir, "kettles", "operator", 30); + const r = await renameXTrendingTopic(dir, { topic: "kettles", title: " Teapots of the week ", by: "agent", now: NOW }); + assert.ok(r.ok); + assert.deepEqual([r.topic, r.title, r.was, r.changed], ["kettles", "Teapots of the week", "Kettles", true]); + assert.match(r.sentence, /Its id stays kettles/); + const topics = await readXTrendingTopics(dir); + assert.deepEqual(topics.map((t) => [t.id, t.title]), [["kettles", "Teapots of the week"], ["saucers", "Saucers"]]); + assert.deepEqual(topics[0].organised, { what: "rename", by: "agent", at: "2026-11-18T10:00:00.000Z" }); + assert.ok((await readXTrendingWatches(dir)).kettles, "its watch is still its own"); + assert.equal((await readXTrendingMembership(dir))["102"].topic, "kettles"); + + const same = await renameXTrendingTopic(dir, { topic: "kettles", title: "Teapots of the week", by: "agent" }); + assert.ok(same.ok && !same.changed); + for (const taken of ["saucers", "SAUCERS", "Saucers"]) { + const no = await renameXTrendingTopic(dir, { topic: "kettles", title: taken, by: "operator" }); + assert.ok(!no.ok && /already answers to/.test(no.error), taken); + } + const missing = await renameXTrendingTopic(dir, { topic: "spoons", title: "x", by: "operator" }); + assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); + const long = await renameXTrendingTopic(dir, { topic: "kettles", title: "x".repeat(121), by: "operator" }); + assert.ok(!long.ok && /at most 120/.test(long.error)); + const who = await renameXTrendingTopic(dir, { topic: "kettles", title: "x", by: "somebody" as never }); + assert.ok(!who.ok && /"by" is/.test(who.error)); +}); + +test("move: posts by id or a whole thread change topic; judgements stay; a later read does not move them back", async () => { + const dir = await library("move"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "102", state: "keep", note: "a note" }, { thread: "101", state: "drop" }] }); + const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); + + const r = await moveXTrendingPosts(dir, { to: "saucers", ids: ["102", "999", "201"], by: "agent", now: NOW }); + assert.ok(r.ok); + assert.deepEqual(r.moved, ["102"]); + assert.deepEqual(r.skipped, [{ id: "999", reason: "not in this library" }, { id: "201", reason: 'already in "Saucers"' }]); + let members = await readXTrendingMembership(dir); + assert.equal(members["102"].topic, "saucers"); + assert.deepEqual(members["102"].moved, { from: "kettles", by: "agent", at: "2026-11-18T10:00:00.000Z" }); + + const t = await moveXTrendingPosts(dir, { to: "Saucers", thread: "101", by: "operator", now: NOW }); + assert.ok(t.ok); + assert.deepEqual([...t.moved].sort(), ["101", "103"]); + assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore, "judgements are keyed by post and thread: untouched"); + const listing = await listXTrending(dir, { topic: "saucers", filter: { state: "drop" }, ids: true }); + assert.deepEqual([...(listing.ids ?? [])].sort(), ["101", "103"], "the thread's judgement travels with its posts"); + + // The page is read again into its first topic: a placed post keeps its place. + await recordXTrendingRead(dir, { readId: READ("D"), at: "2026-11-18T11:00:00.000Z", ref: REF(1), topic: "kettles", postIds: ["101", "102", "103"], added: 0 }); + members = await readXTrendingMembership(dir); + assert.deepEqual(["101", "102", "103"].map((id) => members[id].topic), ["saucers", "saucers", "saucers"]); + + for (const [ask, re] of [ + [{ to: "saucers", by: "agent" }, /one of them/], + [{ to: "saucers", ids: ["101"], thread: "101", by: "agent" }, /one of them/], + [{ to: "saucers", ids: ["x"], by: "agent" }, /list of post ids/], + [{ to: "saucers", thread: "777", by: "agent" }, /no thread "777"/], + [{ to: "spoons", ids: ["101"], by: "agent" }, /no topic "spoons".*"create": true/], + [{ to: "", ids: ["101"], by: "agent" }, /"to" is/], + ] as const) { + const no = await moveXTrendingPosts(dir, ask as never); + assert.ok(!no.ok && re.test(no.error), JSON.stringify(ask)); + } +}); + +test("move with create: a new topic with no page, made only when a post went into it", async () => { + const dir = await library("move-create"); + const none = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["999"], create: true, by: "operator" }); + assert.ok(none.ok && none.moved.length === 0 && !none.to.created); + assert.equal((await readXTrendingTopics(dir)).length, 2); + const r = await moveXTrendingPosts(dir, { to: "Spoons", ids: ["201"], create: true, by: "operator" }); + assert.ok(r.ok && r.to.created); + assert.deepEqual(r.to, { id: "spoons", title: "Spoons", created: true }); + const topics = await readXTrendingTopics(dir); + assert.deepEqual(topics.map((t) => [t.id, t.sources.length]), [["kettles", 1], ["saucers", 2], ["spoons", 0]]); +}); + +test("merge is the operator's, and waits for a read", async () => { + const dir = await library("merge-refused"); + const before = readFileSync(path.join(dir, "trending", "topics.json"), "utf8"); + const agent = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "agent", readInFlight: () => false }); + assert.deepEqual(agent, { ok: false, error: MERGE_IS_THE_OPERATORS }); + const busy = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => true }); + assert.deepEqual(busy, { ok: false, error: MERGE_WAITS_FOR_READS }); + // A read queued between the first look and the lock refuses it too. + let asked = 0; + const late = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => ++asked > 1 }); + assert.deepEqual(late, { ok: false, error: MERGE_WAITS_FOR_READS }); + const self = await mergeXTrendingTopics(dir, { into: "kettles", from: ["Kettles"], by: "operator", readInFlight: () => false }); + assert.ok(!self.ok && /not merged into itself/.test(self.error)); + const missing = await mergeXTrendingTopics(dir, { into: "kettles", from: ["spoons"], by: "operator", readInFlight: () => false }); + assert.ok(!missing.ok && /no topic "spoons"/.test(missing.error)); + assert.equal(readFileSync(path.join(dir, "trending", "topics.json"), "utf8"), before); +}); + +test("merge: posts, pages and reads carried; the same page in both becomes one; judgements untouched; the old id means the target", async () => { + const dir = await library("merge"); + await judgeXTrending(dir, { by: "operator", set: [{ id: "201", state: "keep" }, { thread: "101", state: "later" }] }); + const judgedBefore = readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + assert.deepEqual(r.into, { id: "kettles", title: "Kettles" }); + assert.deepEqual(r.merged, [{ id: "saucers", title: "Saucers", posts: 2, pages: 2 }]); + assert.equal(r.posts, 2); + assert.equal(r.pages, 2); + assert.match(r.sentence, /"Saucers" is now part of "Kettles": 2 posts moved, 2 trending pages in the topic\. The judgements are untouched\. This cannot be undone\./); + + const topics = await readXTrendingTopics(dir); + assert.equal(topics.length, 1); + assert.deepEqual(topics[0].aliases, ["saucers"]); + assert.deepEqual(topics[0].organised, { what: "merge", by: "operator", at: "2026-11-18T10:00:00.000Z" }); + assert.deepEqual( + topics[0].sources.map((s) => [s.trendId, s.reads.map((x) => x.id)]), + [[REF(1).trendId, [READ("A"), READ("C")]], [REF(2).trendId, [READ("B")]]], + ); + const members = await readXTrendingMembership(dir); + assert.ok(Object.values(members).every((m) => m.topic === "kettles")); + assert.deepEqual(members["201"].moved, { from: "saucers", by: "operator", at: "2026-11-18T10:00:00.000Z" }); + assert.equal(readFileSync(path.join(dir, "trending", "judgements.json"), "utf8"), judgedBefore); + + // An ask that still names the merged topic: the listing and a read. + const listing = await listXTrending(dir, { topic: "saucers", ids: true }); + assert.equal(listing.ids?.length, 5); + assert.deepEqual(listing.topics.map((t) => [t.id, t.posts, t.aliases]), [["kettles", 5, ["saucers"]]]); + await writeXTrendingPosts(dir, [post("301", "spoon_daily", "six")]); + const read = await recordXTrendingRead(dir, { readId: READ("E"), at: "2026-11-18T12:00:00.000Z", ref: REF(2), topic: "saucers", postIds: ["301"], added: 1 }); + assert.deepEqual(read.topic, { id: "kettles", title: "Kettles", created: false }); + assert.equal((await readXTrendingTopics(dir)).length, 1, "a merged-away id never makes a topic again"); + // Nor is a new topic ever given that id. + const fresh = await recordXTrendingRead(dir, { readId: READ("F"), at: "2026-11-18T13:00:00.000Z", ref: REF(3), topic: "Saucers!", postIds: [], added: 0 }); + assert.deepEqual(fresh.topic, { id: "saucers-2", title: "Saucers!", created: true }); +}); + +test("merge, two live watches: the target's stands with its own terms, the other is gone, and the sentence says so", async () => { + const dir = await library("merge-watches"); + await watchOn(dir, "kettles", "agent", 45); + await watchOn(dir, "saucers", "operator", 20); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + const watches = await readXTrendingWatches(dir); + assert.deepEqual(Object.keys(watches), ["kettles"]); + assert.deepEqual([watches.kettles.intervalMinutes, watches.kettles.by, watches.kettles.nextSource], [45, "agent", 0]); + assert.deepEqual(r.watch.dropped, ["saucers"]); + assert.equal(r.watch.stands?.from, "kettles"); + assert.match(r.sentence, /The watch of "Kettles" stands with its own terms and reads its 2 pages in turn: Watched every 45 min/); + assert.match(r.sentence, /The watch of "Saucers" is gone: one topic has one watch\./); +}); + +test("merge, only the merged topic watched: its watch becomes the target's; none watched: no watch file is made", async () => { + const dir = await library("merge-watch-moves"); + await watchOn(dir, "saucers", "operator", 20); + const r = await mergeXTrendingTopics(dir, { into: "kettles", from: ["saucers"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(r.ok); + const watches = await readXTrendingWatches(dir); + assert.deepEqual(Object.keys(watches), ["kettles"]); + assert.equal(watches.kettles.intervalMinutes, 20); + assert.match(r.sentence, /The watch of "Saucers" is now the watch of "Kettles" and reads its 2 pages in turn/); + + const plain = await library("merge-no-watch"); + const p = await mergeXTrendingTopics(plain, { into: "saucers", from: ["kettles"], by: "operator", readInFlight: () => false, now: NOW }); + assert.ok(p.ok && !p.watch.stands && p.watch.dropped.length === 0); + assert.deepEqual(await readXTrendingWatches(plain), {}); + assert.doesNotMatch(p.sentence, /watch/i); +}); diff --git a/common/lib/xTrending/organise.ts b/common/lib/xTrending/organise.ts @@ -0,0 +1,351 @@ +// 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, addresses and a queued read keep meaning it. +// +// 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) +// 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, +// 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 { 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<XTrendingTopic>) => topics.map((t) => t.id).join(", ") || "none yet"; +const noTopic = (asked: string, topics: ReadonlyArray<XTrendingTopic>) => `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 async function renameXTrendingTopic( + channelRoot: string, + ask: { topic: string; title: string; by: XTrendingOrganiseBy; now?: number }, +): Promise<XTrendingRenameResult> { + 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(); + return mutateXTrendingTopics<XTrendingRenameResult>(channelRoot, (topics) => { + const topic = resolveXTrendingTopic(topics, ask.topic); + if (!topic) return { write: false, result: { ok: false, error: noTopic(ask.topic, topics) } }; + // 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 }; + 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<string>; + 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<Post>; + }, +): Promise<XTrendingMoveResult> { + 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)]); + const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); + wanted = [...byId.values()].filter((p) => xTrendingThreadOf(p, membership, byId) === ask.thread).map((p) => p.id); + if (wanted.length === 0) return { ok: false, error: `This library has no thread "${ask.thread}".` }; + } + + return mutateXTrendingTopics<XTrendingMoveResult>(channelRoot, async (topics) => { + 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: [] }; + topics.push(target); + created = true; + } + 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 not made. + if (created && out.moved.length === 0) topics.pop(); + const skippedSentence = out.skipped.length ? ` ${n(out.skipped.length, "post")} skipped: ${out.skipped[0].reason}.` : ""; + return { + write: created && out.moved.length > 0, + 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[] }; + sentence: string; + } + | Refused; + +function joinSources(into: XTrendingSource[], add: ReadonlyArray<XTrendingSource>): 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<string>; + by: XTrendingOrganiseBy; + // A read or a reparse of this library queued or running (required, so no + // door can forget it). + readInFlight: () => boolean | Promise<boolean>; + now?: number; + }, +): Promise<XTrendingMergeResult> { + 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<XTrendingMergeResult>(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<string, number>(); + 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<string>(); + 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. 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 }, + 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}`, + }, + }; + }); +} diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -21,7 +21,9 @@ // 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. +// 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 @@ -322,12 +324,23 @@ export type XTrendingSource = { reads: XTrendingSourceRead[]; }; +// 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; }; export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number }; @@ -348,6 +361,9 @@ export type XTrendingMember = { gone?: XTrendingGone; // Earlier absences that ended: gone from `from`, shown again at `to`. wasGone?: Array<{ from: string; to: string }>; + // Its last move between topics (lib/xTrending/organise.ts): the topic it + // was in, who moved it and when. + moved?: { from: string; by: XTrendingOrganiseBy; at: string }; }; type TopicsFile = { version: 1; topics: XTrendingTopic[] }; @@ -377,7 +393,20 @@ function parseTopics(raw: unknown): XTrendingTopic[] { reads, }); } - out.push({ id: t.id, title: t.title, createdAt: str(t.createdAt) ? t.createdAt : "", sources }); + const aliases = (Array.isArray(t.aliases) ? t.aliases : []).filter((a: unknown): a is string => str(a) && a !== t.id); + const o = t.organised as Partial<XTrendingOrganised> | undefined; + const organised = + o && typeof o === "object" && (o.what === "rename" || o.what === "merge") && (o.by === "agent" || o.by === "operator") && str(o.at) + ? { what: o.what, by: o.by, at: o.at } + : undefined; + out.push({ + id: t.id, + title: t.title, + createdAt: str(t.createdAt) ? t.createdAt : "", + sources, + ...(aliases.length ? { aliases: [...new Set<string>(aliases)] } : {}), + ...(organised ? { organised } : {}), + }); } return out; } @@ -409,6 +438,11 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { const wasGone = (Array.isArray(m.wasGone) ? m.wasGone : []).filter( (w): w is { from: string; to: string } => !!w && typeof w === "object" && str(w.from) && str(w.to), ); + const mv = m.moved as Partial<NonNullable<XTrendingMember["moved"]>> | undefined; + const moved = + mv && typeof mv === "object" && str(mv.from) && (mv.by === "agent" || mv.by === "operator") && str(mv.at) + ? { from: mv.from, by: mv.by, at: mv.at } + : undefined; out[id] = { topic: m.topic, ...(typeof m.thread === "string" && /^\d+$/.test(m.thread) ? { thread: m.thread } : {}), @@ -416,6 +450,7 @@ function parseMembership(raw: unknown): Record<string, XTrendingMember> { ...(media ? { media } : {}), ...(gone ? { gone } : {}), ...(wasGone.length ? { wasGone: wasGone.map((w) => ({ from: w.from, to: w.to })) } : {}), + ...(moved ? { moved } : {}), }; } return out; @@ -431,6 +466,51 @@ export async function readXTrendingMembership(channelRoot: string): Promise<Reco return read.ok ? parseMembership(read.value) : {}; } +// THE TOPIC AN ASK NAMES: by its id, else by the id of a topic merged into it +// (`aliases`), else by its title in any case. One rule, asked by a read, the +// listing and every organise step, so a merged-away id never makes a topic. +export function resolveXTrendingTopic<T extends { id: string; title: string; aliases?: string[] }>( + topics: ReadonlyArray<T>, + asked: string | undefined, +): T | undefined { + const name = asked?.trim(); + if (!name) return undefined; + return ( + topics.find((t) => t.id === name) ?? + topics.find((t) => t.aliases?.includes(name)) ?? + topics.find((t) => t.title.toLowerCase() === name.toLowerCase()) + ); +} + +// EVERY OTHER WRITE OF topics.json AND membership.json (lane +// x-trending-publish: rename, merge, move — lib/xTrending/organise.ts): the +// file read under its lock, changed, written. `change` answers `write: false` +// to write nothing. A read's own write is recordXTrendingRead below; the two +// share the locks, so neither sees the other's half. +export async function mutateXTrendingTopics<T>( + channelRoot: string, + change: (topics: XTrendingTopic[]) => Promise<{ write: boolean; result: T }> | { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(topicsPath(channelRoot), async () => { + const topics = await readXTrendingTopics(channelRoot); + const { write, result } = await change(topics); + if (write) await writeJsonAtomic(topicsPath(channelRoot), { version: 1, topics } satisfies TopicsFile, { mkdir: true }); + return result; + }); +} + +export async function mutateXTrendingMembership<T>( + channelRoot: string, + change: (posts: Record<string, XTrendingMember>) => { write: boolean; result: T }, +): Promise<T> { + return withJsonFileLock(membershipPath(channelRoot), async () => { + const posts = await readXTrendingMembership(channelRoot); + const { write, result } = change(posts); + if (write) await writeJsonAtomic(membershipPath(channelRoot), { version: 1, posts } satisfies MembershipFile, { mkdir: true }); + return result; + }); +} + // A topic id from a title: lower-case words joined by "-", at most 48 // characters; "" when the title has no letter or digit. export function topicIdFromTitle(title: string): string { @@ -497,9 +577,7 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const asked = input.topic?.trim(); let found: XTrendingTopic | undefined; if (asked) { - found = - topics.find((t) => t.id === asked) ?? - topics.find((t) => t.title.toLowerCase() === asked.toLowerCase()); + found = resolveXTrendingTopic(topics, asked); } else { found = topics.find((t) => t.sources.some((s) => s.trendId === input.ref.trendId)); } @@ -508,7 +586,8 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead const title = asked || `Trending ${input.ref.trendId}`; const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`; let id = base; - for (let n = 2; topics.some((t) => t.id === id); n++) id = `${base}-${n}`; + // Never the id of a topic merged away: that id means the topic it went into. + for (let n = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); n++) id = `${base}-${n}`; found = { id, title, createdAt: input.at, sources: [] }; topics.push(found); created = true; @@ -712,6 +791,8 @@ export type XTrendingTopicRow = { id: string; title: string; posts: number; + // The ids of topics merged into it: an ask naming one means this topic. + aliases?: string[]; // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it // is doing as one sentence. watch?: XTrendingWatch & { sentence: string }; @@ -874,6 +955,8 @@ export async function listXTrending( readXTrendingJudgementsFile(channelRoot), ]); const archived = new Map((opts.posts ?? (await readXTrendingPosts(channelRoot))).map((p) => [p.id, p])); + // A topic asked for by the id of one merged into it is that topic. + const wantTopic = opts.topic ? (topics.find((t) => t.id === opts.topic) ?? topics.find((t) => t.aliases?.includes(opts.topic!)))?.id ?? opts.topic : undefined; const count = new Map<string, number>(); for (const [id, m] of Object.entries(membership)) { if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1); @@ -902,7 +985,7 @@ export async function listXTrending( if (!Number.isFinite(mark) || Date.parse(firstSeenAt) > mark) fresh.set(m.topic, (fresh.get(m.topic) ?? 0) + 1); } } - if (opts.topic && m.topic !== opts.topic) continue; + if (wantTopic && m.topic !== wantTopic) continue; if (opts.detail) authors.set(post.author, (authors.get(post.author) ?? 0) + 1); const media = m.media ?? { count: post.mediaCount ?? 0, kinds: [] }; if (filter.state && (effective?.state ?? "unjudged") !== filter.state) continue; @@ -966,6 +1049,7 @@ export async function listXTrending( id: t.id, title: t.title, posts: count.get(t.id) ?? 0, + ...(t.aliases?.length ? { aliases: t.aliases } : {}), ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}), ...(opts.detail ? { counts: counts.get(t.id) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 } } : {}), ...(opts.detail && opts.seen ? { fresh: fresh.get(t.id) ?? 0 } : {}),