Archilyzer · Source

archilyzer

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

commit ea059c80d8ad8a9cb0062f6e3d731e9b66c06c94
parent 3f9c12eeffbf3cd7d8101b67856b977fb67fdcf8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 10:50:03 -0500

umtool: the Posts library organises, publishes and archives -- rename, merge and move on the page and in `umtool library`; Publish kept posts in two presses; an Accounts panel with Archive this account

Every press is the editor's action (organise-trending, publish-trending,
x-search-lead's archive) through three new press routes that, like the
others, take a press from umtool's own page in a browser only and stamp it
the operator's. `umtool library rename | move | merge | publish | accounts
| archive` are the same calls from a shell: --by is "agent" unless told,
and a merge and a publish are refused there without --by operator before
the editor is asked. A merge is asked twice and says it cannot be undone;
umtool's own Mark seen state follows it (the earliest of the merged
topics' marks stands). Publish shows the editor's dry run (the slug, posts,
files, bytes) and lets the slug be changed before a first publish. Archive
this account never sends "fetch": the page says it asks X nothing.

The pin that lists what the page may ask the editor now names the three
new asks as the only ways out of a library, the lead action as "archive"
only, and that no site is named to the editor from there. umtool docs
regenerated.

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

Diffstat:
Aumtool/app/api/library/accounts/route.ts | 31+++++++++++++++++++++++++++++++
Aumtool/app/api/library/archive/route.ts | 16++++++++++++++++
Aumtool/app/api/library/organise/route.ts | 19+++++++++++++++++++
Aumtool/app/api/library/publish/route.ts | 16++++++++++++++++
Mumtool/components/tools/library/LibraryView.tsx | 15+++++++--------
Aumtool/components/tools/library/OrganisePanel.tsx | 334+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 10++++++++++
Mumtool/docs/tools.md | 16+++++++++++++++-
Mumtool/lib/cli/groups.mjs | 12++++++++++++
Mumtool/lib/cli/verbs.mjs | 6++++++
Mumtool/lib/library/caller.mjs | 2+-
Mumtool/lib/library/cli.mjs | 90++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/library/client.mjs | 39+++++++++++++++++++++++++++++++++++++--
Mumtool/lib/library/load.ts | 3++-
Aumtool/lib/library/organise.test.mjs | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/library/presses.mjs | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/library/seen.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/report/xTrendingLibrary.test.mjs | 16++++++++++++++--
18 files changed, 974 insertions(+), 39 deletions(-)

diff --git a/umtool/app/api/library/accounts/route.ts b/umtool/app/api/library/accounts/route.ts @@ -0,0 +1,31 @@ +import { askEditor } from "@/lib/articles/generation"; +import { listAccounts } from "@/lib/library/client.mjs"; +import { unavailableSentence } from "@/lib/library/load"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// GET /api/library/accounts?lib=&topic= -> { ok: true, accounts: [{handle, name?, posts, kept, keptByOperator, +// topics, last, archivedAs?}], total, posts, more } or { ok: false, sentence } +// +// THE LIBRARY'S ACCOUNTS (lane x-trending-publish), read THROUGH THE EDITOR +// (GET /api/ops/trending?accounts=1) when the page's Accounts panel is +// opened. READ ONLY, and a private library's: a cross-site request is +// refused, and nothing caches it. +const PRIVATE = { "cache-control": "private, no-store", "cross-origin-resource-policy": "same-origin" }; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export async function GET(request: Request) { + if (crossSiteRefusal(request.headers)) return Response.json({ error: "refused: the library is read by umtool's own pages only" }, { status: 403, headers: PRIVATE }); + const sp = new URL(request.url).searchParams; + const lib = sp.get("lib") ?? ""; + const topic = sp.get("topic") ?? ""; + if (!SLUG.test(lib)) return Response.json({ ok: false, sentence: `"lib" is the library's slug` }, { status: 400, headers: PRIVATE }); + try { + const ask = (route: string) => askEditor<Record<string, unknown>>(route, { fresh: true }); + const answer = await listAccounts(ask, { slug: lib, ...(topic ? { topic } : {}), limit: 200 }); + return Response.json({ ok: true, accounts: answer.accounts ?? [], total: answer.total ?? 0, posts: answer.posts ?? 0, more: answer.more ?? 0 }, { headers: PRIVATE }); + } catch (err) { + return Response.json({ ok: false, ...unavailableSentence(err) }, { headers: PRIVATE }); + } +} diff --git a/umtool/app/api/library/archive/route.ts b/umtool/app/api/library/archive/route.ts @@ -0,0 +1,16 @@ +import { archivePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, handle, name?, dryRun? } -> { ok, slug, dryRun?, fields?, jobIds?, sentence } +// +// THE POSTS LIBRARY PAGE'S "ARCHIVE THIS ACCOUNT" (lane x-trending-publish): +// the editor's `x-search-lead`, action "archive", for an account that wrote a +// post the library holds — `<handle>-x`, an X channel on NO site that names +// nothing of the library. The page's press only (lib/library/route.ts). IT +// ASKS X NOTHING: this route never sends "fetch"; the new channel's first +// fetch is a separate press in the editor. +export async function POST(request: Request) { + return press(request, (body) => archivePress(ask, body)); +} diff --git a/umtool/app/api/library/organise/route.ts b/umtool/app/api/library/organise/route.ts @@ -0,0 +1,19 @@ +import { organisePress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; +import { mergeSeen } from "@/lib/library/seen.mjs"; +import { REPORTS_ROOT } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// POST { lib, op: "rename", topic, title } -> { topic, title, was, changed, sentence } +// POST { lib, op: "move", to, ids | thread, create? } -> { to, moved, skipped, sentence } +// POST { lib, op: "merge", into, from: [topic, …] } -> { into, merged, posts, pages, watch, sentence, seen? } +// +// THE POSTS LIBRARY PAGE'S ORGANISING (lane x-trending-publish): the editor's +// `organise-trending`, written as the OPERATOR's (the page's press only: +// lib/library/route.ts). umtool writes no file of the library. A merge cannot +// be undone; after one, umtool's own Mark seen state follows it (the earliest +// of the merged topics' marks stands: lib/library/seen.mjs mergeSeen). +export async function POST(request: Request) { + return press(request, (body) => organisePress(ask, body, { mergeSeen: (lib: string, into: string, from: string[]) => mergeSeen(REPORTS_ROOT, { slug: lib, into, from }) })); +} diff --git a/umtool/app/api/library/publish/route.ts b/umtool/app/api/library/publish/route.ts @@ -0,0 +1,16 @@ +import { publishPress } from "@/lib/library/presses.mjs"; +import { ask, press } from "@/lib/library/route"; + +export const dynamic = "force-dynamic"; + +// POST { lib, topic, dryRun: true, channel? } -> what would be written: { channel, creates, posts, files, bytes, textOnly, noLongerKept, confirm, sentence, … } +// POST { lib, topic, confirm, channel? } -> published, when it is still what the dry run showed +// +// THE POSTS LIBRARY PAGE'S PUBLISH (lane x-trending-publish): the editor's +// `publish-trending`, the OPERATOR's, in two presses (the page's press only: +// lib/library/route.ts). The topic's posts the operator kept go into an +// ordinary posts channel on NO site; umtool writes nothing itself, and adding +// the channel to a site stays a separate act in the editor. +export async function POST(request: Request) { + return press(request, (body) => publishPress(ask, body)); +} diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx @@ -14,6 +14,7 @@ import { libraryMediaSrc } from "@/lib/library/mediaSrc.mjs"; import { pressSetOf, UNDO_SAYS, undoSetOf } from "@/lib/library/undo.mjs"; import type { LibraryData, LibraryPost, LibraryTopic, LibraryView as View } from "@/lib/library/load"; import { cn } from "@/lib/utils"; +import { AccountsPanel, MoveControl, send, TopicOrganise } from "./OrganisePanel"; // THE POSTS LIBRARY (app/tools/library/page.tsx): topics on the left, the // posts of the view with their captured media in the body, and the presses. @@ -67,12 +68,6 @@ export function utc(iso: string): string { return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}, ${p(d.getUTCHours())}:${p(d.getUTCMinutes())} UTC`; } -async function send(path: string, body: unknown): Promise<Record<string, unknown>> { - const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); - const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; - if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); - return j; -} /** The archive row a library post is drawn from. Never marked deleted: the library records no such thing. */ function postOf(lib: string, row: LibraryPost): Post { @@ -369,7 +364,8 @@ export default function LibraryView({ data: opened }: { data: Ok }) { <section className="min-w-0"> {/* A purge takes the undo memory with it: an undo must never put back a keep whose capture was just removed. */} - <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} onPurged={() => setLast(null)} /> + <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} onPurged={() => setLast(null)} go={(id) => router.push(here({ topic: id }))} /> + <AccountsPanel key={`accounts-${topic?.id ?? "all"}`} lib={lib} topic={topic?.id ?? null} topics={topics} off={off} run={run} /> {/* ── filters: links and one plain form, so they work before the page is alive ── */} <div data-library-filters="" className="mb-3 mt-3 flex flex-wrap items-center gap-x-2 gap-y-2"> @@ -640,6 +636,7 @@ export default function LibraryView({ data: opened }: { data: Ok }) { </Button> ))} </span> + <MoveControl lib={lib} topics={topics} here={topic?.id ?? null} targets={targetsOf(current)} off={off} run={run} /> <Button size="sm" disabled={off || !last} data-library-undo="" title={UNDO_SAYS} onClick={() => void undo()}> Undo </Button> @@ -726,7 +723,7 @@ function TopicList({ topics, view, here, lib }: { topics: LibraryTopic[]; view: ); } -function TopicPanel({ lib, topic, topics, off, run, onPurged }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void>; onPurged: () => void }) { +function TopicPanel({ lib, topic, topics, off, run, onPurged, go }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void>; onPurged: () => void; go: (topicId: string) => void }) { const w = topic?.watch; const live = !!w && w.on && !w.ended; const failing = live && w?.paused?.reason === "failing"; @@ -836,6 +833,8 @@ function TopicPanel({ lib, topic, topics, off, run, onPurged }: { lib: string; t Purge dropped posts’ captures… </Button> </div> + {/* Rename, merge and publish: the topic's own (lane x-trending-publish). */} + {topic && <TopicOrganise key={`${topic.id}:${topic.title}`} lib={lib} topic={topic} topics={topics} off={off} run={run} go={go} when={utc} />} {plan && ( <div role="alertdialog" aria-label="Purge" data-library-purge-plan={plan.posts} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> <p className="m-0" data-library-purge-sentence=""> diff --git a/umtool/components/tools/library/OrganisePanel.tsx b/umtool/components/tools/library/OrganisePanel.tsx @@ -0,0 +1,334 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import type { LibraryTopic } from "@/lib/library/load"; + +// ORGANISE, PUBLISH AND THE ACCOUNTS of the Posts library page (lane +// x-trending-publish). Every press is a POST to /api/library/*, which is the +// editor's action written as the operator's; nothing here writes a library's +// file or asks X anything. +// +// rename the topic's name; its id stays +// merge this topic INTO another: there is no unmerge, so it is asked +// twice, and the second press says so +// move the posts a press would judge (the selection, else the post or +// its thread) into another topic +// publish the posts the operator KEPT, into an ordinary channel on no +// site: the first press says exactly what would be written +// accounts who wrote the library's posts; "Archive this account" makes +// <handle>-x on no site and asks X nothing + +type Run = (what: () => Promise<string | void>) => Promise<void>; + +export async function send(path: string, body: unknown): Promise<Record<string, unknown>> { + const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const j = (await r.json().catch(() => ({}))) as Record<string, unknown>; + if (!r.ok) throw new Error(typeof j.error === "string" ? j.error : `HTTP ${r.status}`); + return j; +} + +const field = "rounded-[3px] border border-seam-2 bg-panel px-2 py-[3px] text-[12.5px] text-text"; + +export function bytesSaid(n: number): string { + if (n < 1024) return `${n} B`; + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; + if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`; + return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`; +} + +type PublishPlan = { + channel: string; + creates: boolean; + kept: number; + posts: number; + already: number; + files: number; + bytes: number; + textOnly?: string[]; + noLongerKept?: string[]; + inFlight?: boolean; + confirm: string; + sentence: string; +}; + +export function TopicOrganise({ lib, topic, topics, off, run, go, when }: { lib: string; topic: LibraryTopic; topics: LibraryTopic[]; off: boolean; run: Run; go: (topicId: string) => void; when: (iso: string) => string }) { + const [title, setTitle] = useState(topic.title); + const others = topics.filter((t) => t.id !== topic.id); + const [into, setInto] = useState(""); + const [merging, setMerging] = useState(false); + const [plan, setPlan] = useState<PublishPlan | null>(null); + const [channel, setChannel] = useState(""); + const target = others.find((t) => t.id === into) ?? null; + const published = topic.published; + const kept = topic.counts?.keep ?? 0; + + const dryRun = (slug: string) => + run(async () => { + const r = (await send("/api/library/publish", { lib, topic: topic.id, dryRun: true, ...(slug ? { channel: slug } : {}) })) as unknown as PublishPlan; + setPlan(r); + setChannel(r.channel); + }); + + return ( + <div className="mt-3 border-t border-seam pt-2" data-library-organise={topic.id}> + <div className="flex flex-wrap items-end gap-x-3 gap-y-2 text-[12px] text-muted"> + <label className="flex min-w-0 flex-col gap-0.5"> + name + <input type="text" value={title} maxLength={120} onChange={(e) => setTitle(e.target.value)} data-library-rename-input="" className={`${field} w-[14rem] max-w-full`} /> + </label> + <Button + size="sm" + disabled={off || !title.trim() || title.trim() === topic.title} + data-library-rename="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "rename", topic: topic.id, title }); + return String(r.sentence ?? ""); + }) + } + > + Rename + </Button> + {others.length > 0 && ( + <> + <label className="flex min-w-0 flex-col gap-0.5"> + merge this topic into + <select value={into} onChange={(e) => { setInto(e.target.value); setMerging(false); }} data-library-merge-into="" className={`${field} max-w-[14rem]`}> + <option value="">choose a topic</option> + {others.map((t) => ( + <option key={t.id} value={t.id}> + {t.title} + </option> + ))} + </select> + </label> + <Button size="sm" disabled={off || !target} data-library-merge="" onClick={() => setMerging(true)}> + Merge… + </Button> + </> + )} + </div> + {merging && target && ( + <div role="alertdialog" aria-label="Merge" data-library-merge-plan={target.id} className="mt-2 rounded-md border border-reject-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-merge-sentence=""> + Merge “{topic.title}” into “{target.title}”? Its {topic.posts} post{topic.posts === 1 ? "" : "s"} and {topic.sources.length} trending page{topic.sources.length === 1 ? "" : "s"} move there and “{topic.title}” is gone. The judgements are + untouched. This cannot be undone: there is no unmerge. + {topic.watch && target.watch && topic.watch.on && target.watch.on && !topic.watch.ended && !target.watch.ended + ? ` Both are watched: the watch of “${target.title}” stands with its own terms, and this topic's watch is gone.` + : topic.watch && topic.watch.on && !topic.watch.ended + ? ` This topic's watch becomes the watch of “${target.title}”.` + : ""} + </p> + <div className="mt-1.5 flex flex-wrap gap-1.5"> + <Button + size="sm" + variant="go" + disabled={off} + data-library-merge-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "merge", into: target.id, from: [topic.id] }); + setMerging(false); + go(target.id); + return String(r.sentence ?? ""); + }) + } + > + Merge into “{target.title}” + </Button> + <Button size="sm" data-library-merge-no="" onClick={() => setMerging(false)}> + Cancel + </Button> + </div> + </div> + )} + + <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1.5"> + <Button size="sm" disabled={off || kept === 0} data-library-publish="" title="The posts the operator kept, into a channel on no site" onClick={() => void dryRun("")}> + Publish kept posts… + </Button> + <span className="text-[11.5px] text-muted" data-library-published={published?.channel ?? ""}> + {published + ? `Published into the channel “${published.channel}”: ${published.posts} post${published.posts === 1 ? "" : "s"}, last ${when(published.lastAt)}.` + : "Not published."} + </span> + </div> + {plan && ( + <div role="alertdialog" aria-label="Publish" data-library-publish-plan={plan.posts} className="mt-2 rounded-md border border-doubt-text p-2 text-[12.5px] text-text"> + <p className="m-0" data-library-publish-sentence=""> + {plan.sentence} + </p> + <p className="m-0 mt-1 text-muted" data-library-publish-numbers=""> + channel {plan.channel} + {plan.creates ? " (new, on no site)" : ""} · {plan.posts} post{plan.posts === 1 ? "" : "s"} to add · {plan.files} file{plan.files === 1 ? "" : "s"} · {bytesSaid(plan.bytes)} · {plan.already} there already + {(plan.textOnly ?? []).length ? ` · ${(plan.textOnly ?? []).length} as words alone` : ""} + {(plan.noLongerKept ?? []).length ? ` · ${(plan.noLongerKept ?? []).length} no longer kept, left` : ""} + </p> + {plan.creates && !published && ( + <div className="mt-1.5 flex flex-wrap items-end gap-x-2 gap-y-1.5 text-[12px] text-muted"> + <label className="flex min-w-0 flex-col gap-0.5"> + the channel’s slug + <input type="text" value={channel} onChange={(e) => setChannel(e.target.value.trim())} data-library-publish-channel="" className={`${field} w-[14rem] max-w-full`} /> + </label> + <Button size="sm" disabled={off || !channel || channel === plan.channel} data-library-publish-recount="" onClick={() => void dryRun(channel)}> + Use this slug + </Button> + </div> + )} + <div className="mt-1.5 flex flex-wrap gap-1.5"> + {(plan.posts > 0 || plan.files > 0 || plan.creates) && ( + <Button + size="sm" + variant="go" + disabled={off || plan.inFlight === true || channel !== plan.channel} + data-library-publish-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/publish", { lib, topic: topic.id, confirm: plan.confirm, ...(plan.creates && !published ? { channel: plan.channel } : {}) }); + setPlan(null); + return String(r.sentence ?? ""); + }) + } + > + Publish {plan.posts} post{plan.posts === 1 ? "" : "s"} into “{plan.channel}” + </Button> + )} + <Button size="sm" data-library-publish-no="" onClick={() => setPlan(null)}> + {plan.posts > 0 || plan.files > 0 || plan.creates ? "Cancel" : "Close"} + </Button> + </div> + </div> + )} + </div> + ); +} + +/** The bar's move: the posts a press would judge, into another topic. */ +export function MoveControl({ lib, topics, here, targets, off, run }: { lib: string; topics: LibraryTopic[]; here: string | null; targets: Array<{ id: string } | { thread: string }>; off: boolean; run: Run }) { + const [to, setTo] = useState(""); + const choices = topics.filter((t) => t.id !== here); + if (topics.length < 2) return null; + const ids = targets.flatMap((t) => ("id" in t ? [t.id] : [])); + const thread = targets.length === 1 && "thread" in targets[0] ? targets[0].thread : null; + return ( + <span className="inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted" data-library-move-control=""> + Move to: + <select value={to} onChange={(e) => setTo(e.target.value)} aria-label="Move to topic" data-library-move-to="" className={`${field} max-w-[11rem]`}> + <option value="">a topic</option> + {choices.map((t) => ( + <option key={t.id} value={t.id}> + {t.title} + </option> + ))} + </select> + <Button + size="sm" + disabled={off || !to || targets.length === 0} + data-library-move="" + onClick={() => + void run(async () => { + const r = await send("/api/library/organise", { lib, op: "move", to, ...(thread ? { thread } : { ids }) }); + return String(r.sentence ?? ""); + }) + } + > + Move + </Button> + </span> + ); +} + +type Account = { handle: string; name?: string; posts: number; kept: number; keptByOperator?: number; topics?: string[]; archivedAs?: string[] }; + +export function AccountsPanel({ lib, topic, topics, off, run }: { lib: string; topic: string | null; topics: LibraryTopic[]; off: boolean; run: Run }) { + const [open, setOpen] = useState(false); + const [state, setState] = useState<{ accounts: Account[]; total: number; more: number } | { sentence: string } | null>(null); + const [asking, setAsking] = useState<string | null>(null); + const [made, setMade] = useState<Record<string, string>>({}); + const names = new Map(topics.map((t) => [t.id, t.title])); + + useEffect(() => { + if (!open) return; + let live = true; + setState(null); + fetch(`/api/library/accounts?lib=${encodeURIComponent(lib)}${topic ? `&topic=${encodeURIComponent(topic)}` : ""}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j: { ok?: boolean; accounts?: Account[]; total?: number; more?: number; sentence?: string; error?: string }) => { + if (!live) return; + setState(j.ok ? { accounts: j.accounts ?? [], total: j.total ?? 0, more: j.more ?? 0 } : { sentence: j.sentence ?? j.error ?? "The accounts could not be read." }); + }) + .catch((err) => live && setState({ sentence: `The accounts could not be read: ${err instanceof Error ? err.message : String(err)}` })); + return () => { + live = false; + }; + }, [open, lib, topic]); + + return ( + <details className="mt-3 rounded-md border border-seam p-3" data-library-accounts={open ? "open" : "closed"} onToggle={(e) => setOpen((e.currentTarget as HTMLDetailsElement).open)}> + <summary className="cursor-pointer text-[12.5px] text-text">Accounts{topic ? " in this topic" : " in the library"}</summary> + {open && !state && <p className="m-0 mt-2 text-[12.5px] text-muted">Reading the accounts…</p>} + {state && "sentence" in state && ( + <p className="m-0 mt-2 text-[12.5px] text-reject-text" data-library-accounts-error=""> + {state.sentence} + </p> + )} + {state && "accounts" in state && ( + <> + <p className="m-0 mt-2 text-[12px] text-muted" data-library-accounts-count={state.total}> + {state.total} account{state.total === 1 ? "" : "s"} + {state.more ? `, the first ${state.accounts.length} shown` : ""}. Archiving one makes its own X channel, on no site, and asks X nothing: its first fetch is a separate press in the editor. + </p> + <ul className="m-0 mt-2 list-none space-y-1.5 p-0"> + {state.accounts.map((a) => { + const archived = made[a.handle] ? [made[a.handle]] : (a.archivedAs ?? []); + return ( + <li key={a.handle} data-library-account={a.handle} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12.5px] text-text-2"> + <span className="min-w-0 break-words text-text"> + @{a.handle} + {a.name ? <span className="text-muted"> {a.name}</span> : null} + </span> + <span className="text-muted"> + {a.posts} post{a.posts === 1 ? "" : "s"} · {a.kept} kept{topic ? "" : ` · ${(a.topics ?? []).map((t) => names.get(t) ?? t).join(", ")}`} + </span> + {archived.length > 0 ? ( + <span className="text-muted" data-library-account-archived=""> + archived as {archived.join(", ")} + </span> + ) : asking === a.handle ? ( + <span role="alertdialog" aria-label="Archive this account" className="inline-flex flex-wrap items-center gap-1.5" data-library-archive-plan={a.handle}> + Makes the channel “{a.handle.toLowerCase()}-x”, on no site. Nothing is asked of X. + <Button + size="sm" + variant="go" + disabled={off} + data-library-archive-yes="" + onClick={() => + void run(async () => { + const r = await send("/api/library/archive", { lib, handle: a.handle, ...(a.name ? { name: a.name } : {}) }); + setAsking(null); + if (typeof r.slug === "string") setMade((m) => ({ ...m, [a.handle]: r.slug as string })); + return String(r.sentence ?? ""); + }) + } + > + Make the channel + </Button> + <Button size="sm" data-library-archive-no="" onClick={() => setAsking(null)}> + Cancel + </Button> + </span> + ) : ( + <Button size="sm" disabled={off} data-library-archive="" onClick={() => setAsking(a.handle)}> + Archive this account… + </Button> + )} + </li> + ); + })} + </ul> + </> + )} + </details> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -100,6 +100,10 @@ Inbox cannot disagree about what is wrong with one. | `library watch <lib> <topic> on\|off [--interval MIN] [--hours H] [--shots] [--by agent\|operator]` | the editor's `watch-trending` for one topic. A watch runs only while X's cookie jar is fresh, and one paused as failing is switched on again only with `--by operator`; the editor's refusal is printed, **exit 1** | | `library purge <lib> [--topic T] (--dry-run \| --confirm DIGEST --by operator)` | the editor's `purge-trending`, in two steps: `--dry-run` says what would be removed (the captures of posts THE OPERATOR dropped: posts, files, bytes; how many of them are gone from the page, whose capture is the only copy; how many an agent dropped, which are never purged) and prints the `--confirm` digest; the removal carries it and `--by operator`. Judgements stay; media another post uses is left; refused while a capture is queued or running, or when the set changed since the dry run (**exit 1**) | | `library seen <lib> (<topic>… \| --all) --by operator` | Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count. **The operator's**: without `--by operator` it is refused (an agent marking topics seen would hide posts from him), and a topic the library does not hold is refused, nothing marked (**exit 1**) | +| `library rename <lib> <topic> --title NAME [--by agent\|operator]` · `library move <lib> --to TOPIC (--id ID,… \| --thread ID) [--create] [--by agent\|operator]` | the editor's `organise-trending`. **rename** changes a topic's name and nothing else (its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused). **move** puts posts, or every post of one thread, into another topic (`--create` makes a topic of that name when there is none); judgements and captures are untouched and a later read never moves a post back. Both say `agent` unless told, and who is recorded | +| `library merge <lib> --into TOPIC --from T,… --by operator` | the editor's `organise-trending`, op `merge`: every post, page and read of the `--from` topics goes into `--into`, and they are gone. **There is no unmerge, so it is the operator's**: without `--by operator` it is refused before the editor is asked (**exit 1**). Refused while a read of the library is queued or running. One watch stands (the target's, with its own terms; else the merged topic's moves to it), and the sentence says which. umtool's Mark seen state follows: the earliest of the merged topics' marks stands | +| `library publish <lib> <topic> [--channel SLUG] (--dry-run \| --confirm DIGEST --by operator)` | the editor's `publish-trending`, in two steps: `--dry-run` says exactly what would be written (the channel's slug and whether it is made, posts, files, bytes; posts published as their words alone; posts published before and no longer kept, which stay) and prints the `--confirm` digest; the publish carries it and **`--by operator`** (an agent's is refused, **exit 1**). Only posts THE OPERATOR kept are published, into an ordinary channel on NO site whose files are copies; `--channel` names the slug at the first publish only. Refused while a read or a capture of the library is queued or running | +| `library accounts <lib> [--topic T] [--limit N] [--json]` · `library archive <lib> <handle> [--name N] [--dry-run] [--fetch]` | the library's **accounts** (handle, posts, kept, topics, the X channels that already archive each), and **archive**: the editor's `x-search-lead`, action `archive`, for an account of the library: `<handle>-x`, an X channel on no site that names nothing of the library. **It asks X nothing**: the first fetch is started only with `--fetch`; `--dry-run` creates nothing | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | | `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | | `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) | @@ -297,6 +301,12 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `library watch` | watch a topic of a trending library, or stop (the editor's watch-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | | `library purge` | remove dropped posts' captures, after a dry run (the editor's purge-trending) | none: the removal is the operator's press on the Posts library page (/tools/library), in two steps | | `library seen` | mark topics of a trending library seen | none: the Posts library page's Mark seen (/tools/library) | +| `library rename` | rename a topic of a trending library; its id stays (the editor's organise-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library move` | move posts of a trending library into another topic (the editor's organise-trending) | none: the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says "agent" unless told | +| `library merge` | merge topics of a trending library into one; no unmerge (the editor's organise-trending) | none: the merge is the operator's press on the Posts library page (/tools/library), behind a confirm | +| `library publish` | publish a topic's kept posts into a channel on no site, after a dry run (the editor's publish-trending) | none: the publish is the operator's press on the Posts library page (/tools/library), in two steps | +| `library accounts` | a trending library's accounts: posts, kept, topics | none: a read the Posts library page (/tools/library) shows | +| `library archive` | archive an account of a trending library as its own X channel, on no site (the editor's x-search-lead) | none: the Posts library page's Archive this account (/tools/library) | | `library help` | the library verbs | none: prints the usage | | `pool stats [--since SINCE]` | the render pool: what it holds | form · *corpus* | | `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* | diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md @@ -48,7 +48,8 @@ A trending library is the editor's private collection of posts read off X's tren `read-x-trending`). This page is where it is judged before anything of it is published. **Everything is the editor's**: the page reads the library through the editor and every press is the editor's action, written as the operator's. umtool writes no file of a library and asks X nothing; nothing here puts a post into a project, a report, an article, the post -archive or a site. With the editor down, or no library in it, the page says so in a sentence. +archive or a site. The one way out is **Publish**: the posts the operator kept in a topic become an ordinary channel, +on no site. With the editor down, or no library in it, the page says so in a sentence. - **Topics** (left; a fold on a phone): posts, unjudged, new, and what its watch is doing. A paused watch says why; a failing one (three reads in a row that did not end as read) is restarted only by the operator: **Watch again**. @@ -71,6 +72,19 @@ archive or a site. With the editor down, or no library in it, the page says so i captures of posts **the operator** dropped: an agent's drop is a suggestion, counted and left alone. For a dropped post that is gone from the page the capture is the only copy, and the confirm says that removing it cannot be undone. Judgements stay; media another post uses is left. +- **Organise** (a topic's panel, and **Move to** in the bar): **Rename** a topic (its id stays: its watch, posts and + judgements are untouched); **Move** the posts a press would judge (the selection, else the post, or its thread) into + another topic; **Merge…** this topic into another, behind a confirm that says it **cannot be undone** and which watch + stands when both are watched (the target's, with its own terms). A merge waits while a read of the library is queued + or running. +- **Publish kept posts…** says exactly what would be written: the channel's slug (a slug of the topic's name; it can be + changed before the first publish, and is fixed after it), posts, files and bytes, how many go as their words alone + (no capture yet) and how many published before are no longer kept (they stay: a publish removes nothing). Then + **Publish**. Only posts **the operator** kept are published, into an ordinary channel **on no site** whose files are + copies. Adding that channel to a site is a separate act in the editor. Publishing again adds what was kept since. +- **Accounts**: who wrote the posts (of the topic, or of the library), with posts, kept and topics. **Archive this + account…** makes `<handle>-x`, an X channel on no site, and **asks X nothing**: its first fetch is a separate press + in the editor. An account an X channel already archives says so. | Key | | |---|---| diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -715,6 +715,10 @@ export const GROUPS = [ " watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", " purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", " seen <lib> (<topic>… | --all) --by operator Mark seen: what --new counts from", + " rename <lib> <topic> --title NAME | move <lib> --to TOPIC (--id ID,… | --thread ID) [--create] [--by agent|operator]", + " merge <lib> --into TOPIC --from T,… --by operator topics into one: no unmerge", + " publish <lib> <topic> [--channel SLUG] (--dry-run | --confirm DIGEST --by operator) kept posts into a channel on no site", + " accounts <lib> [--topic T] [--limit N] | archive <lib> <handle> [--name N] [--dry-run] [--fetch]", ], docs: [ ["`library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]`", @@ -727,6 +731,14 @@ export const GROUPS = [ "the editor's `purge-trending`, in two steps: `--dry-run` says what would be removed (the captures of posts THE OPERATOR dropped: posts, files, bytes; how many of them are gone from the page, whose capture is the only copy; how many an agent dropped, which are never purged) and prints the `--confirm` digest; the removal carries it and `--by operator`. Judgements stay; media another post uses is left; refused while a capture is queued or running, or when the set changed since the dry run (**exit 1**)"], ["`library seen <lib> (<topic>… \\| --all) --by operator`", "Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count. **The operator's**: without `--by operator` it is refused (an agent marking topics seen would hide posts from him), and a topic the library does not hold is refused, nothing marked (**exit 1**)"], + ["`library rename <lib> <topic> --title NAME [--by agent\\|operator]` · `library move <lib> --to TOPIC (--id ID,… \\| --thread ID) [--create] [--by agent\\|operator]`", + "the editor's `organise-trending`. **rename** changes a topic's name and nothing else (its id stays, so its watch, posts and judgements are untouched; a name another topic answers to is refused). **move** puts posts, or every post of one thread, into another topic (`--create` makes a topic of that name when there is none); judgements and captures are untouched and a later read never moves a post back. Both say `agent` unless told, and who is recorded"], + ["`library merge <lib> --into TOPIC --from T,… --by operator`", + "the editor's `organise-trending`, op `merge`: every post, page and read of the `--from` topics goes into `--into`, and they are gone. **There is no unmerge, so it is the operator's**: without `--by operator` it is refused before the editor is asked (**exit 1**). Refused while a read of the library is queued or running. One watch stands (the target's, with its own terms; else the merged topic's moves to it), and the sentence says which. umtool's Mark seen state follows: the earliest of the merged topics' marks stands"], + ["`library publish <lib> <topic> [--channel SLUG] (--dry-run \\| --confirm DIGEST --by operator)`", + "the editor's `publish-trending`, in two steps: `--dry-run` says exactly what would be written (the channel's slug and whether it is made, posts, files, bytes; posts published as their words alone; posts published before and no longer kept, which stay) and prints the `--confirm` digest; the publish carries it and **`--by operator`** (an agent's is refused, **exit 1**). Only posts THE OPERATOR kept are published, into an ordinary channel on NO site whose files are copies; `--channel` names the slug at the first publish only. Refused while a read or a capture of the library is queued or running"], + ["`library accounts <lib> [--topic T] [--limit N] [--json]` · `library archive <lib> <handle> [--name N] [--dry-run] [--fetch]`", + "the library's **accounts** (handle, posts, kept, topics, the X channels that already archive each), and **archive**: the editor's `x-search-lead`, action `archive`, for an account of the library: `<handle>-x`, an X channel on no site that names nothing of the library. **It asks X nothing**: the first fetch is started only with `--fetch`; `--dry-run` creates nothing"], ], }, { diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -358,6 +358,12 @@ export const VERBS = Object.freeze([ none("library watch", "corpus", "watch a topic of a trending library, or stop (the editor's watch-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), none("library purge", "corpus", "remove dropped posts' captures, after a dry run (the editor's purge-trending)", "the removal is the operator's press on the Posts library page (/tools/library), in two steps"), none("library seen", "corpus", "mark topics of a trending library seen", "the Posts library page's Mark seen (/tools/library)"), + none("library rename", "corpus", "rename a topic of a trending library; its id stays (the editor's organise-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library move", "corpus", "move posts of a trending library into another topic (the editor's organise-trending)", "the Posts library page (/tools/library) is its form: its presses are written as the operator's, and this verb says \"agent\" unless told"), + none("library merge", "corpus", "merge topics of a trending library into one; no unmerge (the editor's organise-trending)", "the merge is the operator's press on the Posts library page (/tools/library), behind a confirm"), + none("library publish", "corpus", "publish a topic's kept posts into a channel on no site, after a dry run (the editor's publish-trending)", "the publish is the operator's press on the Posts library page (/tools/library), in two steps"), + none("library accounts", "corpus", "a trending library's accounts: posts, kept, topics", "a read the Posts library page (/tools/library) shows"), + none("library archive", "corpus", "archive an account of a trending library as its own X channel, on no site (the editor's x-search-lead)", "the Posts library page's Archive this account (/tools/library)"), none("library help", "corpus", "the library verbs", "prints the usage"), form("pool stats", "corpus", "the render pool: what it holds", [opt("--since", { help: "7d" })], { shape: "pool stats" }), form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()], { confirm: { what: "delete render pool files past the cap", unless: ["--dry-run"] } }), diff --git a/umtool/lib/library/caller.mjs b/umtool/lib/library/caller.mjs @@ -19,7 +19,7 @@ import { crossSiteRefusal } from "../report/sameOrigin.mjs"; import { fromBrowser } from "../report/writeGuard.mjs"; export const AGENTS_GO_ELSEWHERE = - "This route is the Posts library page's: its presses are written as the operator's, so it takes them from umtool's own page in a browser only. An agent or a script uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` or `umtool library`, and says \"by\": \"agent\"."; + "This route is the Posts library page's: its presses are written as the operator's, so it takes them from umtool's own page in a browser only. An agent or a script uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` / `organise-trending` / `publish-trending` or `umtool library`, and says \"by\": \"agent\"."; /** * Why a request may not press, or null when it is the page's. diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -7,7 +7,9 @@ // 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). +// (`--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. @@ -15,11 +17,11 @@ // Plain ESM. import { agentToken } from "../annotations/agentAuth.mjs"; import { REPORTS_ROOT } from "../paths.mjs"; -import { archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listLibraries, listLibrary, listLibraryIds, purge, watch } from "./client.mjs"; -import { markSeen, seenOf } from "./seen.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"]); -const BOOL_FLAGS = new Set(["--json", "--gone", "--media", "--new", "--filter", "--yes", "--dry-run", "--no-archive", "--shots", "--all"]); +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", @@ -32,6 +34,15 @@ export const LIBRARY_USAGE = [ "umtool library watch <lib> <topic> on|off [--interval MIN] [--hours H] [--shots] [--by agent|operator]", "umtool library purge <lib> [--topic T] (--dry-run | --confirm DIGEST --by operator)", "umtool library seen <lib> (<topic>… | --all) --by operator Mark seen: what `--new` counts from (the operator's mark)", + "umtool library rename <lib> <topic> --title NAME [--by agent|operator] a topic's name (its id stays)", + "umtool library move <lib> --to TOPIC (--id ID[,ID…] | --thread ID) [--create] [--by agent|operator]", + " posts into another topic (--create makes it)", + "umtool library merge <lib> --into TOPIC --from T[,T…] --by operator topics into one: the operator's, no unmerge", + "umtool library publish <lib> <topic> [--channel SLUG] (--dry-run | --confirm DIGEST --by operator)", + " the operator's kept posts into a channel on no site", + "umtool library accounts <lib> [--topic T] [--limit N] [--json] the library's accounts: posts, kept, topics", + "umtool library archive <lib> <handle> [--name NAME] [--dry-run] [--fetch]", + " <handle>-x on no site; asks X nothing unless --fetch", ].join("\n"); class Refusal extends Error {} @@ -207,6 +218,75 @@ export async function libraryCommand(args, deps = {}) { 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 <lib> <topic> --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 <lib> --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 <lib> <topic> (--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 <lib> <handle>"); + 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 asked = flags["--fetch"] && !flags["--dry-run"] ? `Its first fetch was started${done.jobIds?.length ? ` (${done.jobIds.join(", ")})` : ""}.` : "Nothing was asked of X: its first fetch is a separate step (pnpm ops fetch-posts)."; + say(done, `${flags["--dry-run"] ? "Would make" : "Made"} the channel "${done.slug}" for @${handle.replace(/^@/, "")}, on no site. ${flags["--dry-run"] ? "A dry run creates nothing." : asked}`); + return 0; + } throw new Refusal(`library: unknown verb "${sub}"\n${LIBRARY_USAGE}`); } catch (e) { err(e instanceof Error ? e.message : String(e)); diff --git a/umtool/lib/library/client.mjs b/umtool/lib/library/client.mjs @@ -1,8 +1,9 @@ // THE POSTS LIBRARY, ASKED OF THE EDITOR (lane posts-library). One set of // calls for umtool's Posts library page (through lib/articles/generation.ts // askEditor) and for `umtool library` (through editorAsker below): the -// listing (GET /api/ops/trending) and the three presses (judge-trending, -// watch-trending, purge-trending). +// listing (GET /api/ops/trending) and the presses (judge-trending, +// watch-trending, purge-trending; lane x-trending-publish: organise-trending, +// publish-trending and, for an account, x-search-lead's archive). // // UMTOOL WRITES NOTHING OF A LIBRARY AND ASKS X NOTHING. Every press is the // editor's action; a keep's capture is the editor's paced job. This module @@ -114,6 +115,40 @@ export function purge(ask, body) { return ask("/api/ops/purge-trending", { method: "POST", body }); } +/** organise-trending's body, as given ({slug, op: "rename" | "move" | "merge", …, by}) (lane x-trending-publish). */ +export function organise(ask, body) { + return ask("/api/ops/organise-trending", { method: "POST", body }); +} + +/** publish-trending's body, as given ({slug, topic, dryRun: true, channel?} or {slug, topic, confirm, by: "operator"}). */ +export function publish(ask, body) { + return ask("/api/ops/publish-trending", { method: "POST", body }); +} + +/** + * A library's accounts: { accounts: [{handle, name?, posts, kept, keptByOperator, topics, last, archivedAs?}], total, posts, more }. + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {{ slug: string, topic?: string | null, limit?: number }} p + */ +export function listAccounts(ask, { slug, topic, limit }) { + const q = new URLSearchParams({ slug, accounts: "1" }); + if (topic) q.set("topic", topic); + if (limit) q.set("limit", String(limit)); + return ask(`/api/ops/trending?${q.toString()}`); +} + +/** + * "Archive this account": the editor's x-search-lead, action "archive", for an account of the library — + * `<handle>-x` on no site. FROM A LIBRARY IT ASKS X NOTHING: `fetch` is sent only when it is true. + * @param {{ slug: string, handle: string, name?: string, dryRun?: boolean, fetch?: boolean }} p + */ +export function archiveAccount(ask, p) { + return ask("/api/ops/x-search-lead", { + method: "POST", + body: { slug: p.slug, handle: p.handle, action: "archive", ...(p.name ? { name: p.name } : {}), ...(p.dryRun ? { dryRun: true } : {}), ...(p.fetch === true ? { fetch: true } : {}) }, + }); +} + /** * What became of the keeps' archiving, as one sentence (or "" when nothing was kept). * @param {{ kept: string[], archives: Array<{jobId?: string, error?: string, ids: string[]}> }} r diff --git a/umtool/lib/library/load.ts b/umtool/lib/library/load.ts @@ -20,7 +20,8 @@ import { REPORTS_ROOT } from "@/lib/paths.mjs"; export type LibraryView = ReturnType<typeof parseLibraryView>; export type LibrarySummary = { slug: string; name: string; topics: number; posts: number; unjudged: number }; -export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number }; +// `published` (lane x-trending-publish): the channel the topic's kept posts were published into, when they were. +export type LibraryTopic = XTrendingTopicRow & { seenAt: string | null; fresh: number; published?: { channel: string; firstAt: string; lastAt: string; posts: number } }; export type LibraryPost = XTrendingPostRow; export type LibraryData = diff --git a/umtool/lib/library/organise.test.mjs b/umtool/lib/library/organise.test.mjs @@ -0,0 +1,223 @@ +// Organise, publish and "Archive this account" from the Posts library page +// and from `umtool library` (lane x-trending-publish): each the editor's +// action; the page's presses stamped the operator's whatever the body says; +// the CLI's `--by` "agent" unless told, with a merge and a publish the +// operator's. A fake `ask` (no socket), a temp reports root. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { libraryCommand } from "./cli.mjs"; +import { archivePress, organisePress, PressError, publishPress } from "./presses.mjs"; +import { markSeen, mergeSeen, seenFile, seenOf } from "./seen.mjs"; + +const CONFIRM = "FAKE-TEST-VALUE01234567"; + +function editor({ refuse } = {}) { + const asked = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + if (refuse) throw new Error(refuse); + const b = init.body ?? {}; + if (route === "/api/ops/organise-trending") { + if (b.op === "rename") return { ok: true, op: "rename", topic: b.topic, title: b.title, was: "Kettles", changed: true, sentence: `Topic "Kettles" is now "${b.title}".` }; + if (b.op === "move") return { ok: true, op: "move", to: { id: "cups", title: "Cups", created: false }, moved: b.ids ?? ["11", "12"], skipped: [{ id: "99", reason: "not in this library" }], sentence: "2 posts moved." }; + return { ok: true, op: "merge", into: { id: "kettles", title: "Kettles" }, merged: [{ id: "cups", title: "Cups", posts: 2, pages: 1 }], posts: 2, pages: 2, watch: { dropped: [] }, sentence: '"Cups" is now part of "Kettles". This cannot be undone.' }; + } + if (route === "/api/ops/publish-trending") { + return b.dryRun + ? { ok: true, dryRun: true, channel: b.channel ?? "kettles", creates: true, posts: 2, files: 3, bytes: 204, confirm: CONFIRM, sentence: 'Publishing "Kettles" would make the channel "kettles", on no site.' } + : { ok: true, dryRun: false, channel: "kettles", creates: true, posts: 2, files: 3, bytes: 204, confirm: CONFIRM, sentence: 'Publishing "Kettles" made the channel "kettles", on no site.' }; + } + if (route === "/api/ops/x-search-lead") return b.dryRun ? { ok: true, dryRun: true, slug: `${b.handle}-x`, fields: {} } : { ok: true, slug: `${b.handle}-x`, jobIds: b.fetch ? ["job-1"] : [] }; + if (route.startsWith("/api/ops/trending?")) { + return { ok: true, accounts: [{ handle: "teapot_news", posts: 3, kept: 2, keptByOperator: 1, topics: ["kettles", "cups"], archivedAs: ["teapot_news-x"] }, { handle: "saucer_fan", posts: 1, kept: 0, keptByOperator: 0, topics: ["cups"] }], total: 2, posts: 4, more: 0 }; + } + throw new Error(`unexpected ${route}`); + }; + return { ask, asked, posts: () => asked.filter((a) => a.method === "POST") }; +} + +async function withRoot(fn) { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-organise-")); + try { + return await fn(root); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +async function cli(args, e, root) { + const lines = []; + const errors = []; + const code = await libraryCommand(args, { ask: e.ask, out: (s) => lines.push(s), err: (s) => errors.push(s), reportsRoot: root }); + return { code, lines, errors }; +} + +test("the page's organise presses are the operator's, whatever the body says about who", async () => { + const e = editor(); + await organisePress(e.ask, { lib: "lib", op: "rename", topic: " kettles ", title: " Teapots ", by: "agent" }); + await organisePress(e.ask, { lib: "lib", op: "move", to: "cups", ids: ["11", "11", "12"], by: "agent" }); + await organisePress(e.ask, { lib: "lib", op: "move", to: "Spoons", thread: "11", create: true }); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", op: "rename", topic: "kettles", title: "Teapots", by: "operator" }, + { slug: "lib", op: "move", to: "cups", ids: ["11", "12"], by: "operator" }, + { slug: "lib", op: "move", to: "Spoons", thread: "11", create: true, by: "operator" }, + ]); + for (const [body, re] of [ + [{ lib: "lib", op: "split" }, /"op" is/], + [{ lib: "../x", op: "rename", topic: "a", title: "b" }, /"lib" is the library's slug/], + [{ lib: "lib", op: "rename", topic: "a" }, /"title" is/], + [{ lib: "lib", op: "move", to: "cups" }, /one of them/], + [{ lib: "lib", op: "move", to: "cups", ids: ["x"] }, /list of post ids/], + [{ lib: "lib", op: "move", ids: ["11"] }, /"to" is/], + [{ lib: "lib", op: "merge", into: "kettles", from: [] }, /"from" is/], + ]) { + await assert.rejects(organisePress(e.ask, body), (err) => err instanceof PressError && re.test(err.message), JSON.stringify(body)); + } + assert.equal(e.posts().length, 3, "a refused press asks the editor nothing"); +}); + +test("a merge press is the operator's, and umtool's Mark seen state follows it: the earliest mark stands", async () => { + await withRoot(async (root) => { + await markSeen(root, { slug: "lib", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + await markSeen(root, { slug: "lib", topics: ["kettles", "spoons"], now: Date.parse("2026-11-18T08:00:00.000Z") }); + const e = editor(); + const out = await organisePress(e.ask, { lib: "lib", op: "merge", into: "Kettles", from: [" Cups "], by: "agent" }, { mergeSeen: (lib, into, from) => mergeSeen(root, { slug: lib, into, from }) }); + assert.deepEqual(e.posts()[0].body, { slug: "lib", op: "merge", into: "Kettles", from: ["Cups"], by: "operator" }); + // By the EDITOR's ids (kettles, cups), not the names the press was sent with. + assert.deepEqual(out.seen, { slug: "lib", into: "kettles", seenAt: "2026-11-17T08:00:00.000Z", changed: true }); + const seen = await seenOf(root, "lib"); + assert.deepEqual(Object.keys(seen).sort(), ["kettles", "spoons"]); + assert.equal(seen.kettles, "2026-11-17T08:00:00.000Z"); + assert.equal(JSON.parse(await readFile(seenFile(root), "utf8")).libraries.lib.topics.kettles.previous, "2026-11-18T08:00:00.000Z"); + + // A topic that stays and was never marked stays unmarked; nothing to change writes nothing. + await markSeen(root, { slug: "other", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + assert.deepEqual(await mergeSeen(root, { slug: "other", into: "kettles", from: ["cups"] }), { slug: "other", into: "kettles", seenAt: null, changed: true }); + assert.deepEqual(await seenOf(root, "other"), {}); + assert.deepEqual(await mergeSeen(root, { slug: "other", into: "kettles", from: ["cups"] }), { slug: "other", into: "kettles", seenAt: null, changed: false }); + + // The mark failing to follow is said, never thrown: the merge is done. + const said = await organisePress(e.ask, { lib: "lib", op: "merge", into: "kettles", from: ["cups"] }, { mergeSeen: async () => { throw new Error("posts-library.json does not parse"); } }); + assert.deepEqual(said.seen, { error: "posts-library.json does not parse" }); + assert.equal(said.ok, true); + }); +}); + +test("the publish press: two steps, the operator's; a confirm that is not a dry run's digest asks nothing", async () => { + const e = editor(); + const dry = await publishPress(e.ask, { lib: "lib", topic: "kettles", dryRun: true, by: "agent", channel: "Kettles-2026" }); + assert.equal(dry.confirm, CONFIRM); + await publishPress(e.ask, { lib: "lib", topic: "kettles", confirm: CONFIRM, by: "agent" }); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", topic: "kettles", channel: "Kettles-2026", dryRun: true, by: "operator" }, + { slug: "lib", topic: "kettles", confirm: CONFIRM, by: "operator" }, + ]); + for (const [body, re] of [ + [{ lib: "lib", topic: "kettles" }, /carries the "confirm" its dry run answered/], + [{ lib: "lib", topic: "kettles", confirm: "yes" }, /carries the "confirm"/], + [{ lib: "lib", dryRun: true }, /"topic" is/], + [{ lib: "lib", topic: "kettles", dryRun: true, channel: "../x" }, /"channel" is the channel's slug/], + ]) { + await assert.rejects(publishPress(e.ask, body), (err) => err instanceof PressError && re.test(err.message), JSON.stringify(body)); + } + assert.equal(e.posts().length, 2); + const refused = editor({ refuse: "A read or a capture of this library is queued or running: publish once it has finished (its job is on /jobs)." }); + await assert.rejects(publishPress(refused.ask, { lib: "lib", topic: "kettles", confirm: CONFIRM }), /queued or running/); +}); + +test("Archive this account from the page: the lead action, and never a fetch", async () => { + const e = editor(); + const dry = await archivePress(e.ask, { lib: "lib", handle: "@saucer_fan", name: "Saucer Fan", dryRun: true, fetch: true }); + assert.match(dry.sentence, /^Would make the channel "saucer_fan-x" for @saucer_fan, on no site\. Nothing is asked of X/); + const done = await archivePress(e.ask, { lib: "lib", handle: "saucer_fan", fetch: true }); + assert.match(done.sentence, /^Made the channel "saucer_fan-x" for @saucer_fan, on no site\. Nothing was asked of X/); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", handle: "saucer_fan", action: "archive", name: "Saucer Fan", dryRun: true }, + { slug: "lib", handle: "saucer_fan", action: "archive" }, + ]); + await assert.rejects(archivePress(e.ask, { lib: "lib", handle: "not a handle" }), /"handle" is the account's handle/); +}); + +test("umtool library rename / move: --by is agent unless told", async () => { + await withRoot(async (root) => { + const e = editor(); + assert.equal((await cli(["rename", "lib", "kettles", "--title", "Teapots"], e, root)).code, 0); + assert.equal((await cli(["move", "lib", "--to", "cups", "--id", "11, 12", "--by", "operator"], e, root)).code, 0); + const moved = await cli(["move", "lib", "--to", "Spoons", "--thread", "11", "--create"], e, root); + assert.match(moved.lines[0], /2 posts moved\.\n skipped 99: not in this library/); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", op: "rename", topic: "kettles", title: "Teapots", by: "agent" }, + { slug: "lib", op: "move", to: "cups", ids: ["11", "12"], by: "operator" }, + { slug: "lib", op: "move", to: "Spoons", thread: "11", create: true, by: "agent" }, + ]); + for (const [args, re] of [ + [["rename", "lib", "kettles"], /rename: umtool library rename/], + [["move", "lib", "--id", "11"], /--to names the topic/], + [["move", "lib", "--to", "cups"], /--id or --thread, one of them/], + [["move", "lib", "--to", "cups", "--id", "1", "--thread", "1"], /one of them/], + ]) { + const r = await cli(args, e, root); + assert.equal(r.code, 1); + assert.match(r.errors[0], re); + } + assert.equal(e.posts().length, 3); + }); +}); + +test("umtool library merge and publish want --by operator; a dry run of a publish is anyone's and prints the confirm", async () => { + await withRoot(async (root) => { + const e = editor(); + const agent = await cli(["merge", "lib", "--into", "kettles", "--from", "cups"], e, root); + assert.equal(agent.code, 1); + assert.match(agent.errors[0], /merging topics is the operator's \(it cannot be undone\): say --by operator/); + assert.equal(e.posts().length, 0, "an agent's merge asks the editor nothing"); + await markSeen(root, { slug: "lib", topics: ["cups"], now: Date.parse("2026-11-17T08:00:00.000Z") }); + await markSeen(root, { slug: "lib", topics: ["kettles"], now: Date.parse("2026-11-18T08:00:00.000Z") }); + const merged = await cli(["merge", "lib", "--into", "kettles", "--from", "cups, spoons", "--by", "operator", "--json"], e, root); + assert.equal(merged.code, 0); + assert.deepEqual(e.posts()[0].body, { slug: "lib", op: "merge", into: "kettles", from: ["cups", "spoons"], by: "operator" }); + assert.deepEqual(JSON.parse(merged.lines[0]).seen, { slug: "lib", into: "kettles", seenAt: "2026-11-17T08:00:00.000Z", changed: true }); + + const dry = await cli(["publish", "lib", "kettles", "--dry-run"], e, root); + assert.equal(dry.code, 0); + assert.match(dry.lines[0], /would make the channel "kettles", on no site\.\nchannel: kettles \(new\) · 2 posts · 3 files · 204 bytes\nconfirm: FAKE-TEST-VALUE01234567 \(umtool library publish lib kettles --confirm FAKE-TEST-VALUE01234567 --by operator\)/); + assert.deepEqual(e.posts()[1].body, { slug: "lib", topic: "kettles", dryRun: true, by: "agent" }); + const asAgent = await cli(["publish", "lib", "kettles", "--confirm", CONFIRM], e, root); + assert.equal(asAgent.code, 1); + assert.match(asAgent.errors[0], /publishing a topic is the operator's: say --by operator/); + const none = await cli(["publish", "lib", "kettles"], e, root); + assert.match(none.errors[0], /--dry-run says what would be written/); + assert.equal(e.posts().length, 2); + const done = await cli(["publish", "lib", "kettles", "--confirm", CONFIRM, "--by", "operator", "--channel", "kettles"], e, root); + assert.equal(done.code, 0); + assert.deepEqual(e.posts()[2].body, { slug: "lib", topic: "kettles", channel: "kettles", confirm: CONFIRM, by: "operator" }); + assert.match(done.lines[0], /made the channel "kettles", on no site\./); + }); +}); + +test("umtool library accounts and archive: the accounts by posts; archive asks X nothing unless --fetch", async () => { + await withRoot(async (root) => { + const e = editor(); + const view = await cli(["accounts", "lib", "--topic", "cups", "--limit", "20"], e, root); + assert.equal(view.code, 0); + assert.equal(e.asked[0].route, "/api/ops/trending?slug=lib&accounts=1&topic=cups&limit=20"); + assert.equal(view.lines[0], "2 accounts over 4 posts\n@teapot_news 3 posts · 2 kept · topics: kettles, cups · archived as teapot_news-x\n@saucer_fan 1 post · 0 kept · topics: cups"); + const dry = await cli(["archive", "lib", "@saucer_fan", "--dry-run"], e, root); + assert.match(dry.lines[0], /^Would make the channel "saucer_fan-x" for @saucer_fan, on no site\. A dry run creates nothing\.$/); + const made = await cli(["archive", "lib", "saucer_fan", "--name", "Saucer Fan"], e, root); + assert.match(made.lines[0], /^Made the channel "saucer_fan-x" for @saucer_fan, on no site\. Nothing was asked of X/); + const fetched = await cli(["archive", "lib", "saucer_fan", "--fetch"], e, root); + assert.match(fetched.lines[0], /Its first fetch was started \(job-1\)\.$/); + assert.deepEqual(e.posts().map((p) => p.body), [ + { slug: "lib", handle: "saucer_fan", action: "archive", dryRun: true }, + { slug: "lib", handle: "saucer_fan", action: "archive", name: "Saucer Fan" }, + { slug: "lib", handle: "saucer_fan", action: "archive", fetch: true }, + ]); + assert.equal((await cli(["archive", "lib"], e, root)).code, 1); + }); +}); diff --git a/umtool/lib/library/presses.mjs b/umtool/lib/library/presses.mjs @@ -8,7 +8,7 @@ // agent's hand is `pnpm ops` or `umtool library`, which say "agent". // // Plain ESM. -import { JUDGE_STATES, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, purge, watch } from "./client.mjs"; +import { JUDGE_STATES, archiveAccount, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, organise, publish, purge, watch } from "./client.mjs"; import { listingParamsOf, parseLibraryView } from "./filters.mjs"; import { pressSetOf, undoSetOf } from "./undo.mjs"; @@ -156,3 +156,99 @@ export async function purgePress(ask, body) { if (typeof body.confirm !== "string" || !/^[0-9a-f]{16}$/.test(body.confirm)) throw new PressError(`A removal carries the "confirm" its dry run answered: press Purge, read what it would remove, then confirm.`); return purge(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); } + +// ── lane x-trending-publish: organise, publish, archive an account ───────── + +const topicOf = (body, key, what) => { + if (typeof body[key] !== "string" || !body[key].trim()) throw new PressError(`"${key}" is ${what}`); + return body[key].trim(); +}; + +/** + * POST /api/library/organise — the editor's organise-trending, the operator's: + * { lib, op: "rename", topic, title } + * { lib, op: "move", to, ids: [..] | thread, create? } + * { lib, op: "merge", into, from: [topic, …] } no unmerge: the page asks before it sends this + * Answers the editor's answer. After a MERGE umtool's own Mark seen state follows (`deps.mergeSeen(lib, into, + * from)`: the earliest mark stands), and the answer says so in `seen`. + * @param {(route: string, init?: object) => Promise<any>} ask + * @param {any} body + * @param {{ mergeSeen?: (lib: string, into: string, from: string[]) => Promise<any> }} [deps] + */ +export async function organisePress(ask, body, deps = {}) { + const lib = libOf(body); + if (body.op === "rename") { + return organise(ask, { slug: lib, op: "rename", topic: topicOf(body, "topic", "the topic's id"), title: topicOf(body, "title", "the topic's new name"), by: OPERATOR }); + } + if (body.op === "move") { + const hasIds = body.ids !== undefined; + const hasThread = body.thread !== undefined; + if (hasIds === hasThread) throw new PressError(`a move names posts ("ids") or one thread ("thread"), one of them`); + if (hasIds && (!Array.isArray(body.ids) || body.ids.length === 0 || !body.ids.every((id) => typeof id === "string" && ID.test(id)))) throw new PressError(`"ids" is a list of post ids`); + if (hasThread && (typeof body.thread !== "string" || !ID.test(body.thread))) throw new PressError(`"thread" is a thread's root post id`); + return organise(ask, { + slug: lib, + op: "move", + to: topicOf(body, "to", "the topic the posts go to"), + ...(hasIds ? { ids: [...new Set(body.ids)] } : { thread: body.thread }), + ...(body.create === true ? { create: true } : {}), + by: OPERATOR, + }); + } + if (body.op === "merge") { + const into = topicOf(body, "into", "the topic that stays"); + if (!Array.isArray(body.from) || body.from.length === 0 || !body.from.every((t) => typeof t === "string" && t.trim())) throw new PressError(`"from" is the list of topics merged into it`); + const out = await organise(ask, { slug: lib, op: "merge", into, from: body.from.map((t) => t.trim()), by: OPERATOR }); + // The editor's ids, not the names asked with. + const merged = Array.isArray(out.merged) ? out.merged.map((m) => m.id) : []; + let seen = null; + if (deps.mergeSeen && out.into?.id && merged.length) { + try { + seen = await deps.mergeSeen(lib, out.into.id, merged); + } catch (err) { + // The merge is done and cannot be undone: the mark not following is said, never thrown. + seen = { error: err instanceof Error ? err.message : String(err) }; + } + } + return { ...out, ...(seen ? { seen } : {}) }; + } + throw new PressError(`"op" is "rename", "move" or "merge"`); +} + +/** + * POST /api/library/publish: { lib, topic, dryRun: true, channel? } says what would be written; { lib, topic, + * confirm, channel? } publishes what that dry run showed. The operator's, in two steps. Answers the editor's + * publish-trending answer. + */ +export async function publishPress(ask, body) { + const lib = libOf(body); + const topic = topicOf(body, "topic", "the topic's id"); + if (body.channel !== undefined && body.channel !== null && body.channel !== "" && (typeof body.channel !== "string" || !SLUG.test(body.channel))) { + throw new PressError(`"channel" is the channel's slug: letters, digits, ".", "_" and "-"`); + } + const scope = { slug: lib, topic, ...(body.channel ? { channel: body.channel } : {}) }; + if (body.dryRun === true) return publish(ask, { ...scope, dryRun: true, by: OPERATOR }); + if (typeof body.confirm !== "string" || !/^[0-9a-f]{24}$/.test(body.confirm)) throw new PressError(`A publish carries the "confirm" its dry run answered: press Publish, read what it would write, then confirm.`); + return publish(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); +} + +/** + * POST /api/library/archive: { lib, handle, name?, dryRun? } — "Archive this account": the editor's + * x-search-lead (action "archive") for an account of the library. It makes `<handle>-x` on NO site and ASKS X + * NOTHING: this route never sends "fetch" (the first fetch is the editor's own press). Answers + * { ok, slug, jobIds?, dryRun?, fields?, sentence }. + */ +export async function archivePress(ask, body) { + const lib = libOf(body); + if (typeof body.handle !== "string" || !/^@?[A-Za-z0-9_]{1,30}$/.test(body.handle)) throw new PressError(`"handle" is the account's handle`); + if (body.name !== undefined && typeof body.name !== "string") throw new PressError(`"name" is the account's display name`); + const handle = body.handle.replace(/^@/, ""); + const out = await archiveAccount(ask, { slug: lib, handle, ...(body.name ? { name: body.name } : {}), ...(body.dryRun === true ? { dryRun: true } : {}) }); + return { + ...out, + sentence: + body.dryRun === true + ? `Would make the channel "${out.slug}" for @${handle}, on no site. Nothing is asked of X: its first fetch is a separate press in the editor.` + : `Made the channel "${out.slug}" for @${handle}, on no site. Nothing was asked of X: its first fetch is a separate press in the editor (or \`pnpm ops fetch-posts\`).`, + }; +} diff --git a/umtool/lib/library/seen.mjs b/umtool/lib/library/seen.mjs @@ -107,27 +107,13 @@ async function locked(file, fn) { } } -/** - * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and - * a file that is there and does not parse. - * @param {string} reportsRoot - * @param {{ slug: string, topics: string[], now?: number }} o - * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} - */ -export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { - if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); - if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); +/** One read-modify-write of the state file, under its lock and in turn. `change(lib)` edits the library's entry and answers the result. */ +function mutate(reportsRoot, slug, change) { const run = () => locked(seenFile(reportsRoot), async () => { const current = await readSeen(reportsRoot); if (current.error) throw new Error(current.error); const lib = current.libraries[slug] ?? { topics: {} }; - const seenAt = new Date(now).toISOString(); - const marked = {}; - for (const t of topics) { - const was = lib.topics[t]?.seenAt; - lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; - marked[t] = lib.topics[t]; - } + const result = change(lib); current.libraries[slug] = lib; const file = seenFile(reportsRoot); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); @@ -139,9 +125,54 @@ export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw err; } - return { slug, topics: marked }; + return result; }); const p = chain.then(run, run); chain = p.catch(() => {}); return p; } + +/** + * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and + * a file that is there and does not parse. + * @param {string} reportsRoot + * @param {{ slug: string, topics: string[], now?: number }} o + * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} + */ +export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { + if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); + if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); + return mutate(reportsRoot, slug, (lib) => { + const seenAt = new Date(now).toISOString(); + const marked = {}; + for (const t of topics) { + const was = lib.topics[t]?.seenAt; + lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; + marked[t] = lib.topics[t]; + } + return { slug, topics: marked }; + }); +} + +/** + * TOPICS WERE MERGED IN THE EDITOR (lane x-trending-publish): their marks become one. The topic that stays keeps + * the EARLIEST of the marks the merged topics had, so nothing a mark had not covered is hidden as seen; a topic + * that stays and was never marked stays unmarked (all of it new). The merged topics' marks are dropped. Writes + * nothing when there is nothing to change. + * @param {string} reportsRoot + * @param {{ slug: string, into: string, from: string[] }} o + * @returns {Promise<{ slug: string, into: string, seenAt: string | null, changed: boolean }>} + */ +export async function mergeSeen(reportsRoot, { slug, into, from }) { + if (!SLUG.test(String(slug))) throw new Error(`"${slug}" is not a library's slug`); + if (!TOPIC.test(String(into)) || !Array.isArray(from) || !from.every((t) => TOPIC.test(String(t)))) throw new Error("a merge names the topic that stays and the topics merged into it"); + const current = (await seenOf(reportsRoot, slug)) ?? {}; + if (!from.some((t) => current[t]) ) return { slug, into, seenAt: current[into] ?? null, changed: false }; + return mutate(reportsRoot, slug, (lib) => { + const mine = lib.topics[into]?.seenAt; + const marks = [mine, ...from.map((t) => lib.topics[t]?.seenAt)].filter(Boolean).sort(); + for (const t of from) delete lib.topics[t]; + if (mine && marks[0] !== mine) lib.topics[into] = { seenAt: marks[0], previous: mine }; + return { slug, into, seenAt: lib.topics[into]?.seenAt ?? null, changed: true }; + }); +} diff --git a/umtool/lib/report/xTrendingLibrary.test.mjs b/umtool/lib/report/xTrendingLibrary.test.mjs @@ -134,10 +134,22 @@ test("posts-library: nothing of the page, its routes or its CLI imports a way in for (const spec of imports) { for (const way of WAYS_OUT) assert.ok(!spec.includes(way), `${f.rel} imports ${spec}`); } - // The editor is asked for the listing and the three presses, and nothing else. + // The editor is asked for the listing and the presses, and nothing else. LANE x-trending-publish ADDS + // THREE, and they are the only ways out of a library there are: organising its topics (inside the + // library), PUBLISHING A TOPIC (the editor's publish-trending: the operator's, in two steps, into an + // ordinary channel on no site) and archiving an ACCOUNT (the editor's x-search-lead: `<handle>-x` on no + // site, nothing of the library in it). Still no way into a project, a report, an article, the post + // archive or a site: a site carries the PUBLISHED channel, by the operator's separate act in the editor. + const EDITOR_ROUTES = [ + "/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending", + "/api/ops/organise-trending", "/api/ops/publish-trending", "/api/ops/x-search-lead", + ]; for (const m of f.text.matchAll(/["'`](\/api\/ops\/[a-z-]+)/g)) { - assert.ok(["/api/ops/trending", "/api/ops/judge-trending", "/api/ops/watch-trending", "/api/ops/purge-trending"].includes(m[1]), `${f.rel} asks the editor for ${m[1]}`); + assert.ok(EDITOR_ROUTES.includes(m[1]), `${f.rel} asks the editor for ${m[1]}`); } + // The lead action is asked for "archive" only, and a site is never named to the editor from here. + if (f.text.includes("/api/ops/x-search-lead")) assert.ok(/action: "archive"/.test(f.text) && !/action: "(never|restore)"/.test(f.text), `${f.rel} asks the lead action for more than archive`); + assert.ok(!/siteMemberships|site-config|\/api\/ops\/sites|create-site/.test(f.text), `${f.rel} names a site to the editor`); // No request of X or of any outside host is built here. assert.ok(!/fetch\(\s*["'`]https?:\/\//.test(f.text), `${f.rel} fetches an outside address`); // The corpus is never written from here.