// A LIBRARY'S WATCHED TOPICS (lane x-trending-2): `trending/watch.json`. // // A watch is a per-topic switch: while it is on, the topic's trending page is // read again every `intervalMinutes` until `until`, by the same single // `read-x-trending` job a person starts (controller/xTrendingWatch.ts is the // scan that enqueues it; this module is the state and its ONE writer). // // on the switch // shots also screenshot every new post (default: only their media) // paused the scan could not start a tick, and why — X's cookie jar is // older than the limit ("jar"), the X alert is up ("alert"), X is // cooling down after a rate limit ("cooldown"), there is no // connected profile ("no-profile"), or the read was refused // ("refused"). A PAUSE ENDS BY ITSELF at the first scan that finds // the reason gone: a watch resumes after a Refresh on /cookies. // EXCEPT "failing" (review 1 S1): three reads in a row that did // not end "read" (a rate limit, a 403, a page that will not // load). A watch does not read into failure for two days: it // stays paused until a PERSON switches it on again. // ended the watch is over, with a sentence: its end time came, X no // longer has its page(s), or it was switched off // // A WATCH RUNS ONLY WHILE X'S COOKIE JAR IS FRESH (the fresh-jar rule, // jobs/networkGuard.ts): the editor never refreshes the jar by itself, so a // watch does not cover a night nobody presses Refresh in. // // SERVER-ONLY (node:fs). import path from "node:path"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; // TYPES ONLY from store.ts (which reads the watches for its listing): this // module imports nothing of it at run time, so the two do not form a cycle. import type { XTrendingTopic } from "./store"; // store.ts TRENDING_DIRNAME (watch.test.ts holds the two together). const TRENDING_DIRNAME = "trending"; export type XTrendingWatchPauseReason = "jar" | "alert" | "cooldown" | "no-profile" | "refused" | "failing"; export const X_TRENDING_WATCH_PAUSE_REASONS: readonly XTrendingWatchPauseReason[] = ["jar", "alert", "cooldown", "no-profile", "refused", "failing"]; // This many reads of a watched topic in a row that did not end "read", and // the watch pauses ("failing") until a person switches it on again. export const X_TRENDING_WATCH_MAX_FAILURES = 3; // A watch's tabs when it does NOT read both (both is the default and is not // written): ["top"] or ["latest"]. Anything else reads both. export function watchTabsOf(v: unknown): Array<"top" | "latest"> | undefined { if (!Array.isArray(v)) return undefined; const asked = new Set(v.filter((t): t is string => typeof t === "string").map((t) => t.toLowerCase())); const tabs = (["top", "latest"] as const).filter((t) => asked.has(t)); return tabs.length === 1 ? [...tabs] : undefined; } export type XTrendingWatch = { on: boolean; intervalMinutes: number; // When the watch began and when it ends (ISO). startedAt: string; until: string; shots: boolean; // The ONE tab each tick reads, when not both (R3): ["top"] or ["latest"]. tabs?: Array<"top" | "latest">; by: "agent" | "operator"; // The last tick the scan enqueued: when, its job, and when the next is due. lastTickAt?: string; lastJobId?: string; nextTickAt?: string; ticks: number; // Reads of its pages in a row that did not end "read". failures: number; // Which of the topic's pages the next tick reads (round-robin). nextSource: number; // Pages X answered "gone" for: not read again. goneSources: string[]; paused?: { reason: XTrendingWatchPauseReason; since: string; sentence: string }; ended?: { at: string; reason: "until" | "gone" | "off"; sentence: string }; }; type WatchFile = { version: 1; topics: Record }; export function xTrendingWatchPath(channelRoot: string): string { return path.join(channelRoot, TRENDING_DIRNAME, "watch.json"); } const str = (v: unknown): v is string => typeof v === "string" && v !== ""; const iso = (v: unknown): v is string => str(v) && Number.isFinite(Date.parse(v)); function parseWatch(raw: unknown): XTrendingWatch | null { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const r = raw as Record; if (typeof r.on !== "boolean" || !iso(r.startedAt) || !iso(r.until)) return null; const interval = Number(r.intervalMinutes); if (!Number.isInteger(interval) || interval < 1) return null; const paused = r.paused as XTrendingWatch["paused"] | undefined; const ended = r.ended as XTrendingWatch["ended"] | undefined; return { on: r.on, intervalMinutes: interval, startedAt: r.startedAt, until: r.until, shots: r.shots === true, ...(watchTabsOf(r.tabs) ? { tabs: watchTabsOf(r.tabs) } : {}), by: r.by === "operator" ? "operator" : "agent", ...(iso(r.lastTickAt) ? { lastTickAt: r.lastTickAt } : {}), ...(str(r.lastJobId) ? { lastJobId: r.lastJobId } : {}), ...(iso(r.nextTickAt) ? { nextTickAt: r.nextTickAt } : {}), ticks: Number.isInteger(r.ticks) && (r.ticks as number) > 0 ? (r.ticks as number) : 0, failures: Number.isInteger(r.failures) && (r.failures as number) > 0 ? (r.failures as number) : 0, nextSource: Number.isInteger(r.nextSource) && (r.nextSource as number) > 0 ? (r.nextSource as number) : 0, goneSources: Array.isArray(r.goneSources) ? r.goneSources.filter((t): t is string => typeof t === "string" && /^\d+$/.test(t)) : [], ...(paused && typeof paused === "object" && X_TRENDING_WATCH_PAUSE_REASONS.includes(paused.reason) && iso(paused.since) && str(paused.sentence) ? { paused: { reason: paused.reason, since: paused.since, sentence: paused.sentence } } : {}), ...(ended && typeof ended === "object" && iso(ended.at) && str(ended.sentence) && (ended.reason === "until" || ended.reason === "gone" || ended.reason === "off") ? { ended: { at: ended.at, reason: ended.reason, sentence: ended.sentence } } : {}), }; } // The watches by topic id ({} while there is no file). Ill-shaped entries are dropped. export async function readXTrendingWatches(channelRoot: string): Promise> { const read = await readJsonFile(xTrendingWatchPath(channelRoot)); const topics = read.ok ? (read.value as { topics?: unknown } | null)?.topics : null; const out: Record = {}; if (!topics || typeof topics !== "object" || Array.isArray(topics)) return out; for (const [id, raw] of Object.entries(topics as Record)) { const w = parseWatch(raw); if (w && id) out[id] = w; } return out; } // A watch the scan still ticks: switched on and not ended. export const watchIsLive = (w: XTrendingWatch | undefined): w is XTrendingWatch => !!w && w.on && !w.ended; // Every write of watch.json: the file read under its lock, changed, written. // `change` answers false to write nothing. export async function mutateXTrendingWatches( channelRoot: string, change: (topics: Record) => { write: boolean; result: T }, ): Promise { return withJsonFileLock(xTrendingWatchPath(channelRoot), async () => { const topics = await readXTrendingWatches(channelRoot); const { write, result } = change(topics); if (write) await writeJsonAtomic(xTrendingWatchPath(channelRoot), { version: 1, topics } satisfies WatchFile, { mkdir: true }); return result; }); } export type SetWatchAsk = { // The library's topics (store.ts readXTrendingTopics), read by the caller. topics: ReadonlyArray; topic: string; on: boolean; intervalMinutes: number; hours: number; shots?: boolean; // The page's tabs each tick reads: ["top"], ["latest"] or both. Absent: // what the watch had, else both. tabs?: ReadonlyArray<"top" | "latest">; by: "agent" | "operator"; maxTopics: number; now: number; }; export type SetWatchResult = { ok: true; topic: string; watch: XTrendingWatch } | { ok: false; error: string }; const hhmm = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " "); // The switch. ON: the topic must exist and hold at least one trending page, // and the library may not already watch `maxTopics` others; switching a live // watch on again changes its interval, end time and shots and keeps its // history. OFF: the watch ends ("switched off"); a watch that is not on is // left as it is. export async function setXTrendingWatch(channelRoot: string, ask: SetWatchAsk): Promise { const topics = ask.topics; const topic = topics.find((t) => t.id === ask.topic) ?? topics.find((t) => t.title.toLowerCase() === ask.topic.trim().toLowerCase()); if (!topic) { return { ok: false, error: `This library has no topic "${ask.topic}" (its topics: ${topics.map((t) => t.id).join(", ") || "none yet"}).` }; } const at = new Date(ask.now).toISOString(); return mutateXTrendingWatches(channelRoot, (watches) => { const have = watches[topic.id]; if (!ask.on) { if (!watchIsLive(have)) { return { write: false, result: { ok: false, error: `Topic "${topic.title}" is not being watched.` } }; } have.on = false; delete have.paused; have.ended = { at, reason: "off", sentence: `The watch of "${topic.title}" was switched off.` }; return { write: true, result: { ok: true, topic: topic.id, watch: have } }; } if (topic.sources.length === 0) { return { write: false, result: { ok: false, error: `Topic "${topic.title}" holds no trending page to watch: read one into it first.` } }; } const others = Object.entries(watches).filter(([id, w]) => id !== topic.id && watchIsLive(w)).length; if (!watchIsLive(have) && others >= ask.maxTopics) { return { write: false, result: { ok: false, error: `This library already watches ${others} topic${others === 1 ? "" : "s"} (at most ${ask.maxTopics}): ` + `switch one off first, or raise the limit (watch-trending {"settings": {"maxTopics": …}}).`, }, }; } const until = new Date(ask.now + ask.hours * 3_600_000).toISOString(); const live = watchIsLive(have) ? have : undefined; // A watch paused for FAILING is the operator's to start again (review 2 // N5): an agent switching it "on" would be the watch reading into failure // with nobody having looked. if (live?.paused?.reason === "failing" && ask.by !== "operator") { return { write: false, result: { ok: false, error: `The watch of "${topic.title}" is paused because its reads kept failing (${live.paused.sentence}) ` + `Only the operator starts it again: Watch on the topic's page, or watch-trending with "by": "operator".`, }, }; } const watch: XTrendingWatch = { on: true, intervalMinutes: ask.intervalMinutes, startedAt: live?.startedAt ?? at, until, shots: ask.shots ?? live?.shots ?? false, ...(watchTabsOf(ask.tabs ?? live?.tabs) ? { tabs: watchTabsOf(ask.tabs ?? live?.tabs) } : {}), by: ask.by, ...(live?.lastTickAt ? { lastTickAt: live.lastTickAt } : {}), ...(live?.lastJobId ? { lastJobId: live.lastJobId } : {}), // A changed interval counts from the last tick; a new watch ticks at the next scan. ...(live?.lastTickAt ? { nextTickAt: new Date(Date.parse(live.lastTickAt) + ask.intervalMinutes * 60_000).toISOString() } : {}), ticks: live?.ticks ?? 0, // Switched on by a person: a watch paused for failing starts again. failures: 0, nextSource: live?.nextSource ?? 0, goneSources: live?.goneSources ?? [], ...(live?.paused && live.paused.reason !== "failing" ? { paused: live.paused } : {}), }; watches[topic.id] = watch; return { write: true, result: { ok: true, topic: topic.id, watch } }; }); } // What a watch is doing, in one sentence (the panel, `get trending`, the MCP). export function describeXTrendingWatch(w: XTrendingWatch, now: number): string { if (w.ended) return w.ended.sentence; if (!w.on) return "Not watched."; const every = `every ${w.intervalMinutes} min until ${hhmm(Date.parse(w.until))} UTC${w.shots ? ", screenshotting every new post" : ""}` + (w.tabs ? `, reading the "${w.tabs[0] === "latest" ? "Latest" : "Top"}" tab only` : ""); if (w.paused?.reason === "failing") return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC, until the operator switches it on again: ${w.paused.sentence}`; if (w.paused) return `Watched ${every} — PAUSED since ${hhmm(Date.parse(w.paused.since))} UTC: ${w.paused.sentence}`; const next = w.nextTickAt ? Date.parse(w.nextTickAt) : now; return `Watched ${every}; ${w.ticks} tick${w.ticks === 1 ? "" : "s"} so far, next ${next <= now ? "at the next scan" : `at ${hhmm(next)} UTC`}.`; } // PAUSED WATCHES, AS /review LISTS THEM: topics someone switched a watch on // for, which the watch's scan cannot tick now — X's cookie // jar is past its limit, the X alert is up, X is cooling down, there is no // connected profile. It is here because what ends the pause is a PERSON's // press (Refresh cookies on /cookies; the editor never refreshes X's jar by // itself), and until someone makes it the watch reads nothing. export type PausedWatchRow = { slug: string; topic: string; title: string; reason: string; // ISO: when the pause began, and when the watch ends whether or not it resumes. since: string; until: string; sentence: string; }; export function pausedWatchRows( libraries: ReadonlyArray<{ slug: string; topics: ReadonlyArray<{ id: string; title: string }>; watches: Readonly>; }>, ): PausedWatchRow[] { const rows: PausedWatchRow[] = []; for (const lib of libraries) { for (const [topic, w] of Object.entries(lib.watches)) { if (!w.on || w.ended || !w.paused) continue; rows.push({ slug: lib.slug, topic, title: lib.topics.find((t) => t.id === topic)?.title ?? topic, reason: w.paused.reason, since: w.paused.since, until: w.until, sentence: w.paused.sentence, }); } } // Stable across renders. return rows.sort((a, b) => a.slug.localeCompare(b.slug) || a.topic.localeCompare(b.topic)); }