// THE ONE WRITER OF A LIBRARY'S judgements.json (lane x-trending-2) — the // editor's `judge-trending`, for an agent and for the operator alike. // // keep | drop | later written as the post's (or the thread's) judgement, // with who decided and when, and a note; // undecided the entry is REMOVED: no entry is undecided. // // AN AGENT'S JUDGEMENT IS A SUGGESTION. A write `by: "agent"` over an entry the // operator made is SKIPPED for that id and reported; nothing forces it. // // THE PRECEDENCE IS ONE RULE (store.ts xTrendingEffectiveJudgement): the // operator's entry, for the post or for its thread, always outranks an // agent's about the same post, whatever the order in time; between two // entries of the same hand the post's own outranks its thread's. So an // agent's post-level write is skipped whenever the post's thread is the // operator's, and an operator's thread judgement makes an OLDER agent entry // for one of its posts ineffective at once (it stays in the file as history // and decides nothing). The operator overturns anything. `by` is the caller's // word: an agent is trusted to say "agent". // // A THREAD is judged by its root post's id (store.ts xTrendingThreadKey): a // post of it with no judgement of its own is taken to be the thread's. // // DROP DELETES NOTHING. A dropped post keeps its record, its capture and its // media, and a later keep puts it back. (Removing a capture is // mediaStore.ts removeXTrendingPostCapture, asked for by nobody in this // slice.) // // Every write is under the file's lock and atomic. SERVER-ONLY (node:fs). import { withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; import type { Post } from "../posts"; import { readXTrendingJudgementsFile, readXTrendingMembership, readXTrendingPosts, X_TRENDING_JUDGEMENT_STATES, xTrendingJudgementsPath, xTrendingEffectiveJudgement, xTrendingThreadOf, type XTrendingJudgement, type XTrendingJudgementState, } from "./store"; export const X_TRENDING_NOTE_MAX = 2000; export const X_TRENDING_JUDGE_MAX = 500; export type XTrendingJudgeBy = "agent" | "operator"; export type XTrendingJudgeState = XTrendingJudgementState | "undecided"; export type XTrendingJudgeItem = { // A post's id, or a thread's root post id: one of them. id?: string; thread?: string; state: XTrendingJudgeState; note?: string; }; export type XTrendingJudgeAsk = { by: XTrendingJudgeBy; set: ReadonlyArray }; // Why this is not a judge ask, or null. Shape only: whether each id is in the // library is asked of the disk, per id, by the writer. export function xTrendingJudgeProblem(ask: { by?: unknown; set?: unknown }): string | null { if (ask.by !== "agent" && ask.by !== "operator") return `"by" is who decided: "agent" or "operator"`; if (!Array.isArray(ask.set) || ask.set.length === 0) { return `"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`; } if (ask.set.length > X_TRENDING_JUDGE_MAX) return `"set" holds at most ${X_TRENDING_JUDGE_MAX} judgements`; const seen = new Set(); for (const [i, raw] of ask.set.entries()) { const at = `set[${i}]`; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${at} is not an object`; const item = raw as Record; const unknown = Object.keys(item).filter((k) => !["id", "thread", "state", "note"].includes(k)); if (unknown.length) return `${at}: unknown key(s) ${unknown.join(", ")} (id, thread, state, note)`; const hasId = item.id !== undefined; const hasThread = item.thread !== undefined; if (hasId === hasThread) return `${at}: give "id" (a post) or "thread" (a thread's root post id), one of them`; const key = hasId ? item.id : item.thread; if (typeof key !== "string" || !/^\d{1,25}$/.test(key)) return `${at}: "${String(key)}" is not a post id`; const state = item.state; if (state !== "undecided" && !X_TRENDING_JUDGEMENT_STATES.includes(state as XTrendingJudgementState)) { return `${at}: "state" is keep, drop, later or undecided`; } if (item.note !== undefined) { if (typeof item.note !== "string") return `${at}: "note" is text`; if (item.note.length > X_TRENDING_NOTE_MAX) return `${at}: a note is at most ${X_TRENDING_NOTE_MAX} characters`; if (state === "undecided" && item.note.trim()) return `${at}: "undecided" removes the judgement, so it carries no note`; } const mark = `${hasId ? "p" : "t"}:${key}`; if (seen.has(mark)) return `${at}: ${hasId ? "post" : "thread"} ${key} is judged twice in one ask`; seen.add(mark); } return null; } export type XTrendingJudged = { id?: string; thread?: string; state: XTrendingJudgeState }; export type XTrendingJudgeSkipped = { id?: string; thread?: string; reason: string }; export type XTrendingJudgeResult = { written: XTrendingJudged[]; skipped: XTrendingJudgeSkipped[]; // Posts whose judgement BECAME keep by this ask (their own, or their // thread's): what a keep archives. kept: string[]; }; export const JUDGED_BY_OPERATOR = "judged by the operator: an agent's judgement does not replace it"; export const NOT_IN_THE_LIBRARY = "not in this library"; // The ask applied. `posts` is the library's posts when the caller has them. export async function judgeXTrending( channelRoot: string, ask: XTrendingJudgeAsk, opts: { now?: () => number; posts?: ReadonlyArray } = {}, ): Promise { const problem = xTrendingJudgeProblem(ask); if (problem) throw new Error(problem); const at = new Date((opts.now ?? Date.now)()).toISOString(); const [membership, posts] = await Promise.all([ readXTrendingMembership(channelRoot), opts.posts ?? readXTrendingPosts(channelRoot), ]); const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); const threadOf = new Map(); const members = new Map(); for (const p of byId.values()) { const key = xTrendingThreadOf(p, membership, byId); threadOf.set(p.id, key); members.set(key, [...(members.get(key) ?? []), p.id]); } return withJsonFileLock(xTrendingJudgementsPath(channelRoot), async () => { const file = await readXTrendingJudgementsFile(channelRoot); const effective = (id: string) => xTrendingEffectiveJudgement(file.posts[id], file.threads[threadOf.get(id) ?? ""])?.state; const before = new Map([...byId.keys()].map((id) => [id, effective(id)])); const written: XTrendingJudged[] = []; const skipped: XTrendingJudgeSkipped[] = []; for (const item of ask.set) { const isThread = item.thread !== undefined; const key = (isThread ? item.thread : item.id) as string; const name = isThread ? { thread: key } : { id: key }; if (isThread ? !members.has(key) : !byId.has(key)) { skipped.push({ ...name, reason: NOT_IN_THE_LIBRARY }); continue; } const map = isThread ? file.threads : file.posts; const have: XTrendingJudgement | undefined = map[key]; // AN AGENT NEVER WRITES WHERE THE OPERATOR HAS DECIDED (review 2 N2): not // over the operator's entry for this key, and not a post-level entry // for a post whose THREAD the operator judged — whether or not the post // has an (agent's) entry of its own already. The operator's judgement // is the one in force there (xTrendingEffectiveJudgement), and an // agent's write would only be noise beside it. const threads = isThread ? undefined : file.threads[threadOf.get(key) ?? ""]; if (ask.by === "agent" && (have?.by === "operator" || threads?.by === "operator")) { skipped.push({ ...name, reason: JUDGED_BY_OPERATOR }); continue; } if (item.state === "undecided") { if (have) delete map[key]; } else { const note = item.note?.trim(); map[key] = { state: item.state, ...(note ? { note } : {}), by: ask.by, at }; } written.push({ ...name, state: item.state }); } if (written.length > 0) { await writeJsonAtomic(xTrendingJudgementsPath(channelRoot), file, { mkdir: true }); } const kept = [...byId.keys()].filter((id) => effective(id) === "keep" && before.get(id) !== "keep").sort(); return { written, skipped, kept }; }); } // The posts whose judgement is keep — their own, or their thread's. export async function readXTrendingKeptIds(channelRoot: string): Promise> { const [membership, posts, file] = await Promise.all([ readXTrendingMembership(channelRoot), readXTrendingPosts(channelRoot), readXTrendingJudgementsFile(channelRoot), ]); const byId = new Map(posts.filter((p) => membership[p.id]).map((p) => [p.id, p])); const kept = new Set(); for (const p of byId.values()) { const state = xTrendingEffectiveJudgement(file.posts[p.id], file.threads[xTrendingThreadOf(p, membership, byId)])?.state; if (state === "keep") kept.add(p.id); } return kept; }