commit dfe3befd445986900eab94377453f5ea5b5f71ad
parent de872117f01380996832f1bcc51d356fa179601a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 08:40:04 -0500
x-trending review 1 (M1, S2, S5, S6, S7, nits), umtool: the Posts library's press routes take a press from umtool's own page in a browser only -- a request no browser sent (curl, a script, an agent, the editor; with a bearer or with nothing) is refused before its body is read, on /judge, /watch, /purge and /seen, since each writes its press as the operator's; a purge clears the undo memory; a view is two reads of the editor (the topics' seen marks ride the listing, which answers every topic's new posts); a bulk press whose later chunk fails says how many were written and returns the undo of those; a bulk Clear leaves posts judged only through their thread and says how many; the undo bar says an undone entry becomes the operator's; Mark seen checks the library and the topics through the listing, is written under a lock file, and from the CLI wants --by operator; the bulk press's listing is asked fresh; the media route's 416 keeps its private headers; the purge's confirm shows the editor's own sentence and its numbers
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
23 files changed, 513 insertions(+), 117 deletions(-)
diff --git a/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts b/umtool/app/api/library/media/[lib]/[id]/[name]/route.ts
@@ -39,7 +39,11 @@ async function serve(request: Request, params: Promise<{ lib: string; id: string
const { lib, id, name } = await params;
const found = await resolveLibraryMedia({ channelsDir: CHANNELS_DIR, lib, id, name });
if (!found.ok) return Response.json({ error: found.status === 400 ? "bad request" : "not found" }, { status: found.status, headers: PRIVATE });
- return rangeResponse(request, { abs: found.abs, size: found.size, headers: { ...PRIVATE, "content-type": found.type, "accept-ranges": "bytes" } });
+ const res = rangeResponse(request, { abs: found.abs, size: found.size, headers: { ...PRIVATE, "content-type": found.type, "accept-ranges": "bytes" } });
+ // A range that cannot be met is answered by the shared helper with its Content-Range alone: the
+ // same private headers go on it as on every other answer of this route.
+ if (res.status === 416) return new Response(null, { status: 416, headers: { ...PRIVATE, "content-range": res.headers.get("content-range") ?? `bytes */${found.size}` } });
+ return res;
}
export async function GET(request: Request, { params }: { params: Promise<{ lib: string; id: string; name: string }> }) {
diff --git a/umtool/app/api/library/seen/route.ts b/umtool/app/api/library/seen/route.ts
@@ -1,5 +1,5 @@
-import { PressError } from "@/lib/library/presses.mjs";
-import { press } from "@/lib/library/route";
+import { seenPress } from "@/lib/library/presses.mjs";
+import { ask, press } from "@/lib/library/route";
import { markSeen } from "@/lib/library/seen.mjs";
import { REPORTS_ROOT } from "@/lib/paths.mjs";
@@ -8,15 +8,11 @@ export const dynamic = "force-dynamic";
// POST { lib, topics: [<topicId>, …] } -> { ok, slug, topics: { <id>: { seenAt, previous? } } }
//
// MARK SEEN (lane posts-library): the one thing that moves "new since last
-// visit". umtool's OWN state (REPORTS_ROOT/.umtool/posts-library.json,
-// lib/library/seen.mjs), never a file of the library.
+// visit", and the operator's (the page's press only: lib/library/route.ts).
+// umtool's OWN state (REPORTS_ROOT/.umtool/posts-library.json,
+// lib/library/seen.mjs), never a file of the library. The library and every
+// topic are checked through the editor's listing first: a name the editor
+// does not hold is refused and nothing is marked.
export async function POST(request: Request) {
- return press(request, async (body) => {
- const b = (body && typeof body === "object" ? body : {}) as { lib?: unknown; topics?: unknown };
- try {
- return { ok: true, ...(await markSeen(REPORTS_ROOT, { slug: String(b.lib ?? ""), topics: b.topics as string[] })) };
- } catch (err) {
- throw new PressError(err instanceof Error ? err.message : String(err));
- }
- });
+ return press(request, (body) => seenPress(ask, body, { mark: (lib: string, topics: string[]) => markSeen(REPORTS_ROOT, { slug: lib, topics }) }));
}
diff --git a/umtool/components/tools/library/LibraryView.tsx b/umtool/components/tools/library/LibraryView.tsx
@@ -46,7 +46,7 @@ function inForce(own: Entry | undefined, thread: Entry | undefined): Shown | und
return own ?? (thread ? { ...thread, from: "thread" } : undefined);
}
-type PurgePlan = { posts: number; files: number; bytes: number; confirm: string; sentence: string; captureInFlight?: boolean };
+type PurgePlan = { posts: number; files: number; bytes: number; confirm: string; sentence: string; captureInFlight?: boolean; gone?: Array<{ id: string; at: string }>; agentDropped?: number };
const STATE_LABEL: Record<string, string> = { keep: "kept", drop: "dropped", later: "later" };
const STATE_TABS: Array<{ state: string | null; label: string }> = [
@@ -272,9 +272,15 @@ export default function LibraryView({ data: opened }: { data: Ok }) {
(state: JudgeState) =>
run(async () => {
const r = await send("/api/library/judge", { lib, bulk: { view: viewParams(view), state }, expect: total });
- setLast({ set: (r.undo as UndoItem[]) ?? [], label: String(r.sentence ?? "") });
+ const undoable = (r.undo as UndoItem[]) ?? [];
+ setLast(undoable.length ? { set: undoable, label: String(r.sentence ?? "") } : null);
setBulk(null);
setSelected(new Set());
+ // A later chunk failed: what was written is written, and the sentence says how many were not.
+ if (r.partial === true) {
+ setStatus({ text: String(r.sentence ?? ""), error: true });
+ return;
+ }
return String(r.sentence ?? "");
}),
[lib, run, total, view],
@@ -362,7 +368,8 @@ export default function LibraryView({ data: opened }: { data: Ok }) {
</aside>
<section className="min-w-0">
- <TopicPanel key={topic?.id ?? "all"} lib={lib} topic={topic} topics={topics} off={off} run={run} />
+ {/* 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)} />
{/* ── 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">
@@ -719,7 +726,7 @@ function TopicList({ topics, view, here, lib }: { topics: LibraryTopic[]; view:
);
}
-function TopicPanel({ lib, topic, topics, off, run }: { lib: string; topic: LibraryTopic | null; topics: LibraryTopic[]; off: boolean; run: (what: () => Promise<string | void>) => Promise<void> }) {
+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 }) {
const w = topic?.watch;
const live = !!w && w.on && !w.ended;
const failing = live && w?.paused?.reason === "failing";
@@ -834,7 +841,12 @@ function TopicPanel({ lib, topic, topics, off, run }: { lib: string; topic: Libr
<p className="m-0" data-library-purge-sentence="">
{plan.sentence}
</p>
- {plan.posts > 0 && <p className="m-0 mt-1 text-muted">Removing them cannot be undone here; keeping a post again captures it again.</p>}
+ {/* What is true of the removal is the editor's sentence above (the only copies, what keeping again does): nothing is added to it here. */}
+ {plan.posts > 0 && (
+ <p className="m-0 mt-1 text-muted" data-library-purge-numbers="">
+ {plan.posts} to remove · {(plan.gone ?? []).length} of them gone from the page · {plan.agentDropped ?? 0} dropped by an agent, left alone
+ </p>
+ )}
<div className="mt-1.5 flex flex-wrap gap-1.5">
{plan.posts > 0 && (
<Button
@@ -846,6 +858,7 @@ function TopicPanel({ lib, topic, topics, off, run }: { lib: string; topic: Libr
void run(async () => {
const r = await send("/api/library/purge", { lib, ...scope, confirm: plan.confirm });
setPlan(null);
+ onPurged();
return String(r.sentence ?? "");
})
}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -98,8 +98,8 @@ Inbox cannot disagree about what is wrong with one.
| `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 |
+| `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**) |
| `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)) |
diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md
@@ -58,7 +58,8 @@ archive or a site. With the editor down, or no library in it, the page says so i
**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.
+ nothing. **Undo** puts back what the last press replaced, written as the operator's whoever wrote it before; it does
+ not cancel a capture already queued, and a purge clears it.
- **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**
@@ -66,8 +67,10 @@ archive or a site. With the editor down, or no library in it, the page says so i
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.
+- **Purge dropped posts' captures…** says what would be removed (posts, files, bytes), then **Remove**. It takes the
+ 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.
| Key | |
|---|---|
@@ -81,8 +84,10 @@ archive or a site. With the editor down, or no library in it, the page says so i
| `?` | 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.
+library's `trending/posts-media/<id>/`, read only, to umtool's own pages. The press routes (`/api/library/judge`,
+`/watch`, `/purge`, `/seen`) take a press from umtool's own page in a browser only, because they write it as the
+operator's: a script or an agent gets a 403 naming `pnpm ops` and `umtool library` ([cli.md](cli.md)), where `--by`
+is `agent` unless told and Mark seen wants `--by operator`.
## The phrase finder (`/tools/phrases`)
diff --git a/umtool/e2e/fixtures/editor-stub-trending.mjs b/umtool/e2e/fixtures/editor-stub-trending.mjs
@@ -8,7 +8,8 @@
// POST /__stub/trending {reset?: true, mode?: "ok" | "unreachable" | "none"}
// "unreachable": every trending route drops the connection (the editor is down);
// "none": the editor holds no library
-// GET /__stub/trending -> { mode, requests, judgements, captured, watches }
+// GET /__stub/trending -> { mode, requests, reads, judgements, captured, watches }
+// `reads`: how many times the listing was asked (GET /api/ops/trending) since the reset
//
// Nothing here asks X, or any host, anything.
import { createHash } from "node:crypto";
@@ -17,6 +18,7 @@ import { libraryState } from "./library-fixture.mjs";
let state = libraryState();
let mode = "ok";
let requests = [];
+let reads = 0;
let jobs = 0;
const NOW = "2026-11-18T09:00:00.000Z";
@@ -95,6 +97,7 @@ function listing(sp) {
(!since || p.firstSeenAt > since) &&
words.every((w) => `${p.text} ${p.author} ${p.authorName}`.toLowerCase().includes(w)),
);
+ const seen = detail && sp.get("seen") ? JSON.parse(sp.get("seen")) : null;
const offset = Number(sp.get("offset") ?? 0);
const limit = Number(sp.get("limit") ?? 100);
const authors = new Map();
@@ -110,7 +113,8 @@ function listing(sp) {
counts[stateOf(p)]++;
if (p.gone) counts.gone++;
}
- return { id: t.id, title: t.title, posts: mine.length, ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), sources: [] };
+ const fresh = seen ? mine.filter((p) => !seen[t.id] || p.firstSeenAt > seen[t.id]).length : null;
+ return { id: t.id, title: t.title, posts: mine.length, ...(t.watch ? { watch: { ...t.watch, sentence: watchSentence(t.watch) } } : {}), ...(detail ? { counts } : {}), ...(fresh !== null ? { fresh } : {}), sources: [] };
}),
posts: sp.get("ids") === "1" ? [] : rows.slice(offset, offset + limit).map((p) => row(p, detail)),
total: rows.length,
@@ -154,19 +158,29 @@ function watch(body) {
const digest = (ids) => createHash("sha256").update(JSON.stringify([state.slug, [...ids].sort()])).digest("hex").slice(0, 16);
+// The editor's rule (common/lib/xTrending/purge.ts): the OPERATOR's drops only; an agent's are counted and
+// left; the posts gone from the page are named, and the sentence is true of them.
function purge(body) {
- const ids = state.posts.filter((p) => (!body.topic || p.topic === body.topic) && effective(p)?.state === "drop" && state.captured.includes(p.id)).map((p) => p.id).sort();
+ const scoped = state.posts.filter((p) => (!body.topic || p.topic === body.topic) && effective(p)?.state === "drop" && state.captured.includes(p.id));
+ const mine = scoped.filter((p) => effective(p).by === "operator");
+ const ids = mine.map((p) => p.id).sort();
+ const agentDropped = scoped.length - mine.length;
+ const gone = mine.filter((p) => p.gone).map((p) => ({ id: p.id, at: p.gone.at }));
const files = ids.reduce((n, pid) => n + 2 + (captureFiles(state.posts.find((p) => p.id === pid))?.media.length ?? 0), 0);
const bytes = files * 68;
const confirm = digest(ids);
const what = `the capture${ids.length === 1 ? "" : "s"} of ${ids.length} dropped post${ids.length === 1 ? "" : "s"}: ${files} file${files === 1 ? "" : "s"}, ${bytes} B`;
+ const agent = agentDropped ? ` ${agentDropped} post${agentDropped === 1 ? "" : "s"} an agent dropped ${agentDropped === 1 ? "is" : "are"} left alone: a purge takes the operator's drops only.` : "";
+ const only = gone.length ? ` ${ids.length === 1 ? "It is" : `${gone.length} of them ${gone.length === 1 ? "is" : "are"}`} gone from the page: this is the only copy: X no longer showed this post at ${gone[0].at.slice(0, 10)} ${gone[0].at.slice(11, 16)} UTC; removing it cannot be undone.` : "";
+ const again = ids.length - gone.length > 0 ? ` Keeping ${gone.length ? "the other one" : ids.length === 1 ? "it" : "one of them"} again captures it again.` : "";
+ const answer = { ok: true, slug: state.slug, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, gone, agentDropped, skipped: [], confirm };
if (body.dryRun === true) {
- return { ok: true, slug: state.slug, dryRun: true, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, skipped: [], confirm, sentence: ids.length ? `Would remove ${what}. The judgements stay.` : "No dropped post has a capture: nothing to remove." };
+ return { ...answer, dryRun: true, sentence: ids.length ? `Would remove ${what}. The judgements stay.${only}${again}${agent}` : `No post the operator dropped has a capture: nothing to remove.${agent}` };
}
if (body.by !== "operator") return { ok: false, error: "Removing dropped posts' captures is the operator's press" };
if (body.confirm !== confirm) return { ok: false, error: `The dropped posts with a capture have changed since the dry run (${ids.length} now): nothing was removed. Run the dry run again and confirm what it shows.` };
state.captured = state.captured.filter((pid) => !ids.includes(pid));
- return { ok: true, slug: state.slug, dryRun: false, posts: ids.length, ids, files, bytes, blobsFreed: 0, blobsKept: 0, skipped: [], confirm, sentence: `Removed ${what}. The judgements stay.` };
+ return { ...answer, dryRun: false, sentence: `Removed ${what}. The judgements stay.${agent}` };
}
/** The spec's door. True when answered. */
@@ -174,13 +188,14 @@ export function trendingControl(req, res, url, { json, readBody }) {
if (url.pathname !== "/__stub/trending") return false;
if (req.method === "GET") {
req.resume();
- json(res, 200, { mode, requests, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])) });
+ json(res, 200, { mode, requests, reads, judgements: state.judgements, captured: state.captured, watches: Object.fromEntries(state.topics.map((t) => [t.id, t.watch ?? null])) });
return true;
}
readBody(req, (body) => {
if (body?.reset === true) {
state = libraryState();
requests = [];
+ reads = 0;
jobs = 0;
mode = "ok";
}
@@ -202,6 +217,7 @@ export function trendingRoute(req, res, url, { json, readBody, authorization })
}
if (req.method === "GET" && url.pathname === "/api/ops/trending") {
req.resume();
+ reads++;
if (!url.searchParams.has("slug")) {
const all = listing(new URLSearchParams({ detail: "1" }));
json(res, 200, { ok: true, libraries: mode === "none" ? [] : [{ slug: state.slug, name: state.name, topics: all.topics.length, posts: all.total, unjudged: all.topics.reduce((n, t) => n + t.counts.unjudged, 0) }] });
diff --git a/umtool/e2e/fixtures/library-fixture.mjs b/umtool/e2e/fixtures/library-fixture.mjs
@@ -23,6 +23,7 @@ export const P = {
dropped: id(7004),
later: id(7005),
fresh: id(7006),
+ goneDropped: id(7007),
cup: id(7101),
cupDropped: id(7102),
};
@@ -41,6 +42,7 @@ export const CAPTURES = {
[P.reply]: { "shot.png": PNG, "shot-thread.png": PNG },
[P.dropped]: { "shot.png": PNG, [`${P.dropped}_1.jpg`]: PNG },
[P.cupDropped]: { "shot.png": PNG },
+ [P.goneDropped]: { "shot.png": PNG },
};
/** The library's state as the stub editor starts with it (a fresh copy per call). */
@@ -76,6 +78,8 @@ export function libraryState() {
post(P.later, "teapot_news", "Teapot News", "More on the kettle parade later.", "kettle-festival", READ_2),
post(P.fresh, "kettle_fan", "Kettle Fan", "Just arrived at the festival.", "kettle-festival", READ_3, { capture: { at: "2026-11-17T12:05:00.000Z", state: "deleted", mediaState: "skipped" } }),
post(P.cup, "cup_other", "Cup Other", "Cups are short this week.", "cup-shortage", READ_1),
+ // The operator dropped it, and the page no longer shows it: its capture is the only copy.
+ post(P.goneDropped, "lid_watch", "Lid Watch", "Lids, half price.", "lids", READ_1, { gone: { at: READ_2, read: "tr-01JB0000000000000000000000", trendId: "1900000000000000003" }, capture: { at: "2026-11-17T10:09:00.000Z", state: "captured", mediaState: "none" } }),
post(P.cupDropped, "cup_other", "Cup Other", "Buy my cups.", "cup-shortage", READ_1, { capture: { at: "2026-11-17T10:08:00.000Z", state: "captured", mediaState: "none" } }),
],
judgements: {
@@ -83,6 +87,7 @@ export function libraryState() {
[P.dropped]: { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" },
[P.later]: { state: "later", note: "check the source", by: "agent", at: "2026-11-17T12:31:00.000Z" },
[P.cupDropped]: { state: "drop", by: "agent", at: "2026-11-17T12:32:00.000Z" },
+ [P.goneDropped]: { state: "drop", by: "operator", at: "2026-11-17T12:33:00.000Z" },
},
threads: {},
},
diff --git a/umtool/e2e/library.spec.ts b/umtool/e2e/library.spec.ts
@@ -28,7 +28,7 @@ const KETTLES = "kettle-festival";
const CUPS = "cup-shortage";
type Recorded = { action: string; body: Record<string, any>; authorization: string };
-type StubState = { requests: Recorded[]; judgements: { posts: Record<string, any>; threads: Record<string, any> }; captured: string[]; watches: Record<string, any> };
+type StubState = { requests: Recorded[]; reads: number; judgements: { posts: Record<string, any>; threads: Record<string, any> }; captured: string[]; watches: Record<string, any> };
const stub = async (request: APIRequestContext): Promise<StubState> => (await request.get(`${STUB}/__stub/trending`)).json();
const reset = async (request: APIRequestContext, mode: "ok" | "unreachable" | "none" = "ok") => {
@@ -36,6 +36,8 @@ const reset = async (request: APIRequestContext, mode: "ok" | "unreachable" | "n
rmSync(SEEN, { force: true });
};
const last = async (request: APIRequestContext) => (await stub(request)).requests.at(-1)!;
+// What a browser puts on the page's own fetch, and a page cannot forge: the press routes take a press with them only.
+const asPage = (baseURL: string | undefined) => ({ origin: new URL(baseURL!).origin, "sec-fetch-site": "same-origin" });
const lib = (view: Record<string, unknown> = {}) => urls.postsLibraryHref({ lib: LIB, ...view });
const post = (page: Page, id: string) => page.locator(`[data-library-post="${id}"]`);
const rail = (page: Page) => page.locator('[data-library-topics="rail"]');
@@ -97,8 +99,8 @@ test("found from Tools; topics on the left with their counts and what each watch
await expect(cups).toHaveAttribute("data-library-watch", "failing");
await expect(cups.locator("[data-library-topic-watch]")).toContainText("Watch failing");
await expect(rail(page).locator('[data-library-topic="lids"]')).toHaveAttribute("data-library-watch", "none");
- // Every topic's posts, 8 in all.
- await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "8");
+ // Every topic's posts, 9 in all.
+ await expect(page.locator("[data-library-count]")).toHaveAttribute("data-library-count", "9");
await kettles.click();
await expect(page).toHaveURL(new RegExp(`topic=${KETTLES}`));
@@ -160,7 +162,7 @@ test("keep, drop, later and clear are the editor's judge-trending, as the operat
await idle(page);
// Undo: its own entry removed, nothing archived, and the bar says what undo does not do.
- await expect(page.locator("[data-library-undo-says]")).toHaveText("Undo puts the judgements back. It does not cancel a capture already queued.");
+ await expect(page.locator("[data-library-undo-says]")).toHaveText("Undo puts the judgements back, written as the operator's whoever wrote them before. It does not cancel a capture already queued.");
await page.locator("[data-library-undo]").click();
await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "unjudged");
r = await last(request);
@@ -385,11 +387,18 @@ test("the watch: why it is paused, that only the operator restarts a failing one
expect((await last(request)).body).toEqual({ slug: LIB, topic: "lids", on: true, shots: true, by: "operator" });
});
-test("purge of dropped posts' captures: two presses, the first saying what would go; the judgements stay", async ({ page, request }) => {
+test("purge of the operator's dropped posts' captures: two presses, the first saying what would go and what is true of it; the undo memory goes with it", async ({ page, request }) => {
await open(page, { topic: KETTLES });
+ // A keep first: there is something to undo.
+ await post(page, P.opening).locator('[data-library-press="keep"]').click();
+ await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep");
+ await idle(page);
+ await expect(page.locator("[data-library-undo]")).toBeEnabled();
+
await page.locator("[data-library-purge]").click();
const plan = page.locator("[data-library-purge-plan]");
- await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay.");
+ await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("Would remove the capture of 1 dropped post: 3 files, 204 B. The judgements stay. Keeping it again captures it again.");
+ await expect(plan.locator("[data-library-purge-numbers]")).toHaveText("1 to remove · 0 of them gone from the page · 0 dropped by an agent, left alone");
let r = await last(request);
expect(r.action).toBe("purge-trending");
expect(r.body).toEqual({ slug: LIB, topic: KETTLES, dryRun: true, by: "operator" });
@@ -406,23 +415,42 @@ test("purge of dropped posts' captures: two presses, the first saying what would
expect(r.body.dryRun).toBeUndefined();
const after = await stub(request);
expect(after.captured).not.toContain(P.dropped);
- // The other topic's dropped post, and the judgement itself, are untouched.
- expect(after.captured).toContain(P.cupDropped);
expect(after.judgements.posts[P.dropped].state).toBe("drop");
await expect(post(page, P.dropped)).toHaveAttribute("data-library-judgement", "drop");
+ // S2: a purge takes the undo memory: the keep before it can no longer be undone from here.
+ await expect(page.locator("[data-library-undo]")).toBeDisabled();
+ const asked = (await stub(request)).requests.length;
+ await page.keyboard.press("u");
+ await expect(status(page)).toHaveText("Nothing to undo.");
+ expect((await stub(request)).requests.length).toBe(asked);
+ await expect(post(page, P.opening)).toHaveAttribute("data-library-judgement", "keep");
await idle(page);
// Again: nothing to remove, and no removal is offered.
await page.locator("[data-library-purge]").click();
- await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No dropped post has a capture: nothing to remove.");
+ await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No post the operator dropped has a capture: nothing to remove.");
await expect(plan.locator("[data-library-purge-yes]")).toHaveCount(0);
await plan.locator("[data-library-purge-no]").click();
- // Cancel after a dry run removes nothing.
+
+ // S1: an AGENT's drop is never purged: it is counted and left, and nothing is offered.
await open(page, { topic: CUPS });
await page.locator("[data-library-purge]").click();
- await expect(plan.locator("[data-library-purge-sentence]")).toContainText("Would remove the capture of 1 dropped post");
+ await expect(plan.locator("[data-library-purge-sentence]")).toHaveText("No post the operator dropped has a capture: nothing to remove. 1 post an agent dropped is left alone: a purge takes the operator's drops only.");
+ await expect(plan.locator("[data-library-purge-yes]")).toHaveCount(0);
await plan.locator("[data-library-purge-no]").click();
expect((await stub(request)).captured).toContain(P.cupDropped);
+
+ // S1: a dropped post gone from the page: the capture is the only copy, and nothing promises it back.
+ await open(page, { topic: "lids" });
+ await page.locator("[data-library-purge]").click();
+ await expect(plan.locator("[data-library-purge-sentence]")).toHaveText(
+ "Would remove the capture of 1 dropped post: 2 files, 136 B. The judgements stay. It is gone from the page: this is the only copy: X no longer showed this post at 2026-11-17 11:00 UTC; removing it cannot be undone.",
+ );
+ await expect(plan.locator("[data-library-purge-numbers]")).toHaveText("1 to remove · 1 of them gone from the page · 0 dropped by an agent, left alone");
+ await expect(plan).not.toContainText("captures it again");
+ // Cancel after a dry run removes nothing.
+ await plan.locator("[data-library-purge-no]").click();
+ expect((await stub(request)).captured).toContain(P.goneDropped);
});
test("the media route serves a library's captured pictures and videos, and nothing else", async ({ request }) => {
@@ -464,30 +492,57 @@ test("the media route serves a library's captured pictures and videos, and nothi
// Another site's page cannot fetch it.
expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403);
expect((await request.get(at(LIB, P.opening, "shot.png"), { headers: { "sec-fetch-site": "same-origin" } })).status()).toBe(200);
+ // A range that cannot be met keeps the route's private headers.
+ const beyond = await request.get(at(LIB, P.opening, `${P.opening}_2.mp4`), { headers: { range: "bytes=999999-" } });
+ expect(beyond.status()).toBe(416);
+ expect(beyond.headers()["cache-control"]).toBe("private, no-store");
+ expect(beyond.headers()["cross-origin-resource-policy"]).toBe("same-origin");
+ expect(beyond.headers()["content-range"]).toBe(`bytes */${VIDEO_BYTES.length}`);
// Read only.
expect([404, 405]).toContain((await request.post(at(LIB, P.opening, "shot.png"), { data: {} })).status());
});
-test("the press routes write as the operator whatever the body says, and send an agent elsewhere", async ({ request }) => {
- // A body that claims to be an agent: not read.
- const judged = await request.post("/api/library/judge", { data: { lib: LIB, by: "agent", set: [{ id: P.cup, state: "later", by: "agent" }] } });
+test("the press routes take a press from umtool's own page only: stamped the operator's whatever the body says; a request no browser sent is not the operator", async ({ request, baseURL }) => {
+ const page = asPage(baseURL);
+ // The page's fetch, with a body that claims to be an agent: not read.
+ const judged = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, by: "agent", set: [{ id: P.cup, state: "later", by: "agent" }] } });
expect(judged.status()).toBe(200);
expect((await last(request)).body).toEqual({ slug: LIB, by: "operator", set: [{ id: P.cup, state: "later" }] });
- await request.post("/api/library/watch", { data: { lib: LIB, topic: "lids", on: true, by: "agent" } });
+ expect((await request.post("/api/library/watch", { headers: page, data: { lib: LIB, topic: "lids", on: true, by: "agent" } })).status()).toBe(200);
expect((await last(request)).body.by).toBe("operator");
- await request.post("/api/library/purge", { data: { lib: LIB, dryRun: true, by: "agent" } });
+ expect((await request.post("/api/library/purge", { headers: page, data: { lib: LIB, dryRun: true, by: "agent" } })).status()).toBe(200);
expect((await last(request)).body.by).toBe("operator");
- // A caller carrying a bearer is an agent or the editor: refused, and nothing reaches the editor.
+ // M1: A HEADERLESS POST (curl, a script, an agent with no bearer) IS NOT THE OPERATOR: refused on all four,
+ // the dry run and its confirm included, and nothing reaches the editor or umtool's state.
const before = (await stub(request)).requests.length;
- for (const route of ["judge", "watch", "purge", "seen"]) {
- const res = await request.post(`/api/library/${route}`, { headers: { authorization: "Bearer umtool-e2e-token" }, data: { lib: LIB, set: [{ id: P.cup, state: "keep" }], topic: "lids", on: true, dryRun: true, topics: ["lids"] } });
- expect(res.status(), route).toBe(403);
- expect((await res.json()).error).toContain("pnpm ops judge-trending");
+ const bodies: Record<string, unknown> = {
+ judge: { lib: LIB, set: [{ id: P.cup, state: "keep" }] },
+ watch: { lib: LIB, topic: "lids", on: false },
+ purge: { lib: LIB, dryRun: true },
+ seen: { lib: LIB, topics: ["lids"] },
+ };
+ for (const [route, data] of Object.entries(bodies)) {
+ for (const headers of [{}, { authorization: "Bearer umtool-e2e-token" }, { ...page, authorization: "Bearer umtool-e2e-token" }, { origin: "https://example.org", "sec-fetch-site": "cross-site" }] as Record<string, string>[]) {
+ const res = await request.post(`/api/library/${route}`, { headers, data });
+ expect(res.status(), `${route} ${JSON.stringify(headers)}`).toBe(403);
+ if (!headers.origin || headers.authorization) expect((await res.json()).error).toContain("pnpm ops judge-trending");
+ }
}
+ const confirm = await request.post("/api/library/purge", { data: { lib: LIB, confirm: "FAKE-TEST-VALUE" } });
+ expect(confirm.status()).toBe(403);
expect((await stub(request)).requests.length).toBe(before);
expect(existsSync(SEEN)).toBe(false);
+ // Mark seen, from the page: the library and the topic are checked through the editor first.
+ const ghost = await request.post("/api/library/seen", { headers: page, data: { lib: LIB, topics: ["lids", "spoons"] } });
+ expect(ghost.status()).toBe(404);
+ expect((await ghost.json()).error).toContain('has no topic "spoons": nothing was marked');
+ expect((await request.post("/api/library/seen", { headers: page, data: { lib: "nope", topics: ["lids"] } })).status()).toBe(404);
+ expect(existsSync(SEEN)).toBe(false);
+ expect((await request.post("/api/library/seen", { headers: page, data: { lib: LIB, topics: ["lids"] } })).status()).toBe(200);
+ expect(Object.keys(JSON.parse(readFileSync(SEEN, "utf8")).libraries[LIB].topics)).toEqual(["lids"]);
+
// The page's own read, asked again after a press: the view's rows, to umtool's own pages only.
const read = await request.get(`/api/library?lib=${LIB}&topic=${KETTLES}&state=drop`);
expect(read.status()).toBe(200);
@@ -498,14 +553,34 @@ test("the press routes write as the operator whatever the body says, and send an
expect((await request.get(`/api/library?lib=${LIB}`, { headers: { "sec-fetch-site": "cross-site" } })).status()).toBe(403);
// Ill-shaped: refused here with a sentence, the editor not asked.
- const bad = await request.post("/api/library/judge", { data: { lib: LIB, set: [{ id: "../x", state: "keep" }] } });
+ const bad = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, set: [{ id: "../x", state: "keep" }] } });
expect(bad.status()).toBe(400);
expect((await bad.json()).error).toContain("not a post id");
// A bulk press whose count is stale judges nothing.
- const stale = await request.post("/api/library/judge", { data: { lib: LIB, bulk: { view: { topic: KETTLES, state: "unjudged" }, state: "drop" }, expect: 99 } });
+ const stale = await request.post("/api/library/judge", { headers: page, data: { lib: LIB, bulk: { view: { topic: KETTLES, state: "unjudged" }, state: "drop" }, expect: 99 } });
expect(stale.status()).toBe(409);
expect((await stale.json()).error).toContain("nothing was judged");
- expect((await stub(request)).requests.length).toBe(before);
+ expect((await stub(request)).requests.filter((x) => x.action === "judge-trending").length).toBe(1);
+});
+
+test("S5: one view is two reads of the editor, whatever the number of topics and marks; so is the read after a press", async ({ page, request }) => {
+ // Every topic marked seen: the new counts still come in the one listing read.
+ mkdirSync(path.dirname(SEEN), { recursive: true });
+ const seenAt = "2026-11-17T11:30:00.000Z";
+ writeFileSync(SEEN, JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { [LIB]: { topics: { [KETTLES]: { seenAt }, [CUPS]: { seenAt }, lids: { seenAt } } } } }));
+ await request.post(`${STUB}/__stub/trending`, { data: { mode: "ok" } });
+ const before = (await stub(request)).reads;
+ await open(page, { topic: KETTLES });
+ await expect(rail(page).locator(`[data-library-topic="${KETTLES}"] [data-library-topic-new]`)).toHaveText("1");
+ await expect(rail(page).locator(`[data-library-topic="${CUPS}"] [data-library-topic-new]`)).toHaveCount(0);
+ await idle(page);
+ expect((await stub(request)).reads - before).toBe(2);
+ // A press: the press itself, then the view read again: two reads more.
+ await post(page, P.gone).locator('[data-library-press="later"]').click();
+ await expect(post(page, P.gone)).toHaveAttribute("data-library-judgement", "later");
+ await idle(page);
+ await expect(page.locator(`[data-library-panel="${KETTLES}"]`)).toContainText("3 unjudged");
+ expect((await stub(request)).reads - before).toBe(4);
});
test("on a phone (360 px): nothing pushes the page sideways, the topics fold, and a press works", async ({ page, request }) => {
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -714,7 +714,7 @@ export const GROUPS = [
" (--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",
+ " seen <lib> (<topic>… | --all) --by operator 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]`",
@@ -724,9 +724,9 @@ export const GROUPS = [
["`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"],
+ "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**)"],
],
},
{
diff --git a/umtool/lib/library/caller.mjs b/umtool/lib/library/caller.mjs
@@ -0,0 +1,35 @@
+// WHO MAY PRESS (lane posts-library, review 1): the Posts library's press
+// routes write every press as the OPERATOR's, so they take a press only from
+// what the operator uses — umtool's own page, in a browser.
+//
+// A request is the page's when it carries what a browser sends and a page
+// cannot forge (`Origin` on a write, `Sec-Fetch-Site` on every request:
+// lib/report/writeGuard.mjs fromBrowser) AND is same-origin to a host that is
+// this machine (lib/report/sameOrigin.mjs crossSiteRefusal). Anything else —
+// curl, a script, an agent, the editor's server, with or without a bearer —
+// is sent to the doors where a caller says who it is: `pnpm ops` and `umtool
+// library`, whose `by` is "agent" unless told.
+//
+// The proxy's guard (umtool/proxy.ts) lets a request with neither header
+// through on purpose (the CLI and the editor write other routes that way), so
+// this is asked HERE, by every press route, before the body is read.
+//
+// Plain ESM.
+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\".";
+
+/**
+ * Why a request may not press, or null when it is the page's.
+ * @param {{ get(name: string): string | null }} headers
+ * @param {Record<string, string | undefined>} [env]
+ * @returns {{ status: 403, error: string } | null}
+ */
+export function pressRefusal(headers, env = process.env) {
+ if (headers.get("authorization") !== null) return { status: 403, error: AGENTS_GO_ELSEWHERE };
+ if (!fromBrowser(headers)) return { status: 403, error: AGENTS_GO_ELSEWHERE };
+ const cross = crossSiteRefusal(headers, env);
+ return cross ? { status: 403, error: cross } : null;
+}
diff --git a/umtool/lib/library/caller.test.mjs b/umtool/lib/library/caller.test.mjs
@@ -0,0 +1,40 @@
+// Who may press the Posts library's routes (review 1, M1): umtool's own page
+// in a browser, and nothing else — a request with no browser header is NOT
+// the operator.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { AGENTS_GO_ELSEWHERE, pressRefusal } from "./caller.mjs";
+
+const h = (o) => new Headers(o);
+const ENV = {};
+
+test("the page's own fetch presses: a same-origin browser request to this machine", () => {
+ assert.equal(pressRefusal(h({ host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin" }), ENV), null);
+ assert.equal(pressRefusal(h({ host: "127.0.0.1:3050", origin: "http://127.0.0.1:3050" }), ENV), null);
+ assert.equal(pressRefusal(h({ host: "localhost:3050", "sec-fetch-site": "same-origin" }), ENV), null);
+});
+
+test("a request no browser sent is not the operator: curl, a script, an agent, the editor — with a bearer or with nothing", () => {
+ for (const headers of [{}, { host: "localhost:3050" }, { host: "localhost:3050", "content-type": "application/json" }, { host: "localhost:3050", "user-agent": "curl/8" }]) {
+ assert.deepEqual(pressRefusal(h(headers), ENV), { status: 403, error: AGENTS_GO_ELSEWHERE });
+ }
+ // A bearer is refused even from a browser-shaped request.
+ assert.deepEqual(pressRefusal(h({ host: "localhost:3050", origin: "http://localhost:3050", "sec-fetch-site": "same-origin", authorization: "Bearer x" }), ENV), { status: 403, error: AGENTS_GO_ELSEWHERE });
+ assert.match(AGENTS_GO_ELSEWHERE, /pnpm ops judge-trending/);
+ assert.match(AGENTS_GO_ELSEWHERE, /"by": "agent"/);
+});
+
+test("another site's page, a sibling site's, an opaque origin and a host that is not this machine are refused", () => {
+ for (const headers of [
+ { host: "localhost:3050", origin: "https://example.org", "sec-fetch-site": "cross-site" },
+ { host: "localhost:3050", origin: "http://localhost:3001", "sec-fetch-site": "same-site" },
+ { host: "localhost:3050", origin: "null" },
+ { host: "rebound.example.org", origin: "http://rebound.example.org", "sec-fetch-site": "same-origin" },
+ ]) {
+ const no = pressRefusal(h(headers), ENV);
+ assert.equal(no?.status, 403, JSON.stringify(headers));
+ assert.notEqual(no?.error, AGENTS_GO_ELSEWHERE);
+ }
+});
diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs
@@ -31,7 +31,7 @@ export const LIBRARY_USAGE = [
" [--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",
+ "umtool library seen <lib> (<topic>… | --all) --by operator Mark seen: what `--new` counts from (the operator's mark)",
].join("\n");
class Refusal extends Error {}
@@ -117,11 +117,10 @@ export async function libraryCommand(args, deps = {}) {
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 })),
- );
+ // One read: the topics, and each one's new posts from its Mark seen time.
+ const seen = await seenOf(reportsRoot, need(lib));
+ const listing = await listLibrary(ask, { slug: lib, detail: true, limit: 1, seen });
+ const topics = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts }));
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;
}
@@ -186,7 +185,7 @@ export async function libraryCommand(args, deps = {}) {
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)` : ""}`);
+ say(plan, `${plan.sentence}\n${plan.posts} to remove · ${(plan.gone ?? []).length} of them gone from the page · ${plan.agentDropped ?? 0} dropped by an agent, left alone${plan.posts ? `\nconfirm: ${plan.confirm} (umtool library purge ${lib}${flags["--topic"] ? ` --topic ${flags["--topic"]}` : ""} --confirm ${plan.confirm} --by operator)` : ""}`);
return 0;
}
if (!flags["--confirm"]) throw new Refusal("purge: --dry-run says what would be removed and prints the --confirm the removal needs");
@@ -196,9 +195,14 @@ export async function libraryCommand(args, deps = {}) {
}
if (sub === "seen") {
need(lib);
+ // What is "new" is the operator's to say: an agent marking topics seen would hide posts from him.
+ if (byOf(flags) !== "operator") throw new Refusal("seen: Mark seen is the operator's (it decides what he is shown as new): say --by operator. An agent does not mark topics seen.");
+ const known = (await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id);
let topics = words.slice(2);
- if (flags["--all"]) topics = (await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id);
+ if (flags["--all"]) topics = known;
if (!topics.length) throw new Refusal("seen: name the topics, or --all");
+ const unknown = topics.filter((t) => !known.includes(t));
+ if (unknown.length) throw new Refusal(`seen: ${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked`);
const marked = await markSeen(reportsRoot, { slug: lib, topics });
say({ ok: true, ...marked }, `${topics.length} topic${topics.length === 1 ? "" : "s"} marked seen: ${topics.join(", ")}`);
return 0;
diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs
@@ -22,7 +22,7 @@ function harness(answers = {}) {
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: [] }],
+ topics: [{ id: "kettles", title: "Kettles", posts: 3, counts: { unjudged: 2, keep: 0, drop: 1, later: 0, gone: 1 }, ...(sp.get("seen") ? { fresh: Object.keys(JSON.parse(sp.get("seen"))).length ? 2 : 3 } : {}), 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" } }],
};
}
@@ -31,7 +31,7 @@ function harness(answers = {}) {
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." };
+ if (route === "/api/ops/purge-trending") return init.body.dryRun ? { ok: true, dryRun: true, posts: 1, gone: [{ id: "11", at: "2026-11-17T11:00:00.000Z" }], agentDropped: 2, 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") };
@@ -117,7 +117,8 @@ test("watch and purge: the switch with its terms; the editor's refusal is exit 1
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\)$/);
+ // The same numbers the page and `pnpm ops` give: to remove, gone from the page, an agent's left alone.
+ assert.match(h.lines.at(-1), /^Would remove the capture of 1 dropped post: 3 files, 204 B\. The judgements stay\.\n1 to remove · 1 of them gone from the page · 2 dropped by an agent, left alone\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);
@@ -129,14 +130,28 @@ 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);
+ // Mark seen is the operator's: an agent (the default) is refused, and nothing is written.
+ assert.equal(await libraryCommand(["seen", "lib", "--all"], deps), 1);
+ assert.match(h.errors.at(-1), /Mark seen is the operator's .*say --by operator\. An agent does not mark topics seen\./);
+ assert.equal(await libraryCommand(["seen", "lib", "kettles", "--by", "agent"], deps), 1);
+ assert.equal(await libraryCommand(["posts", "lib", "--topic", "kettles", "--new"], deps), 0);
+ assert.doesNotMatch(h.asked.at(-1).route, /since=/);
+ // A topic the library does not hold: refused, nothing marked.
+ assert.equal(await libraryCommand(["seen", "lib", "spoons", "--by", "operator"], deps), 1);
+ assert.match(h.errors.at(-1), /lib has no topic "spoons": nothing was marked/);
+ assert.equal(await libraryCommand(["seen", "lib", "--by", "operator"], deps), 1);
+ assert.equal(await libraryCommand(["seen", "lib", "--all", "--by", "operator", "--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, "\\.")}`));
+ // topics: ONE read, the marks riding it.
+ const before = h.asked.length;
assert.equal(await libraryCommand(["topics", "lib"], deps), 0);
assert.match(h.lines.at(-1), /2 unjudged · 2 new/);
+ assert.equal(h.asked.length, before + 1);
+ assert.match(h.asked.at(-1).route, /detail=1/);
+ assert.match(h.asked.at(-1).route, /seen=%7B%22kettles%22/);
});
});
diff --git a/umtool/lib/library/client.mjs b/umtool/lib/library/client.mjs
@@ -20,7 +20,7 @@ export const JUDGE_STATES = ["keep", "drop", "later", "undecided"];
/**
* The query of one listing ask.
- * @param {{ slug: string, topic?: string|null, limit?: number, offset?: number, state?: string|null, gone?: boolean, media?: boolean, author?: string|null, q?: string|null, since?: string|null, ids?: boolean, detail?: boolean }} p
+ * @param {{ slug: string, topic?: string|null, limit?: number, offset?: number, state?: string|null, gone?: boolean, media?: boolean, author?: string|null, q?: string|null, since?: string|null, by?: string|null, seen?: Record<string, string>|null, ids?: boolean, detail?: boolean }} p
*/
export function libraryQuery(p) {
const q = new URLSearchParams({ slug: p.slug });
@@ -33,6 +33,9 @@ export function libraryQuery(p) {
if (p.author) q.set("author", p.author);
if (p.q && p.q.trim()) q.set("q", p.q.trim());
if (p.since) q.set("since", p.since);
+ if (p.by) q.set("by", p.by);
+ // The topics' Mark seen times: with detail, every topic's new posts come back in this one read.
+ if (p.seen && p.detail) q.set("seen", JSON.stringify(p.seen));
if (p.ids) q.set("ids", "1");
if (p.detail) q.set("detail", "1");
return `/api/ops/trending?${q.toString()}`;
@@ -70,16 +73,28 @@ export async function listLibraryRows(ask, params) {
/**
* Judge, at most JUDGE_CHUNK per ask (the editor's limit). Each chunk's keeps
* are ONE capture job, started by the editor's action: never a job per post.
+ *
+ * A LATER CHUNK THAT FAILS IS NOT A SILENT PARTIAL: what the chunks before it
+ * wrote is written, so the answer carries it with `failed` — the editor's
+ * words, and how many of the set were never asked. (The first chunk failing
+ * wrote nothing: it throws, as any refusal does.)
* @param {{ slug: string, by: "agent"|"operator", set: Array<{id?: string, thread?: string, state: string, note?: string}>, archive?: boolean }} p
- * @returns {Promise<{ written: object[], skipped: object[], kept: string[], archives: object[], asks: number }>}
+ * @returns {Promise<{ written: object[], skipped: object[], kept: string[], archives: object[], asks: number, failed?: { error: string, asked: number, unasked: number } }>}
*/
export async function judge(ask, p) {
const out = { written: [], skipped: [], kept: [], archives: [], asks: 0 };
for (let i = 0; i < p.set.length; i += JUDGE_CHUNK) {
- const answer = await ask("/api/ops/judge-trending", {
- method: "POST",
- body: { slug: p.slug, by: p.by, set: p.set.slice(i, i + JUDGE_CHUNK), ...(p.archive === false ? { archive: false } : {}) },
- });
+ let answer;
+ try {
+ answer = await ask("/api/ops/judge-trending", {
+ method: "POST",
+ body: { slug: p.slug, by: p.by, set: p.set.slice(i, i + JUDGE_CHUNK), ...(p.archive === false ? { archive: false } : {}) },
+ });
+ } catch (err) {
+ if (i === 0) throw err;
+ out.failed = { error: err instanceof Error ? err.message : String(err), asked: i, unasked: p.set.length - i };
+ return out;
+ }
out.asks++;
out.written.push(...(answer.written ?? []));
out.skipped.push(...(answer.skipped ?? []));
diff --git a/umtool/lib/library/client.test.mjs b/umtool/lib/library/client.test.mjs
@@ -23,6 +23,9 @@ test("a view becomes the editor's query: only what is asked is sent", () => {
"/api/ops/trending?slug=lib&topic=kettles&limit=50&offset=100&state=unjudged&gone=1&media=1&author=teapot_news&q=kettle++lid&since=2026-11-17T10%3A00%3A00.000Z&detail=1",
);
assert.equal(libraryQuery({ slug: "lib", topic: null, state: null, gone: false, q: " ", ids: true }), "/api/ops/trending?slug=lib&ids=1");
+ // The topics' seen marks ride the detail read (one read answers every topic's new posts); never without detail.
+ assert.equal(libraryQuery({ slug: "lib", detail: true, seen: { kettles: "2026-11-17T10:00:00.000Z" }, by: "operator" }), `/api/ops/trending?slug=lib&by=operator&seen=${encodeURIComponent('{"kettles":"2026-11-17T10:00:00.000Z"}').replace(/%20/g, "+")}&detail=1`);
+ assert.equal(libraryQuery({ slug: "lib", ids: true, seen: { kettles: "2026-11-17T10:00:00.000Z" } }), "/api/ops/trending?slug=lib&ids=1");
});
test("the libraries, the ids of a filter, and every row a page at a time", async () => {
@@ -88,3 +91,20 @@ test("the CLI's asker: the bearer, the editor's words on a refusal, a sentence w
await assert.rejects(none("/x"), /WORKER_TOKEN is not set/);
assert.equal(asked, false);
});
+
+test("S6: a later chunk that fails is said: what was written, the editor's words, how many were never asked; the first chunk failing throws", async () => {
+ const set = Array.from({ length: 2 * JUDGE_CHUNK + 7 }, (_, i) => ({ id: String(1000 + i), state: "drop" }));
+ const r = recorder((route, init, n) => {
+ if (n === 2) throw new Error("X is cooling down");
+ return { ok: true, written: init.body.set.map((s) => ({ id: s.id, state: s.state })), skipped: [], kept: [] };
+ });
+ const out = await judge(r.ask, { slug: "lib", by: "operator", set });
+ // Two asks: the third chunk was never sent after the second failed.
+ assert.equal(r.asked.length, 2);
+ assert.equal(out.written.length, 500);
+ assert.deepEqual(out.failed, { error: "X is cooling down", asked: 500, unasked: 507 });
+ const first = recorder(() => {
+ throw new Error("lib is not an X trending library");
+ });
+ await assert.rejects(judge(first.ask, { slug: "lib", by: "operator", set }), /not an X trending library/);
+});
diff --git a/umtool/lib/library/load.ts b/umtool/lib/library/load.ts
@@ -1,6 +1,6 @@
import type { XTrendingListing, XTrendingPostRow, XTrendingTopicRow } from "yt-dlp-transcript-common/lib/xTrending/store";
import { askEditor, EditorError, editorUrl } from "@/lib/articles/generation";
-import { listLibraries, listLibrary, listLibraryIds } from "@/lib/library/client.mjs";
+import { listLibraries, listLibrary } from "@/lib/library/client.mjs";
import { listingParamsOf, PAGE_SIZE, parseLibraryView } from "@/lib/library/filters.mjs";
import { seenOf } from "@/lib/library/seen.mjs";
import { REPORTS_ROOT } from "@/lib/paths.mjs";
@@ -9,7 +9,12 @@ import { REPORTS_ROOT } from "@/lib/paths.mjs";
// EDITOR (GET /api/ops/trending): the libraries, one library's topics with
// their counts and watches, and one page of posts under the view's filters.
// umtool opens no file of a library here. The one thing it adds is its own:
-// each topic's Mark seen time, and from it how many posts are new.
+// each topic's Mark seen time, handed to the listing, which answers how many
+// posts of each topic are new in the same read.
+//
+// TWO READS OF THE EDITOR PER VIEW, whatever the number of topics: the
+// libraries, and one listing (the topics, their counts and new posts, the
+// page of posts).
//
// SERVER-ONLY.
@@ -66,16 +71,10 @@ export async function loadLibrary(view: LibraryView): Promise<LibraryData> {
limit: PAGE_SIZE,
offset: view.offset,
detail: true,
+ // New since Mark seen, per topic, answered by this same read (a topic never marked is new in full).
+ seen,
})) as unknown as XTrendingListing & { name?: string };
- // New since Mark seen, per topic: a topic never marked is new in full; a
- // marked one is asked for the ids a read first showed after its mark.
- const topics: LibraryTopic[] = await Promise.all(
- listing.topics.map(async (t) => {
- const seenAt = seen[t.id] ?? null;
- const fresh = seenAt ? ((await listLibraryIds(ask, { slug: lib, topic: t.id, since: seenAt })) as string[]).length : t.posts;
- return { ...t, seenAt, fresh };
- }),
- );
+ const topics: LibraryTopic[] = listing.topics.map((t) => ({ ...t, seenAt: seen[t.id] ?? null, fresh: t.fresh ?? t.posts }));
return {
ok: true,
libraries,
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, listLibraryRows, purge, watch } from "./client.mjs";
+import { JUDGE_STATES, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, purge, watch } from "./client.mjs";
import { listingParamsOf, parseLibraryView } from "./filters.mjs";
import { pressSetOf, undoSetOf } from "./undo.mjs";
@@ -52,7 +52,9 @@ function judgedSentence(out, state) {
const skipped = out.skipped.length ? ` ${n(out.skipped.length, "id")} skipped: ${out.skipped[0].reason ?? "not judged"}.` : "";
const did = state === "undecided" ? "cleared" : state === "keep" ? "kept" : state === "drop" ? "dropped" : state === "later" ? "marked later" : "judged";
const archive = archiveSentence(out);
- return `${n(out.written.length, "judgement")} ${state ? did : "written"}.${skipped}${archive ? ` ${archive}` : ""}`;
+ // A later chunk failed: exactly how many were written, and that the rest were not.
+ const failed = out.failed ? ` THE REST WERE NOT JUDGED: after ${n(out.failed.asked, "post")} the editor refused (${out.failed.error}), and ${n(out.failed.unasked, "post")} ${out.failed.unasked === 1 ? "was" : "were"} never asked. Undo puts back the ${out.written.length} that were written.` : "";
+ return `${n(out.written.length, "judgement")} ${state ? did : "written"}.${skipped}${archive ? ` ${archive}` : ""}${failed}`;
}
/**
@@ -90,9 +92,34 @@ export async function judgePress(ask, body, deps = {}) {
if (rows.length !== body.expect) {
throw new PressError(`The filter now matches ${n(rows.length)}, not the ${body.expect} the confirm showed: nothing was judged. Look again and press once more.`, 409);
}
- const targets = rows.map((r) => ({ id: r.id }));
+ // A bulk press judges POSTS. Clearing a post that is judged only through its thread would write nothing (it has
+ // no entry of its own): those are left out and counted, not reported as cleared.
+ const throughThread = bulk.state === "undecided" ? rows.filter((r) => !r.detail?.ownJudgement && r.judgement?.from === "thread") : [];
+ const left = new Set(throughThread.map((r) => r.id));
+ const targets = rows.filter((r) => !left.has(r.id)).map((r) => ({ id: r.id }));
+ const notChanged = throughThread.length ? ` ${n(throughThread.length, "post")} ${throughThread.length === 1 ? "is" : "are"} judged through ${throughThread.length === 1 ? "its" : "their"} thread: not changed (clear the thread, with Judging: the whole thread).` : "";
+ if (targets.length === 0) return { ok: true, written: [], skipped: [], kept: [], archives: [], asks: 0, undo: [], throughThread: throughThread.length, sentence: `Nothing cleared.${notChanged}` };
const out = await judge(ask, { slug: lib, by: OPERATOR, set: pressSetOf(targets, bulk.state, bulk.note ?? "") });
- return { ok: true, ...out, undo: undoSetOf(rows, targets), sentence: judgedSentence(out, bulk.state) };
+ // The undo is of what WAS written: after a chunk that failed, the posts never asked are not in it.
+ const written = new Set(out.written.map((w) => w.id));
+ const done = out.failed ? targets.filter((t) => written.has(t.id)) : targets;
+ return { ok: true, ...out, ...(out.failed ? { partial: true } : {}), throughThread: throughThread.length, undo: undoSetOf(rows, done), sentence: `${judgedSentence(out, bulk.state)}${notChanged}` };
+}
+
+/**
+ * POST /api/library/seen: { lib, topics: [<topicId>, …] } — Mark seen. The library and every topic are checked
+ * THROUGH THE EDITOR'S LISTING before anything is written (umtool's own state never names a library or a topic
+ * the editor does not hold). `mark(lib, topics)` writes (lib/library/seen.mjs markSeen).
+ */
+export async function seenPress(ask, body, { mark }) {
+ const lib = libOf(body);
+ if (!Array.isArray(body.topics) || body.topics.length === 0 || !body.topics.every((t) => typeof t === "string" && t)) throw new PressError(`"topics" is the list of topic ids to mark seen`);
+ const libraries = await listLibraries(ask);
+ if (!libraries.some((l) => l.slug === lib)) throw new PressError(`The editor has no library "${lib}".`, 404);
+ const known = new Set((await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id));
+ const unknown = body.topics.filter((t) => !known.has(t));
+ if (unknown.length) throw new PressError(`${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked.`, 404);
+ return { ok: true, ...(await mark(lib, [...new Set(body.topics)])) };
}
/**
diff --git a/umtool/lib/library/presses.test.mjs b/umtool/lib/library/presses.test.mjs
@@ -5,12 +5,16 @@
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
import test from "node:test";
-import { judgePress, PressError, purgePress, watchPress } from "./presses.mjs";
+import { judgePress, PressError, purgePress, seenPress, watchPress } from "./presses.mjs";
-function editor(rows = []) {
+function editor(rows = [], { failAt = 0 } = {}) {
const asked = [];
+ let judged = 0;
const ask = async (route, init = {}) => {
asked.push({ route, ...init });
+ if (route === "/api/ops/trending") return { ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 2, posts: rows.length, unjudged: 0 }] };
+ if (route === "/api/ops/judge-trending" && ++judged === failAt) throw new Error("X is cooling down for 14 minutes");
+ if (route.startsWith("/api/ops/trending?") && new URL(route, "http://x").searchParams.get("detail") !== "1") return { ok: true, topics: [{ id: "kettles" }, { id: "cups" }], posts: [], total: 0 };
if (route.startsWith("/api/ops/trending")) {
const offset = Number(new URL(route, "http://x").searchParams.get("offset") ?? 0);
return { ok: true, total: rows.length, posts: rows.slice(offset, offset + 500) };
@@ -108,3 +112,59 @@ test("the purge is two presses: the dry run, then the removal with the dry run's
await assert.rejects(purgePress(e.ask, { lib: "lib", confirm: "yes" }), /confirm/);
assert.equal(e.posts().length, 2);
});
+
+// ── review 1 ───────────────────────────────────────────────────────────────
+
+test("S6: a bulk press whose later chunk fails says exactly how many were written, that the rest were not, and returns the undo of what WAS written", async () => {
+ const rows = Array.from({ length: 620 }, (_, i) => ({ id: String(1900000000000003000n + BigInt(i)), thread: String(1900000000000003000n + BigInt(i)), detail: i === 0 ? { ownJudgement: { state: "keep", by: "agent", at: "t" } } : {} }));
+ const e = editor(rows, { failAt: 2 });
+ const out = await judgePress(e.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 620 });
+ assert.equal(out.ok, true);
+ assert.equal(out.partial, true);
+ assert.equal(out.written.length, 500);
+ assert.equal(out.sentence, "500 judgements dropped. THE REST WERE NOT JUDGED: after 500 posts the editor refused (X is cooling down for 14 minutes), and 120 posts were never asked. Undo puts back the 500 that were written.");
+ // The undo names the 500 written, in their order, and none of the 120.
+ assert.equal(out.undo.length, 500);
+ assert.deepEqual(out.undo[0], { id: rows[0].id, state: "keep" });
+ assert.equal(out.undo.at(-1).id, rows[499].id);
+ assert.ok(!out.undo.some((u) => u.id === rows[500].id));
+ // The first chunk failing wrote nothing: a refusal, not a partial.
+ const first = editor(rows, { failAt: 1 });
+ await assert.rejects(judgePress(first.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 620 }), /cooling down/);
+});
+
+test("nit: a bulk Clear leaves posts judged only through their thread, and says how many: not changed", async () => {
+ const rows = [
+ { id: "1900000000000004001", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t" }, detail: { ownJudgement: { state: "keep", by: "operator", at: "t" } } },
+ { id: "1900000000000004002", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t", from: "thread" }, detail: { threadJudgement: { state: "keep", by: "operator", at: "t" } } },
+ { id: "1900000000000004003", thread: "1900000000000004001", judgement: { state: "keep", by: "operator", at: "t", from: "thread" }, detail: {} },
+ ];
+ const e = editor(rows);
+ const out = await judgePress(e.ask, { lib: "lib", bulk: { view: { state: "keep" }, state: "undecided" }, expect: 3 });
+ assert.deepEqual(e.posts()[0].body.set, [{ id: "1900000000000004001", state: "undecided" }]);
+ assert.equal(out.throughThread, 2);
+ assert.equal(out.sentence, "1 judgement cleared. 2 posts are judged through their thread: not changed (clear the thread, with Judging: the whole thread).");
+ assert.deepEqual(out.undo, [{ id: "1900000000000004001", state: "keep" }]);
+ // Only such posts: nothing is asked of the editor, and it is said.
+ const only = editor(rows.slice(1));
+ const none = await judgePress(only.ask, { lib: "lib", bulk: { view: {}, state: "undecided" }, expect: 2 });
+ assert.equal(only.posts().length, 0);
+ assert.equal(none.sentence, "Nothing cleared. 2 posts are judged through their thread: not changed (clear the thread, with Judging: the whole thread).");
+ // Any other state judges them all, post by post.
+ const drop = editor(rows);
+ await judgePress(drop.ask, { lib: "lib", bulk: { view: {}, state: "drop" }, expect: 3 });
+ assert.equal(drop.posts()[0].body.set.length, 3);
+});
+
+test("nit: Mark seen checks the library and every topic through the editor's listing before anything is written", async () => {
+ const e = editor();
+ const marks = [];
+ const mark = async (lib, topics) => (marks.push([lib, topics]), { slug: lib, topics: Object.fromEntries(topics.map((t) => [t, { seenAt: "2026-11-18T10:00:00.000Z" }])) });
+ assert.deepEqual(await seenPress(e.ask, { lib: "lib", topics: ["kettles", "kettles", "cups"] }, { mark }), { ok: true, slug: "lib", topics: { kettles: { seenAt: "2026-11-18T10:00:00.000Z" }, cups: { seenAt: "2026-11-18T10:00:00.000Z" } } });
+ assert.deepEqual(marks, [["lib", ["kettles", "cups"]]]);
+ await assert.rejects(seenPress(e.ask, { lib: "other", topics: ["kettles"] }, { mark }), (err) => err.status === 404 && /The editor has no library "other"/.test(err.message));
+ await assert.rejects(seenPress(e.ask, { lib: "lib", topics: ["kettles", "spoons"] }, { mark }), (err) => err.status === 404 && /lib has no topic "spoons": nothing was marked/.test(err.message));
+ await assert.rejects(seenPress(e.ask, { lib: "lib", topics: [] }, { mark }), /"topics"/);
+ assert.equal(marks.length, 1);
+ assert.equal(e.posts().length, 0);
+});
diff --git a/umtool/lib/library/route.ts b/umtool/lib/library/route.ts
@@ -1,28 +1,27 @@
import { askEditor, clearEditorMemo, EditorError } from "@/lib/articles/generation";
+import { pressRefusal } from "@/lib/library/caller.mjs";
import { PressError } from "@/lib/library/presses.mjs";
// What the Posts library's press routes share (lane posts-library).
//
-// THESE ROUTES ARE THE PAGE'S: every press through them is stamped the
-// operator's (lib/library/presses.mjs). A request carrying an Authorization
-// header is an agent or the editor, and is refused here: an agent judges
-// through `pnpm ops` or `umtool library`, where it says who it is.
+// THESE ROUTES ARE THE PAGE'S, AND ONLY THE PAGE'S: every press through them
+// is stamped the operator's (lib/library/presses.mjs), so a press is taken
+// only from umtool's own page in a browser (lib/library/caller.mjs
+// pressRefusal: what a browser sends, same-origin, to this machine). A
+// request no browser sent — curl, a script, an agent, the editor, with a
+// bearer or with nothing at all — is refused before its body is read, and
+// sent to `pnpm ops` / `umtool library`, where a caller says who it is.
export const NO_STORE = { "cache-control": "no-store" };
-export const AGENTS_GO_ELSEWHERE =
- "This route is the Posts library page's: its presses are written as the operator's. An agent uses `pnpm ops judge-trending` / `watch-trending` / `purge-trending` or `umtool library`, and says \"by\": \"agent\".";
+// A read is always asked again: a press is judged against the rows as they are NOW (a bulk press's
+// targets and its undo), never an answer askEditor kept from two seconds ago.
+export const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, { ...init, fresh: true });
-export function refuseAgent(request: Request): Response | null {
- return request.headers.get("authorization") === null ? null : Response.json({ error: AGENTS_GO_ELSEWHERE }, { status: 403, headers: NO_STORE });
-}
-
-export const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor<Record<string, unknown>>(route, init);
-
-/** Run one press: the body parsed, the press's answer, or its refusal in its own words. */
+/** Run one press: the caller checked, the body parsed, the press's answer, or its refusal in its own words. */
export async function press(request: Request, run: (body: unknown) => Promise<unknown>): Promise<Response> {
- const refused = refuseAgent(request);
- if (refused) return refused;
+ const refused = pressRefusal(request.headers);
+ if (refused) return Response.json({ error: refused.error }, { status: refused.status, headers: NO_STORE });
const body = await request.json().catch(() => null);
try {
return Response.json(await run(body), { headers: NO_STORE });
diff --git a/umtool/lib/library/seen.mjs b/umtool/lib/library/seen.mjs
@@ -11,11 +11,15 @@
// operator says he has seen it, on whichever device. `previous` is the mark it
// replaced.
//
-// One writer, serialised in-process; every write is a whole file to a temp
-// name and a rename. A file that does not parse is never overwritten.
+// SEVERAL PROCESSES WRITE IT (the app, `umtool library seen`): a write is a
+// read-modify-rename under a LOCK FILE beside it (`posts-library.json.lock`,
+// made exclusively; one left by a process that died is taken over after 10 s),
+// and serialised in-process too, so two marks at once are both kept. Every
+// write is a whole file to a temp name and a rename. A file that does not
+// parse is never overwritten.
//
// Plain ESM.
-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -71,6 +75,38 @@ export async function seenOf(reportsRoot, slug) {
let chain = Promise.resolve();
+export const SEEN_LOCK_STALE_MS = 10_000;
+const LOCK_WAIT_MS = 5_000;
+
+/** Run `fn` holding the state file's lock (an exclusive create; a stale one is taken over). */
+async function locked(file, fn) {
+ const lock = `${file}.lock`;
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const deadline = Date.now() + LOCK_WAIT_MS;
+ for (;;) {
+ try {
+ const fh = await open(/* turbopackIgnore: true */ lock, "wx");
+ await fh.writeFile(`${process.pid}\n`);
+ await fh.close();
+ break;
+ } catch (err) {
+ if (err?.code !== "EEXIST") throw err;
+ const st = await stat(/* turbopackIgnore: true */ lock).catch(() => null);
+ if (st && Date.now() - st.mtimeMs > SEEN_LOCK_STALE_MS) {
+ await rm(/* turbopackIgnore: true */ lock, { force: true });
+ continue;
+ }
+ if (Date.now() > deadline) throw new Error("posts-library.json is being written by another umtool process: nothing was marked, press again");
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ }
+ try {
+ return await fn();
+ } finally {
+ await rm(/* turbopackIgnore: true */ lock, { force: true }).catch(() => {});
+ }
+}
+
/**
* Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and
* a file that is there and does not parse.
@@ -81,7 +117,7 @@ let chain = Promise.resolve();
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"));
- const run = async () => {
+ 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: {} };
@@ -104,7 +140,7 @@ export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) {
throw err;
}
return { slug, topics: marked };
- };
+ });
const p = chain.then(run, run);
chain = p.catch(() => {});
return p;
diff --git a/umtool/lib/library/seen.test.mjs b/umtool/lib/library/seen.test.mjs
@@ -7,7 +7,8 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promis
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
-import { markSeen, readSeen, seenFile, seenOf } from "./seen.mjs";
+import { utimes } from "node:fs/promises";
+import { markSeen, readSeen, SEEN_LOCK_STALE_MS, seenFile, seenOf } from "./seen.mjs";
test("nothing is marked until the press; a press marks the topics named and remembers the mark it replaced", async () => {
const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-"));
@@ -49,3 +50,32 @@ test("refused: an ill-shaped slug or topic, no topics; a file that does not pars
await rm(root, { recursive: true, force: true });
}
});
+
+test("nit: the write is under a lock file: it waits for another process's, takes over one left by a process that died, and leaves none behind", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-"));
+ try {
+ await mkdir(path.join(root, ".umtool"), { recursive: true });
+ const lock = `${seenFile(root)}.lock`;
+ // Another process holds it, and writes its own mark before letting go.
+ await writeFile(lock, "999999\n");
+ const mine = markSeen(root, { slug: "lib", topics: ["kettles"], now: Date.parse("2026-11-18T12:00:00.000Z") });
+ await new Promise((r) => setTimeout(r, 120));
+ assert.deepEqual(await readSeen(root), { libraries: {} }, "nothing written while the lock is held");
+ await writeFile(seenFile(root), JSON.stringify({ format: "umtool-posts-library", version: 1, libraries: { lib: { topics: { cups: { seenAt: "2026-11-18T11:00:00.000Z" } } } } }));
+ await rm(lock);
+ await mine;
+ // Both marks are there: the read was made under the lock, after the other write.
+ assert.deepEqual(await seenOf(root, "lib"), { cups: "2026-11-18T11:00:00.000Z", kettles: "2026-11-18T12:00:00.000Z" });
+ assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]);
+
+ // A lock older than the limit is a dead process's.
+ await writeFile(lock, "999999\n");
+ const old = new Date(Date.now() - SEEN_LOCK_STALE_MS - 5_000);
+ await utimes(lock, old, old);
+ await markSeen(root, { slug: "lib", topics: ["lids"] });
+ assert.ok((await seenOf(root, "lib")).lids);
+ assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/library/undo.mjs b/umtool/lib/library/undo.mjs
@@ -9,7 +9,7 @@
//
// Plain ESM, no imports.
-export const UNDO_SAYS = "Undo puts the judgements back. It does not cancel a capture already queued.";
+export const UNDO_SAYS = "Undo puts the judgements back, written as the operator's whoever wrote them before. It does not cancel a capture already queued.";
const before = (j) => (j && typeof j.state === "string" ? { state: j.state, ...(typeof j.note === "string" && j.note ? { note: j.note } : {}) } : { state: "undecided" });
diff --git a/umtool/lib/library/view.test.mjs b/umtool/lib/library/view.test.mjs
@@ -65,4 +65,6 @@ test("undo puts back each id's OWN entry, or removes the judgement it had none o
assert.deepEqual(pressSetOf([{ id: "1" }, { thread: "3" }], "drop", "spam"), [{ id: "1", state: "drop", note: "spam" }, { thread: "3", state: "drop", note: "spam" }]);
assert.deepEqual(pressSetOf([{ id: "1" }], "undecided", "ignored"), [{ id: "1", state: "undecided" }]);
assert.match(UNDO_SAYS, /does not cancel a capture already queued/);
+ // S7: an undone entry becomes the operator's, and the bar says so.
+ assert.match(UNDO_SAYS, /written as the operator's whoever wrote them before/);
});