// `umtool library …` (lane posts-library): the Posts library page's reads and // presses from a shell, through the SAME calls (lib/library/client.mjs) to the // editor — the listing, judge-trending, watch-trending, purge-trending — and // Mark seen (lib/library/seen.mjs). umtool writes no file of a library and // asks X nothing. // // WHO IS ASKING. `--by` is "agent" unless told otherwise, as `pnpm ops` is: an // agent's judgement is a suggestion the operator's outranks, a failing watch is // restarted only by the operator, and a purge's removal is the operator's // (`--by operator`, with the `--confirm` its `--dry-run` printed). Lane // x-trending-publish: `rename` and `move` are anyone's and record who; a // `merge` (no unmerge) and a `publish` are the operator's (`--by operator`). // // Needs the editor at ARCHILYZER_EDITOR_URL (default http://localhost:3001) and // WORKER_TOKEN (else the editor's env files). Exit 1 on a refusal. // // Plain ESM. import { agentToken } from "../annotations/agentAuth.mjs"; import { REPORTS_ROOT } from "../paths.mjs"; import { archiveAccount, archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listAccounts, listLibraries, listLibrary, listLibraryIds, organise, publish, purge, watch } from "./client.mjs"; import { markSeen, mergeSeen, seenOf } from "./seen.mjs"; const VALUE_FLAGS = new Set(["--topic", "--state", "--author", "--q", "--limit", "--offset", "--id", "--thread", "--note", "--by", "--interval", "--hours", "--confirm", "--where", "--title", "--to", "--into", "--from", "--channel", "--name"]); const BOOL_FLAGS = new Set(["--json", "--gone", "--media", "--new", "--filter", "--yes", "--dry-run", "--no-archive", "--shots", "--all", "--create", "--fetch"]); export const LIBRARY_USAGE = [ "umtool library [ls] [--json] the editor's X trending libraries", "umtool library topics [--json] a library's topics: posts, unjudged, new, the watch", "umtool library posts [--topic T] [--state unjudged|keep|drop|later] [--gone] [--media]", " [--author H] [--q TEXT] [--new] [--limit N] [--offset N] [--json]", "umtool library judge --state keep|drop|later|undecided (--id ID[,ID…] | --thread ID[,ID…] |", " --filter [--where unjudged|keep|drop|later] [the posts filters] (--dry-run | --yes))", " [--note TEXT] [--no-archive] [--by agent|operator]", "umtool library watch on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", "umtool library purge [--topic T] (--dry-run | --confirm DIGEST --by operator)", "umtool library seen (… | --all) --by operator Mark seen: what `--new` counts from (the operator's mark)", "umtool library rename --title NAME [--by agent|operator] a topic's name (its id stays)", "umtool library move --to TOPIC (--id ID[,ID…] | --thread ID) [--create] [--by agent|operator]", " posts into another topic (--create makes it)", "umtool library merge --into TOPIC --from T[,T…] --by operator topics into one: the operator's, no unmerge", "umtool library publish [--channel SLUG] (--dry-run | --confirm DIGEST --by operator)", " the operator's kept posts into a channel on no site", "umtool library accounts [--topic T] [--limit N] [--json] the library's accounts: posts, kept, topics", "umtool library archive [--name NAME] [--dry-run] [--fetch]", " -x on no site, with sync off; asks X nothing unless --fetch", ].join("\n"); class Refusal extends Error {} function parse(args) { const flags = {}; const words = []; for (let i = 0; i < args.length; i++) { const a = args[i]; const eq = a.startsWith("--") && a.includes("=") ? a.indexOf("=") : -1; const name = eq > 0 ? a.slice(0, eq) : a; if (VALUE_FLAGS.has(name)) { const v = eq > 0 ? a.slice(eq + 1) : args[++i]; if (v === undefined) throw new Refusal(`${name} needs a value`); flags[name] = v; } else if (BOOL_FLAGS.has(name) && eq < 0) flags[name] = true; else if (a.startsWith("--")) throw new Refusal(`library: unknown flag ${name}`); else words.push(a); } return { flags, words }; } const whole = (flags, name, min) => { if (flags[name] === undefined) return undefined; const n = Number(flags[name]); if (!Number.isInteger(n) || n < min) throw new Refusal(`${name} is a whole number, ${min} or more`); return n; }; function byOf(flags) { const by = flags["--by"] ?? "agent"; if (by !== "agent" && by !== "operator") throw new Refusal(`--by is "agent" or "operator"`); return by; } const need = (lib) => { if (!lib) throw new Refusal(`library: name the library (\`umtool library ls\` lists them)`); return lib; }; async function filterOf(flags, lib, reportsRoot) { if (flags["--state"] !== undefined && !LIBRARY_STATES.includes(flags["--state"])) throw new Refusal(`the judgement to filter by is one of ${LIBRARY_STATES.join(", ")}`); let since = null; if (flags["--new"]) { if (!flags["--topic"]) throw new Refusal("--new goes with --topic: each topic is marked seen on its own"); since = (await seenOf(reportsRoot, lib))[flags["--topic"]] ?? null; } return { slug: lib, topic: flags["--topic"] ?? null, state: flags["--state"] ?? null, gone: !!flags["--gone"], media: !!flags["--media"], author: flags["--author"] ?? null, q: flags["--q"] ?? null, since }; } const line = (p) => { const j = p.judgement ? `${p.judgement.state}${p.judgement.from === "thread" ? " (thread)" : ""} by ${p.judgement.by}` : "unjudged"; const gone = (p.gone ? ` · gone from the page at ${p.gone.at}` : "") + (p.goneTabs ?? []).map((g) => ` · gone from the "${g.tab}" tab at ${g.at}`).join(""); const capture = p.capture ? ` · capture: ${p.capture.state} at ${p.capture.at}` : ""; return `${p.id} @${p.author} ${j}${gone}${capture}\n ${String(p.text).replace(/\s+/g, " ").slice(0, 160)}`; }; /** * @param {string[]} args what follows `library` * @param {{ ask?: Function, out?: (s: string) => void, err?: (s: string) => void, reportsRoot?: string, env?: Record }} [deps] * @returns {Promise} the exit code */ export async function libraryCommand(args, deps = {}) { const out = deps.out ?? ((s) => console.log(s)); const err = deps.err ?? ((s) => console.error(s)); const env = deps.env ?? process.env; const reportsRoot = deps.reportsRoot ?? REPORTS_ROOT; const ask = deps.ask ?? editorAsker({ editorUrl: env.ARCHILYZER_EDITOR_URL ?? "http://localhost:3001", token: agentToken(env) }); try { const { flags, words } = parse(args); const json = !!flags["--json"]; const sub = words[0] ?? "ls"; const lib = words[1]; const say = (value, text) => out(json ? JSON.stringify(value, null, 2) : text); if (sub === "help") { out(LIBRARY_USAGE); return 0; } if (sub === "ls") { const libraries = await listLibraries(ask); say({ libraries }, libraries.length ? libraries.map((l) => `${l.slug} ${l.name} ${l.topics} topics · ${l.posts} posts · ${l.unjudged} unjudged`).join("\n") : "The editor has no X trending library."); return 0; } if (sub === "topics") { // One read: the topics, and each one's new posts from its Mark seen time. const seen = await seenOf(reportsRoot, need(lib)); const listing = await listLibrary(ask, { slug: lib, detail: true, limit: 1, seen }); const topics = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts })); // X's own words for each page read into the topic, and the tab its last read saw. const pages = (t) => (t.sources ?? []) .flatMap((src) => [ src.title ? ` X's title: ${src.title}` : "", src.summary ? ` X's summary: ${src.summary.length > 600 ? `${src.summary.slice(0, 599).trimEnd()}…` : src.summary}` : "", src.lastReadTabs?.length ? ` The last read saw the ${src.lastReadTabs.map((tab) => `"${tab}"`).join(" and ")} tabs.` : src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", ]) .filter(Boolean) .map((line) => `\n${line}`) .join(""); say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new${pages(t)}\n ${t.watch ? t.watch.sentence : "Not watched."}`).join("\n") : `${lib} has no topic yet.`); return 0; } if (sub === "posts") { const filter = await filterOf(flags, need(lib), reportsRoot); const listing = await listLibrary(ask, { ...filter, limit: whole(flags, "--limit", 1) ?? 50, offset: whole(flags, "--offset", 0), detail: true }); say({ slug: lib, total: listing.total, posts: listing.posts }, `${listing.total} post${listing.total === 1 ? "" : "s"}${listing.posts.length < listing.total ? ` (${listing.posts.length} shown)` : ""}\n${listing.posts.map(line).join("\n")}`.trimEnd()); return 0; } if (sub === "judge") { need(lib); const state = flags["--state"]; if (!JUDGE_STATES.includes(state)) throw new Refusal(`judge: --state is one of ${JUDGE_STATES.join(", ")}`); const by = byOf(flags); const ways = [flags["--id"] !== undefined, flags["--thread"] !== undefined, !!flags["--filter"]].filter(Boolean).length; if (ways !== 1) throw new Refusal("judge: give --id, --thread or --filter, one of them"); const note = flags["--note"] && state !== "undecided" ? { note: flags["--note"] } : {}; let set; if (flags["--filter"]) { // --state is the judgement to WRITE; the posts' judgement now is --where. const ids = await listLibraryIds(ask, { ...(await filterOf({ ...flags, "--state": flags["--where"] }, lib, reportsRoot)) }); if (flags["--dry-run"] || !flags["--yes"]) { say({ slug: lib, dryRun: true, state, posts: ids.length, ids }, `${ids.length} post${ids.length === 1 ? "" : "s"} would be judged ${state}${flags["--dry-run"] ? "" : " (--yes judges them)"}.`); return flags["--dry-run"] ? 0 : 1; } set = ids.map((id) => ({ id, state, ...note })); if (!set.length) { say({ slug: lib, written: [], skipped: [], kept: [], archives: [] }, "No post matches: nothing judged."); return 0; } } else { const key = flags["--id"] !== undefined ? "id" : "thread"; set = String(flags[`--${key}`]).split(",").map((s) => s.trim()).filter(Boolean).map((id) => ({ [key]: id, state, ...note })); if (!set.length) throw new Refusal(`judge: --${key} names no post`); } const result = await judge(ask, { slug: lib, by, set, ...(flags["--no-archive"] ? { archive: false } : {}) }); const skipped = result.skipped.map((s) => `\n skipped ${s.id ?? s.thread}: ${s.reason}`).join(""); say({ slug: lib, by, ...result }, `${result.written.length} judgement${result.written.length === 1 ? "" : "s"} written as the ${by}'s.${skipped}${archiveSentence(result) ? `\n${archiveSentence(result)}` : ""}`); return 0; } if (sub === "watch") { need(lib); const [topic, to] = [words[2], words[3]]; if (!topic || (to !== "on" && to !== "off")) throw new Refusal("watch: umtool library watch on|off"); const interval = whole(flags, "--interval", 1); const hours = whole(flags, "--hours", 1); const result = await watch(ask, { slug: lib, topic, on: to === "on", ...(to === "on" && interval !== undefined ? { intervalMinutes: interval } : {}), ...(to === "on" && hours !== undefined ? { hours } : {}), ...(to === "on" && flags["--shots"] ? { shots: true } : {}), by: byOf(flags), }); say(result, String(result.sentence ?? "")); return 0; } if (sub === "purge") { need(lib); const scope = { slug: lib, ...(flags["--topic"] ? { topic: flags["--topic"] } : {}) }; const by = byOf(flags); if (flags["--dry-run"]) { const plan = await purge(ask, { ...scope, dryRun: true, by }); say(plan, `${plan.sentence}\n${plan.posts} to remove · ${(plan.gone ?? []).length} of them gone from the page · ${plan.agentDropped ?? 0} dropped by an agent, left alone${plan.posts ? `\nconfirm: ${plan.confirm} (umtool library purge ${lib}${flags["--topic"] ? ` --topic ${flags["--topic"]}` : ""} --confirm ${plan.confirm} --by operator)` : ""}`); return 0; } if (!flags["--confirm"]) throw new Refusal("purge: --dry-run says what would be removed and prints the --confirm the removal needs"); const done = await purge(ask, { ...scope, confirm: flags["--confirm"], by }); say(done, String(done.sentence ?? "")); return 0; } if (sub === "seen") { need(lib); // What is "new" is the operator's to say: an agent marking topics seen would hide posts from him. if (byOf(flags) !== "operator") throw new Refusal("seen: Mark seen is the operator's (it decides what he is shown as new): say --by operator. An agent does not mark topics seen."); const known = (await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id); let topics = words.slice(2); if (flags["--all"]) topics = known; if (!topics.length) throw new Refusal("seen: name the topics, or --all"); const unknown = topics.filter((t) => !known.includes(t)); if (unknown.length) throw new Refusal(`seen: ${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked`); const marked = await markSeen(reportsRoot, { slug: lib, topics }); say({ ok: true, ...marked }, `${topics.length} topic${topics.length === 1 ? "" : "s"} marked seen: ${topics.join(", ")}`); return 0; } if (sub === "rename") { need(lib); const topic = words[2]; if (!topic || !flags["--title"]) throw new Refusal("rename: umtool library rename --title NAME"); const done = await organise(ask, { slug: lib, op: "rename", topic, title: flags["--title"], by: byOf(flags) }); say(done, String(done.sentence ?? "")); return 0; } if (sub === "move") { need(lib); if (!flags["--to"]) throw new Refusal("move: --to names the topic the posts go to"); if ((flags["--id"] !== undefined) === (flags["--thread"] !== undefined)) throw new Refusal("move: give --id or --thread, one of them"); const ids = flags["--id"] !== undefined ? String(flags["--id"]).split(",").map((x) => x.trim()).filter(Boolean) : null; if (ids && !ids.length) throw new Refusal("move: --id names no post"); const done = await organise(ask, { slug: lib, op: "move", to: flags["--to"], ...(ids ? { ids } : { thread: String(flags["--thread"]) }), ...(flags["--create"] ? { create: true } : {}), by: byOf(flags) }); const skipped = (done.skipped ?? []).map((x) => `\n skipped ${x.id}: ${x.reason}`).join(""); say(done, `${done.sentence ?? ""}${skipped}`); return 0; } if (sub === "merge") { need(lib); const from = String(flags["--from"] ?? "").split(",").map((x) => x.trim()).filter(Boolean); if (!flags["--into"] || !from.length) throw new Refusal("merge: umtool library merge --into TOPIC --from T[,T…] --by operator"); // There is no unmerge: it is the operator's, here as in the editor. if (byOf(flags) !== "operator") throw new Refusal("merge: merging topics is the operator's (it cannot be undone): say --by operator. An agent may rename a topic and move posts."); const done = await organise(ask, { slug: lib, op: "merge", into: flags["--into"], from, by: "operator" }); // umtool's own Mark seen state follows the merge (the earliest mark stands). const merged = (done.merged ?? []).map((m) => m.id); const seen = done.into?.id && merged.length ? await mergeSeen(reportsRoot, { slug: lib, into: done.into.id, from: merged }).catch((e) => ({ error: e instanceof Error ? e.message : String(e) })) : null; say({ ...done, ...(seen ? { seen } : {}) }, String(done.sentence ?? "")); return 0; } if (sub === "publish") { need(lib); const topic = words[2]; if (!topic) throw new Refusal("publish: umtool library publish (--dry-run | --confirm DIGEST --by operator)"); const scope = { slug: lib, topic, ...(flags["--channel"] ? { channel: flags["--channel"] } : {}) }; const by = byOf(flags); if (flags["--dry-run"]) { const plan = await publish(ask, { ...scope, dryRun: true, by }); say(plan, `${plan.sentence}\nchannel: ${plan.channel}${plan.creates ? " (new)" : ""} · ${plan.posts} post${plan.posts === 1 ? "" : "s"} · ${plan.files} file${plan.files === 1 ? "" : "s"} · ${plan.bytes} bytes\nconfirm: ${plan.confirm} (umtool library publish ${lib} ${topic}${flags["--channel"] ? ` --channel ${flags["--channel"]}` : ""} --confirm ${plan.confirm} --by operator)`); return 0; } if (!flags["--confirm"]) throw new Refusal("publish: --dry-run says what would be written and prints the --confirm the publish needs"); if (by !== "operator") throw new Refusal("publish: publishing a topic is the operator's: say --by operator. An agent may ask for --dry-run."); const done = await publish(ask, { ...scope, confirm: flags["--confirm"], by }); say(done, String(done.sentence ?? "")); return 0; } if (sub === "accounts") { const view = await listAccounts(ask, { slug: need(lib), topic: flags["--topic"] ?? null, limit: whole(flags, "--limit", 1) }); const rows = view.accounts ?? []; say( { slug: lib, accounts: rows, total: view.total, posts: view.posts, more: view.more }, rows.length ? `${view.total} account${view.total === 1 ? "" : "s"} over ${view.posts} post${view.posts === 1 ? "" : "s"}${view.more ? ` (${rows.length} shown)` : ""}\n${rows.map((a) => `@${a.handle} ${a.posts} post${a.posts === 1 ? "" : "s"} · ${a.kept} kept · topics: ${(a.topics ?? []).join(", ")}${a.archivedAs?.length ? ` · archived as ${a.archivedAs.join(", ")}` : ""}`).join("\n")}` : `${lib} holds no post yet.`, ); return 0; } if (sub === "archive") { need(lib); const handle = words[2]; if (!handle) throw new Refusal("archive: umtool library archive "); const done = await archiveAccount(ask, { slug: lib, handle: handle.replace(/^@/, ""), ...(flags["--name"] ? { name: flags["--name"] } : {}), ...(flags["--dry-run"] ? { dryRun: true } : {}), ...(flags["--fetch"] ? { fetch: true } : {}) }); const h = handle.replace(/^@/, ""); const text = flags["--dry-run"] ? `Would make the channel "${done.slug}" for @${h}, on no site${flags["--fetch"] ? ", and start its first fetch" : ", with sync off. Nothing is asked of X"}. A dry run creates nothing.` : flags["--fetch"] ? `Made the channel "${done.slug}" for @${h}, on no site. Its first fetch was started${done.jobIds?.length ? ` (${done.jobIds.join(", ")})` : ""}.` : // The editor's own sentence: sync off, nothing asked of X, how to turn sync on and run the first fetch. String(done.sentence ?? `Made the channel "${done.slug}" for @${h}, on no site.`); say(done, text); return 0; } throw new Refusal(`library: unknown verb "${sub}"\n${LIBRARY_USAGE}`); } catch (e) { err(e instanceof Error ? e.message : String(e)); return 1; } }