commit 59aa5d45b3f2459c13f5e7bc09642d51218df330
parent c470c4be8a063bdb033ba864cff3721cbca1ef82
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 07:48:15 -0500
umtool: `umtool library` -- the Posts library's reads and presses from a shell, through the page's own calls to the editor: ls, topics, posts with the page's filters, judge (ids, threads, or a filter that counts first and wants --yes), watch, purge (--dry-run, then --confirm with --by operator) and seen; --json on each; `--by` is agent unless told. Rows in the verb registry, help in groups.mjs, docs/cli.md regenerated, and docs/tools.md says what the page is and its keys
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
8 files changed, 446 insertions(+), 2 deletions(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -952,6 +952,8 @@ const COMMANDS = {
jobs: async () => process.exit(await (await import("../lib/queue/cli.mjs")).jobsCommand(argv.slice(argv.indexOf("jobs") + 1))),
// Render mode (2026-10-30): lib/report/renderMode.mjs.
"render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))),
+ // The Posts library (lane posts-library): a private trending library's topics and posts, judged through the editor.
+ library: async () => process.exit(await (await import("../lib/library/cli.mjs")).libraryCommand(argv.slice(argv.indexOf("library") + 1))),
// The render pool (report-to-video render-pool.mjs): lib/report/poolCli.mjs.
pool: async () => process.exit(await (await import("../lib/report/poolCli.mjs")).poolCommand(argv.slice(argv.indexOf("pool") + 1))),
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -95,6 +95,11 @@ Inbox cannot disagree about what is wrong with one.
| `takes verdict <project> <take> like\|maybe\|no\|clear [--note "…"] [--json]` | **a take's verdict** in `takes/verdicts.json` — the Takes page's and Play's **Like · Maybe · No**; a version with a render and none is a call on home ("versions to judge", [knobs.md](knobs.md#what-needs-you-home-the-inbox-one-press-actions-quick-clip)) |
| `takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \| --all] [--apply] [--json]` | **the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions)) |
| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
+| `library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]` | the **Posts library** ([tools.md](tools.md#posts-library-toolslibrary)) from a shell: the editor's X trending libraries, a library's topics (posts, unjudged, new since Mark seen, what its watch is doing) and its posts under the page's filters — `--state unjudged\|keep\|drop\|later` is the judgement in force, `--gone` gone from the page, `--media` carrying media, `--author` one account, `--q` every word, `--new` first shown since the topic's Mark seen (with `--topic`). Read THROUGH THE EDITOR (`GET /api/ops/trending`): umtool opens no file of a library. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL |
+| `library judge <lib> --state keep\|drop\|later\|undecided (--id ID,… \| --thread ID,… \| --filter [--where S] [filters] (--dry-run \| --yes)) [--note T] [--no-archive] [--by agent\|operator]` | the editor's `judge-trending`: posts by id, threads by their root post's id, or every post a filter matches (`--where` the judgement they hold now; `--dry-run` counts, and without `--yes` nothing is judged, **exit 1**), at most 500 per ask — a keep's archiving is ONE paced capture job per ask, never one per post (`--no-archive` marks only). **`--by` is `agent` unless told**: an agent's judgement is a suggestion and never replaces the operator's (skipped, by name); the page's presses are the operator's |
+| `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 dropped posts: posts, files, bytes) 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)` | Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count |
| `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)) |
@@ -285,6 +290,14 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `render-mode on [--for FOR] [--note NOTE]` | render mode: a render gets the machine, for a window | form · *corpus* |
| `render-mode off [--force]` | render mode off | form · *corpus* |
| `render-mode status` | is render mode on, for what, until when | form · *corpus* |
+| `library ls` | the editor's X trending libraries | none: a read the Posts library page (/tools/library) shows |
+| `library topics` | a trending library's topics: posts, unjudged, new, the watch | none: a read the Posts library page (/tools/library) shows |
+| `library posts` | a trending library's posts, filtered | none: a read the Posts library page (/tools/library) shows |
+| `library judge` | keep, drop or later posts of a trending library (the editor's judge-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 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 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* |
| `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* |
diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md
@@ -3,8 +3,8 @@
## `/tools`
Four lists. **Song**: song piles, find, mix, faces, sources, a trim set. **Montage**: the phrase finder. **Articles**:
-the verdict bench. **Corpus**: the channel context notes. While you are in a tool the rail opens Tools into its tools:
-find · mix · phrases · **song ▸** (the four piles) · faces · sources · bench · context.
+the verdict bench. **Corpus**: the channel context notes and the posts library. While you are in a tool the rail opens
+Tools into its tools: find · mix · phrases · **song ▸** (the four piles) · faces · sources · bench · context · library.
| Tool | Address | What it is |
|---|---|---|
@@ -17,6 +17,7 @@ find · mix · phrases · **song ▸** (the four piles) · faces · sources · b
| Trim | `/tools/trim/<set>` | a hook set's trims against the waveform, then **run the chain** (apply-hook-trims → pick-take → mix-hooks) |
| Verdict bench | `/tools/bench` | could a model propose a fact-check verdict well enough to review: runs of `archilyzer reports bench-verdicts`, each with its prompt version and items hash, each model's agreement and recalls against the bar (**passes the bar** / **fails the bar**), confusion matrices, the items; **compare with** another run over the same items (each model's agreement in both, the claims whose answers changed); **Right** / **Wrong** on each disagreement (was the model right? kept in the run's `marks.json`), and not-CORROBORATED precision and recall as ruled and as marked beside the bar; what the verdicts mean. The bar is set here (`settings.generation.verdicts`), and with it the window proposals read (`verdicts.window`: the run's window mode and seconds); a ticked model is the only kind verdict proposals run on (the Inbox's `verdict-proposed`, [inbox.md](inbox.md)) |
| Channel context notes | `/tools/digest-context` | each channel's candidate `digest-context.suggested.md` ([below](#channel-context-notes-toolsdigest-context)): what it asserts beside what it rests on, and **Yes** or **No** |
+| Posts library | `/tools/library` | a private X trending library, by topic: keep, drop or later each post, watch a topic, purge what was dropped ([below](#posts-library-toolslibrary)). Read and judged through the editor; on no site |
A song's own page links its piles, find, mix and sources (its Overview's Song tools; [piece.md](piece.md#a-song-projectspath)).
The old addresses (`/sort`, `/salvage`, `/verify`, `/keeps`, `/mix`, `/bench`, `/browse/find`, `/browse/faces`,
@@ -41,6 +42,48 @@ Nothing applies a note by itself. The one route is `GET`/`POST /api/digest-conte
and a request carrying any `Authorization` header — the way an agent writes — is a 403: the press is the operator's.
Besides the notes files (`lib/paths.mjs` isCorpusNotesFile), these two are the only corpus files umtool writes.
+## Posts library (`/tools/library`)
+
+A trending library is the editor's private collection of posts read off X's trending pages, by topic (the editor's
+`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.
+
+- **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**.
+- **A post** is drawn as the archive's viewer draws one, with its captured screenshot, pictures and video in the body,
+ the post it answers or quotes as its capture read it, and two sentences in their own words: **Gone from the page at
+ <time>** (a trending page that showed it no longer does; a ranked list dropped it, which says nothing more) and
+ **capture: <state> at <time>** (what the capture job recorded of the post's own page).
+- **Keep / Drop / Later / Clear**, per post or, with **Judging: the whole thread**, per thread; **Note** keeps a note
+ with a judgement. A keep archives the post's screenshot and media through the editor's paced capture job. Drop deletes
+ nothing. **Undo** puts back what the last press replaced; it does not cancel a capture already queued.
+- **All N in the filter**: Keep all / Drop all / Later all, behind a confirm that states the count. One capture job
+ per 500 posts, never one per post.
+- **Filters** (in the URL, so a phone and a desk open the same view): All / Unjudged / Kept / Dropped / Later, **New**
+ (first shown since the topic's **Mark seen**, the only thing that moves it), **Gone from the page**, **Has media**, an
+ author, and a search over the words, the handle and the name.
+- **Watch** a topic: every N minutes, for H hours, optionally screenshotting everything new. It runs only while X's
+ cookie jar is fresh, and pauses otherwise (Refresh cookies in the editor resumes it).
+- **Purge dropped posts' captures…** says what would be removed (posts, files, bytes), then **Remove**. Judgements
+ stay; media another post uses is left.
+
+| Key | |
+|---|---|
+| `j` `k` | next, previous post |
+| `a` `d` `l` `c` | keep, drop, later, clear (the selection when posts are selected) |
+| `t` | judge the post or its whole thread |
+| `n` · `x` | note · select |
+| `Shift+A` `Shift+D` `Shift+L` | keep, drop, later everything in the filter (asks first) |
+| `u` | undo the last press |
+| `/` · `g` · `m` | search · only gone from the page · only with media |
+| `?` | the list |
+
+A captured file is served by `/api/library/media/<lib>/<id>/<name>`: only a picture or a video under a marked
+library's `trending/posts-media/<id>/`, read only, to umtool's own pages. The CLI is `umtool library`
+([cli.md](cli.md)); there `--by` is `agent` unless told.
+
## The phrase finder (`/tools/phrases`)
Finding the next montage phrase, with no model. Type phrases — one row each, **Add phrase** for another — pick the
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -706,6 +706,30 @@ export const GROUPS = [
],
},
{
+ cmd: "library",
+ usage: [
+ " umtool library [ls] | topics <lib> | posts <lib> [--topic T] [--state S] [--gone] [--media] [--author H] [--q TEXT]",
+ " [--new] [--limit N] [--offset N] [--json] a private X trending library, read through the editor",
+ " judge <lib> --state keep|drop|later|undecided (--id ID,… | --thread ID,… | --filter [--where S] …",
+ " (--dry-run | --yes)) [--note T] [--no-archive] [--by agent|operator]",
+ " 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) Mark seen: what --new counts from",
+ ],
+ docs: [
+ ["`library [ls] [--json]` · `library topics <lib>` · `library posts <lib> [--topic --state --gone --media --author --q --new --limit --offset --json]`",
+ "the **Posts library** ([tools.md](tools.md#posts-library-toolslibrary)) from a shell: the editor's X trending libraries, a library's topics (posts, unjudged, new since Mark seen, what its watch is doing) and its posts under the page's filters — `--state unjudged\\|keep\\|drop\\|later` is the judgement in force, `--gone` gone from the page, `--media` carrying media, `--author` one account, `--q` every word, `--new` first shown since the topic's Mark seen (with `--topic`). Read THROUGH THE EDITOR (`GET /api/ops/trending`): umtool opens no file of a library. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL"],
+ ["`library judge <lib> --state keep\\|drop\\|later\\|undecided (--id ID,… \\| --thread ID,… \\| --filter [--where S] [filters] (--dry-run \\| --yes)) [--note T] [--no-archive] [--by agent\\|operator]`",
+ "the editor's `judge-trending`: posts by id, threads by their root post's id, or every post a filter matches (`--where` the judgement they hold now; `--dry-run` counts, and without `--yes` nothing is judged, **exit 1**), at most 500 per ask — a keep's archiving is ONE paced capture job per ask, never one per post (`--no-archive` marks only). **`--by` is `agent` unless told**: an agent's judgement is a suggestion and never replaces the operator's (skipped, by name); the page's presses are the operator's"],
+ ["`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 dropped posts: posts, files, bytes) 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)`",
+ "Mark seen: umtool's own state (`<reports>/.umtool/posts-library.json`), the only thing that moves what `--new` and the page's New count"],
+ ],
+ },
+ {
cmd: "pool",
usage: [
" umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -351,6 +351,14 @@ export const VERBS = Object.freeze([
form("render-mode on", "corpus", "render mode: a render gets the machine, for a window", [opt("--for", { help: "90m, 2h (default 2h)" }), opt("--note")]),
form("render-mode off", "corpus", "render mode off", [bool("--force", "even while a render holds it")], { confirm: { what: "take render mode from the render that holds it", when: ["--force"] } }),
form("render-mode status", "corpus", "is render mode on, for what, until when", []),
+ none("library ls", "corpus", "the editor's X trending libraries", "a read the Posts library page (/tools/library) shows"),
+ none("library topics", "corpus", "a trending library's topics: posts, unjudged, new, the watch", "a read the Posts library page (/tools/library) shows"),
+ none("library posts", "corpus", "a trending library's posts, filtered", "a read the Posts library page (/tools/library) shows"),
+ none("library judge", "corpus", "keep, drop or later posts of a trending library (the editor's judge-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 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 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"] } }),
form("pool verify", "corpus", "the render pool's files checked", [num("--sample"), bool("--all")], Q),
diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs
@@ -43,6 +43,7 @@ const SUBVERBS = [
{ cmd: "candidates", file: "lib/report/candidatesCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
{ cmd: "clips", file: "lib/report/reactions.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help"] },
{ cmd: "pool", file: "lib/report/poolCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "library", file: "lib/library/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
{ cmd: "render-mode", file: "lib/report/renderMode.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
{ cmd: "schedule", file: "bin/schedule.ts", re: /\bsub === "([a-z][a-z-]*)"/g },
{ cmd: "storage", file: "bin/umtool.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, within: ["async function cmdStorage()", "async function cmdStorageDeliverables"] },
diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs
@@ -0,0 +1,211 @@
+// `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).
+//
+// 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 { archiveSentence, editorAsker, judge, JUDGE_STATES, LIBRARY_STATES, listLibraries, listLibrary, listLibraryIds, purge, watch } from "./client.mjs";
+import { markSeen, 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"]);
+
+export const LIBRARY_USAGE = [
+ "umtool library [ls] [--json] the editor's X trending libraries",
+ "umtool library topics <lib> [--json] a library's topics: posts, unjudged, new, the watch",
+ "umtool library posts <lib> [--topic T] [--state unjudged|keep|drop|later] [--gone] [--media]",
+ " [--author H] [--q TEXT] [--new] [--limit N] [--offset N] [--json]",
+ "umtool library judge <lib> --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 <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) Mark seen: what `--new` counts from",
+].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}` : "";
+ 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<string, string | undefined> }} [deps]
+ * @returns {Promise<number>} 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") {
+ const listing = await listLibrary(ask, { slug: need(lib), detail: true, limit: 1 });
+ const seen = await seenOf(reportsRoot, lib);
+ const topics = await Promise.all(
+ listing.topics.map(async (t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: seen[t.id] ? (await listLibraryIds(ask, { slug: lib, topic: t.id, since: seen[t.id] })).length : t.posts })),
+ );
+ say({ slug: lib, topics }, topics.length ? topics.map((t) => `${t.id} ${t.title} ${t.posts} posts · ${t.counts?.unjudged ?? 0} unjudged · ${t.fresh} new\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 <lib> <topic> 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}${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);
+ let topics = words.slice(2);
+ if (flags["--all"]) topics = (await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id);
+ if (!topics.length) throw new Refusal("seen: name the topics, or --all");
+ 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;
+ }
+ throw new Refusal(`library: unknown verb "${sub}"\n${LIBRARY_USAGE}`);
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs
@@ -0,0 +1,142 @@
+// `umtool library` (lane posts-library): the page's calls from a shell. A fake
+// editor (no socket), a temp reports root.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, 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";
+
+function harness(answers = {}) {
+ const asked = [];
+ const lines = [];
+ const errors = [];
+ const ask = async (route, init = {}) => {
+ asked.push({ route, ...init });
+ if (route === "/api/ops/trending") return { ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 1, posts: 3, unjudged: 2 }] };
+ if (route.startsWith("/api/ops/trending?")) {
+ const sp = new URL(route, "http://x").searchParams;
+ if (sp.get("ids") === "1") return { ok: true, ids: answers.ids ?? ["11", "12"], posts: [], total: 2, topics: [] };
+ return {
+ ok: true,
+ total: 1,
+ topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, watch: { on: true, sentence: "Watched every 30 min." }, sources: [] }],
+ posts: [{ id: "11", author: "teapot_news", text: "The kettle\nfestival opens.", thread: "11", gone: { at: "2026-11-17T11:00:00.000Z" }, capture: { state: "captured", at: "2026-11-17T10:05:00.000Z" } }],
+ };
+ }
+ if (route === "/api/ops/judge-trending") return { ok: true, written: init.body.set.map((s) => ({ ...s })), skipped: answers.skipped ?? [], kept: init.body.set.filter((s) => s.state === "keep").map((s) => s.id), ...(init.body.archive === false ? {} : { archive: { jobId: "cap-1", ids: ["11"] } }) };
+ if (route === "/api/ops/watch-trending") {
+ if (answers.watchRefused) throw new Error(answers.watchRefused);
+ return { ok: true, sentence: "Watched every 45 min." };
+ }
+ if (route === "/api/ops/purge-trending") return init.body.dryRun ? { ok: true, dryRun: true, posts: 1, confirm: "FAKE-TEST-VALUE", sentence: "Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay." } : { ok: true, dryRun: false, posts: 1, sentence: "Removed the capture of 1 dropped post: 3 files, 204 B. The judgements stay." };
+ throw new Error(`unexpected ${route}`);
+ };
+ return { asked, lines, errors, deps: { ask, out: (s) => lines.push(s), err: (s) => errors.push(s) }, posts: () => asked.filter((a) => a.method === "POST") };
+}
+
+async function withRoot(fn) {
+ const root = await mkdtemp(path.join(tmpdir(), "umtool-library-cli-"));
+ try {
+ return await fn(root);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+test("ls, topics and posts read through the editor; --json prints the answer", async () => {
+ await withRoot(async (root) => {
+ const h = harness();
+ assert.equal(await libraryCommand([], { ...h.deps, reportsRoot: root }), 0);
+ assert.equal(h.lines[0], "lib Lib 1 topics · 3 posts · 2 unjudged");
+ assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0);
+ assert.equal(h.lines[1], "kettles Kettles 3 posts · 2 unjudged · 3 new\n Watched every 30 min.");
+ assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--state", "unjudged", "--gone", "--media", "--author", "teapot_news", "--q", "kettle lid", "--limit", "5", "--offset", "10"], { ...h.deps, reportsRoot: root }), 0);
+ assert.equal(h.asked.at(-1).route, "/api/ops/trending?slug=lib&topic=kettles&limit=5&offset=10&state=unjudged&gone=1&media=1&author=teapot_news&q=kettle+lid&detail=1");
+ // Gone from the page, in those words; the capture's state verbatim.
+ assert.match(h.lines[2], /^1 post\n11 {2}@teapot_news {2}unjudged · gone from the page at 2026-11-17T11:00:00\.000Z · capture: captured at 2026-11-17T10:05:00\.000Z\n {4}The kettle festival opens\.$/);
+ assert.equal(await libraryCommand(["posts", "lib", "--json"], { ...h.deps, reportsRoot: root }), 0);
+ assert.equal(JSON.parse(h.lines[3]).posts[0].id, "11");
+ });
+});
+
+test("judge: an agent by default, the operator when said; ids, threads, and a filter that asks first", async () => {
+ await withRoot(async (root) => {
+ const h = harness();
+ const deps = { ...h.deps, reportsRoot: root };
+ assert.equal(await libraryCommand(["judge", "lib", "--state", "keep", "--id", "11,12", "--note", "the opening"], deps), 0);
+ assert.deepEqual(h.posts()[0].body, { slug: "lib", by: "agent", set: [{ id: "11", state: "keep", note: "the opening" }, { id: "12", state: "keep", note: "the opening" }] });
+ assert.match(h.lines[0], /^2 judgements written as the agent's\.\n1 post queued for archiving \(the editor's capture job cap-1\)\.$/);
+ assert.equal(await libraryCommand(["judge", "lib", "--state", "drop", "--thread", "11", "--by", "operator", "--no-archive"], deps), 0);
+ assert.deepEqual(h.posts()[1].body, { slug: "lib", by: "operator", set: [{ thread: "11", state: "drop" }], archive: false });
+
+ // --filter: a count first (exit 1 without --yes, 0 with --dry-run), then one judge ask.
+ assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--topic", "kettles", "--media"], deps), 1);
+ assert.equal(h.lines.at(-1), "2 posts would be judged later (--yes judges them).");
+ assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--topic", "kettles", "--dry-run", "--json"], deps), 0);
+ assert.deepEqual(JSON.parse(h.lines.at(-1)), { slug: "lib", dryRun: true, state: "later", posts: 2, ids: ["11", "12"] });
+ assert.equal(h.posts().length, 2);
+ assert.equal(await libraryCommand(["judge", "lib", "--state", "later", "--filter", "--where", "unjudged", "--topic", "kettles", "--media", "--yes"], deps), 0);
+ assert.equal(h.asked.at(-2).route, "/api/ops/trending?slug=lib&topic=kettles&state=unjudged&media=1&ids=1");
+ assert.deepEqual(h.posts()[2].body.set, [{ id: "11", state: "later" }, { id: "12", state: "later" }]);
+
+ for (const [args, re] of [
+ [["judge", "lib", "--state", "deleted", "--id", "11"], /--state is one of keep, drop, later, undecided/],
+ [["judge", "lib", "--state", "keep"], /--id, --thread or --filter, one of them/],
+ [["judge", "lib", "--state", "keep", "--id", "11", "--thread", "11"], /one of them/],
+ [["judge", "lib", "--state", "keep", "--id", "11", "--by", "me"], /--by is "agent" or "operator"/],
+ [["judge", "--state", "keep", "--id", "11"], /name the library/],
+ [["posts", "lib", "--new"], /--new goes with --topic/],
+ [["posts", "lib", "--nope"], /unknown flag --nope/],
+ [["frobnicate", "lib"], /unknown verb "frobnicate"/],
+ ]) {
+ const before = h.posts().length;
+ assert.equal(await libraryCommand(args, deps), 1);
+ assert.match(h.errors.at(-1), re);
+ assert.equal(h.posts().length, before);
+ }
+ });
+});
+
+test("watch and purge: the switch with its terms; the editor's refusal is exit 1 in its words; the purge is a dry run, then --confirm", async () => {
+ await withRoot(async (root) => {
+ const h = harness();
+ const deps = { ...h.deps, reportsRoot: root };
+ assert.equal(await libraryCommand(["watch", "lib", "kettles", "on", "--interval", "45", "--hours=24", "--shots"], deps), 0);
+ assert.deepEqual(h.posts()[0].body, { slug: "lib", topic: "kettles", on: true, intervalMinutes: 45, hours: 24, shots: true, by: "agent" });
+ assert.equal(h.lines[0], "Watched every 45 min.");
+ assert.equal(await libraryCommand(["watch", "lib", "kettles", "off", "--interval", "45", "--by", "operator"], deps), 0);
+ assert.deepEqual(h.posts()[1].body, { slug: "lib", topic: "kettles", on: false, by: "operator" });
+ assert.equal(await libraryCommand(["watch", "lib", "kettles"], deps), 1);
+
+ const refused = harness({ watchRefused: "This watch is paused as failing: only the operator switches it on again." });
+ assert.equal(await libraryCommand(["watch", "lib", "kettles", "on"], { ...refused.deps, reportsRoot: root }), 1);
+ assert.equal(refused.errors[0], "This watch is paused as failing: only the operator switches it on again.");
+
+ assert.equal(await libraryCommand(["purge", "lib", "--topic", "kettles", "--dry-run"], deps), 0);
+ assert.deepEqual(h.posts().at(-1).body, { slug: "lib", topic: "kettles", dryRun: true, by: "agent" });
+ assert.match(h.lines.at(-1), /^Would remove the capture of 1 dropped post: 3 files, 204 B\. The judgements stay\.\nconfirm: FAKE-TEST-VALUE {3}\(umtool library purge lib --topic kettles --confirm FAKE-TEST-VALUE --by operator\)$/);
+ assert.equal(await libraryCommand(["purge", "lib"], deps), 1);
+ assert.match(h.errors.at(-1), /--dry-run says what would be removed/);
+ assert.equal(await libraryCommand(["purge", "lib", "--topic", "kettles", "--confirm", "FAKE-TEST-VALUE", "--by", "operator"], deps), 0);
+ assert.deepEqual(h.posts().at(-1).body, { slug: "lib", topic: "kettles", confirm: "FAKE-TEST-VALUE", by: "operator" });
+ });
+});
+
+test("seen marks topics in umtool's own state, and --new counts from it", async () => {
+ await withRoot(async (root) => {
+ const h = harness();
+ const deps = { ...h.deps, reportsRoot: root };
+ assert.equal(await libraryCommand(["seen", "lib"], deps), 1);
+ assert.equal(await libraryCommand(["seen", "lib", "--all", "--json"], deps), 0);
+ const marked = JSON.parse(h.lines.at(-1));
+ assert.ok(Date.parse(marked.topics.kettles.seenAt) > 0);
+ assert.equal(h.posts().length, 0);
+ assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--new"], deps), 0);
+ assert.match(h.asked.at(-1).route, new RegExp(`since=${encodeURIComponent(marked.topics.kettles.seenAt).replace(/\./g, "\\.")}`));
+ assert.equal(await libraryCommand(["topics", "lib"], deps), 0);
+ assert.match(h.lines.at(-1), /2 unjudged · 2 new/);
+ });
+});