Archilyzer · Source

archilyzer

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

commit 59bdb4dfcd8a154395a42f01498a974b5603f789
parent 7fc29371b81daaa3f1cb14f001085b22100e341d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 06:42:07 -0500

umtool: the Posts library's helpers, lib/library/ -- one set of calls to the editor for the page and the CLI (the listing's query, judging in chunks of at most 500 so a bulk keep is one capture job per chunk, the watch, the purge); the view a URL says and its sentences ("Gone from the page at", a capture's state verbatim); the key table; the set that undoes a press; Mark seen, umtool's own state under the reports root's .umtool/, moved only by the press; and the one file the media route may name (a picture or a video under a marked library's trending/posts-media/<id>/, its real path inside it); a detail row carries its thread's own judgement for the undo; `pnpm test:scripts` runs umtool/lib/library/*.test.mjs

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

Diffstat:
Mcommon/lib/xTrending/store.test.ts | 2++
Mcommon/lib/xTrending/store.ts | 3+++
Meditor/app/api/ops/trending/route.ts | 2+-
Mpackage.json | 2+-
Aumtool/lib/library/client.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/client.test.mjs | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/filters.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/keys.mjs | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/media.mjs | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/media.test.mjs | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/seen.mjs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/seen.test.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/undo.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/library/view.test.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 808 insertions(+), 2 deletions(-)

diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -471,6 +471,8 @@ test("detail: a topic's counts, the accounts, the rest of the record, the first assert.equal(by["903"].judgement?.from, "thread"); assert.equal(by["903"].detail?.ownJudgement, undefined); assert.equal(by["902"].detail?.ownJudgement?.state, "drop"); + assert.equal(by["903"].detail?.threadJudgement?.note, "the opening"); + assert.equal(by["902"].detail?.threadJudgement, undefined); // The capture: names and sizes, pictures and videos only; the context without its media addresses. assert.deepEqual(by["901"].detail?.capture, { shot: "shot.png", diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -774,6 +774,8 @@ export type XTrendingPostDetail = { }; firstSeenAt: string; ownJudgement?: XTrendingJudgement; + // Its thread's own entry (what an undo of a thread press restores). + threadJudgement?: XTrendingJudgement; capture?: { shot?: string; threadShot?: string; @@ -925,6 +927,7 @@ export async function listXTrending( }, firstSeenAt, ...(judgements.posts[id] ? { ownJudgement: judgements.posts[id] } : {}), + ...(judgements.threads[thread] ? { threadJudgement: judgements.threads[thread] } : {}), }, } : {}), diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -66,7 +66,7 @@ export const dynamic = "force-dynamic"; // gone}; the answer gains `authors` [{author, posts}] (of the // topic asked for); each row gains `detail` {post: {isReply, // isRepost, replyTo?, quoted?, links, engagement?, -// mediaCount?}, firstSeenAt, ownJudgement?, capture?: {shot?, +// mediaCount?}, firstSeenAt, ownJudgement?, threadJudgement?, capture?: {shot?, // threadShot?, media: [{name, kind, bytes}], context?: // {parent?, quoted?}}}. A capture's files are NAMES under // trending/posts-media/<id>/: this route serves no bytes. diff --git a/package.json b/package.json @@ -25,7 +25,7 @@ "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", "test:files": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 node scripts/test-files.mjs", - "test:scripts": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", + "test:scripts": "ARCHILYZER_EDITOR_URL=http://127.0.0.1:9 WORKER_TOKEN= UMTOOL_URL=http://127.0.0.1:9 ARCHILYZER_NO_NETWORK=1 NODE_OPTIONS=\"--import=\\\"$PWD/common/lib/noNetwork.mjs\\\" $NODE_OPTIONS\" node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/library/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/umtool/lib/library/client.mjs b/umtool/lib/library/client.mjs @@ -0,0 +1,142 @@ +// THE POSTS LIBRARY, ASKED OF THE EDITOR (lane posts-library). One set of +// calls for umtool's Posts library page (through lib/articles/generation.ts +// askEditor) and for `umtool library` (through editorAsker below): the +// listing (GET /api/ops/trending) and the three presses (judge-trending, +// watch-trending, purge-trending). +// +// UMTOOL WRITES NOTHING OF A LIBRARY AND ASKS X NOTHING. Every press is the +// editor's action; a keep's capture is the editor's paced job. This module +// reads no file of the corpus. +// +// `ask(route, {method?, body?})` answers the editor's JSON and throws an Error +// carrying its words when it refuses or cannot be reached. +// +// Plain ESM, no imports. + +export const JUDGE_CHUNK = 500; +export const LIST_PAGE_MAX = 500; +export const LIBRARY_STATES = ["unjudged", "keep", "drop", "later"]; +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 + */ +export function libraryQuery(p) { + const q = new URLSearchParams({ slug: p.slug }); + if (p.topic) q.set("topic", p.topic); + if (p.limit) q.set("limit", String(p.limit)); + if (p.offset) q.set("offset", String(p.offset)); + if (p.state) q.set("state", p.state); + if (p.gone) q.set("gone", "1"); + if (p.media) q.set("media", "1"); + 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.ids) q.set("ids", "1"); + if (p.detail) q.set("detail", "1"); + return `/api/ops/trending?${q.toString()}`; +} + +/** Every library the editor holds: [{slug, name, topics, posts, unjudged}]. */ +export async function listLibraries(ask) { + const answer = await ask("/api/ops/trending"); + return Array.isArray(answer.libraries) ? answer.libraries : []; +} + +/** One listing ask (libraryQuery's parameters). */ +export function listLibrary(ask, params) { + return ask(libraryQuery(params)); +} + +/** Every id matching a filter, in listing order. */ +export async function listLibraryIds(ask, params) { + const answer = await ask(libraryQuery({ ...params, ids: true, detail: false, limit: undefined, offset: undefined })); + return Array.isArray(answer.ids) ? answer.ids : []; +} + +/** Every row matching a filter, with detail, a page at a time. */ +export async function listLibraryRows(ask, params) { + const rows = []; + for (let offset = 0; ; offset += LIST_PAGE_MAX) { + const answer = await ask(libraryQuery({ ...params, detail: true, ids: false, limit: LIST_PAGE_MAX, offset })); + const page = Array.isArray(answer.posts) ? answer.posts : []; + rows.push(...page); + if (page.length < LIST_PAGE_MAX || rows.length >= (answer.total ?? 0)) break; + } + return rows; +} + +/** + * 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. + * @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 }>} + */ +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 } : {}) }, + }); + out.asks++; + out.written.push(...(answer.written ?? [])); + out.skipped.push(...(answer.skipped ?? [])); + out.kept.push(...(answer.kept ?? [])); + if (answer.archive) out.archives.push(answer.archive); + } + return out; +} + +/** The watch's switch, the library's settings, or one scan: watch-trending's body, as given. */ +export function watch(ask, body) { + return ask("/api/ops/watch-trending", { method: "POST", body }); +} + +/** purge-trending's body, as given ({slug, dryRun: true, …} or {slug, confirm, by: "operator", …}). */ +export function purge(ask, body) { + return ask("/api/ops/purge-trending", { method: "POST", body }); +} + +/** + * What became of the keeps' archiving, as one sentence (or "" when nothing was kept). + * @param {{ kept: string[], archives: Array<{jobId?: string, error?: string, ids: string[]}> }} r + */ +export function archiveSentence(r) { + if (!r.kept.length) return ""; + const started = r.archives.filter((a) => a.jobId); + const refused = r.archives.filter((a) => a.error); + const n = (k) => `${k} post${k === 1 ? "" : "s"}`; + const parts = []; + if (started.length) parts.push(`${n(started.reduce((s, a) => s + a.ids.length, 0))} queued for archiving (the editor's capture job${started.length === 1 ? "" : "s"} ${started.map((a) => a.jobId).join(", ")})`); + if (refused.length) parts.push(`${n(refused.reduce((s, a) => s + a.ids.length, 0))} kept but not archived now: ${refused[0].error}`); + if (!parts.length) parts.push(`${n(r.kept.length)} kept, not archived now`); + return parts.join("; ") + "."; +} + +/** + * An asker for a process with no Next around it (the CLI): the editor's URL + * and the shared token, the editor's refusals as Errors with its words. + * @param {{ editorUrl: string, token: string, doFetch?: typeof fetch, timeoutMs?: number }} o + */ +export function editorAsker({ editorUrl, token, doFetch = fetch, timeoutMs = 30_000 }) { + const base = String(editorUrl).replace(/\/+$/, ""); + return async (route, init = {}) => { + if (!token) throw new Error("WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with."); + let res; + try { + res = await doFetch(`${base}${route}`, { + method: init.method ?? "GET", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (err) { + throw new Error(`could not reach the editor at ${base}: ${err?.message ?? err}`); + } + const body = await res.json().catch(() => ({})); + if (!res.ok || body.ok === false) throw new Error(String(body.error ?? `the editor answered HTTP ${res.status}`)); + return body; + }; +} diff --git a/umtool/lib/library/client.test.mjs b/umtool/lib/library/client.test.mjs @@ -0,0 +1,90 @@ +// The Posts library's calls to the editor (lane posts-library): the query a +// view becomes, judging in chunks the editor takes, and the asker's refusals. +// No socket: `ask` and `doFetch` are fakes. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { archiveSentence, editorAsker, judge, JUDGE_CHUNK, libraryQuery, listLibraries, listLibraryIds, listLibraryRows, purge, watch } from "./client.mjs"; + +function recorder(answers) { + const asked = []; + const ask = async (route, init = {}) => { + asked.push({ route, ...init }); + return typeof answers === "function" ? answers(route, init, asked.length) : answers; + }; + return { ask, asked }; +} + +test("a view becomes the editor's query: only what is asked is sent", () => { + assert.equal(libraryQuery({ slug: "lib" }), "/api/ops/trending?slug=lib"); + assert.equal( + libraryQuery({ slug: "lib", topic: "kettles", limit: 50, offset: 100, state: "unjudged", gone: true, media: true, author: "teapot_news", q: " kettle lid ", since: "2026-11-17T10:00:00.000Z", detail: true }), + "/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"); +}); + +test("the libraries, the ids of a filter, and every row a page at a time", async () => { + const libs = recorder({ ok: true, libraries: [{ slug: "lib", name: "Lib", topics: 1, posts: 2, unjudged: 1 }] }); + assert.deepEqual(await listLibraries(libs.ask), [{ slug: "lib", name: "Lib", topics: 1, posts: 2, unjudged: 1 }]); + assert.equal(libs.asked[0].route, "/api/ops/trending"); + + const ids = recorder({ ok: true, ids: ["1", "2"], posts: [] }); + assert.deepEqual(await listLibraryIds(ids.ask, { slug: "lib", state: "drop", limit: 5, offset: 5, detail: true }), ["1", "2"]); + assert.equal(ids.asked[0].route, "/api/ops/trending?slug=lib&state=drop&ids=1"); + + const total = 620; + const rows = recorder((route) => { + const offset = Number(new URL(route, "http://x").searchParams.get("offset") ?? 0); + return { ok: true, total, posts: Array.from({ length: Math.min(500, total - offset) }, (_, i) => ({ id: String(offset + i) })) }; + }); + assert.equal((await listLibraryRows(rows.ask, { slug: "lib" })).length, total); + assert.deepEqual(rows.asked.map((a) => a.route), ["/api/ops/trending?slug=lib&limit=500&detail=1", "/api/ops/trending?slug=lib&limit=500&offset=500&detail=1"]); +}); + +test("judging goes in chunks of at most 500: one ask, so one capture job, per chunk — never one per post", async () => { + const set = Array.from({ length: 2 * JUDGE_CHUNK + 7 }, (_, i) => ({ id: String(1000 + i), state: "keep" })); + const r = recorder((route, init, n) => ({ ok: true, written: init.body.set.map((s) => ({ id: s.id, state: s.state })), skipped: [], kept: init.body.set.map((s) => s.id), archive: { jobId: `job-${n}`, ids: init.body.set.map((s) => s.id) } })); + const out = await judge(r.ask, { slug: "lib", by: "operator", set }); + assert.equal(r.asked.length, 3); + assert.deepEqual(r.asked.map((a) => a.body.set.length), [500, 500, 7]); + assert.ok(r.asked.every((a) => a.route === "/api/ops/judge-trending" && a.method === "POST" && a.body.by === "operator" && a.body.slug === "lib" && !("archive" in a.body))); + assert.equal(out.asks, 3); + assert.equal(out.kept.length, 1007); + assert.deepEqual(out.archives.map((a) => a.jobId), ["job-1", "job-2", "job-3"]); + assert.match(archiveSentence(out), /^1007 posts queued for archiving \(the editor's capture jobs job-1, job-2, job-3\)\.$/); + + // archive: false is passed on (an undo), and starts nothing. + const undo = recorder({ ok: true, written: [], skipped: [], kept: [] }); + await judge(undo.ask, { slug: "lib", by: "operator", set: [{ id: "1", state: "undecided" }], archive: false }); + assert.equal(undo.asked[0].body.archive, false); + assert.equal(archiveSentence({ kept: [], archives: [] }), ""); + assert.match(archiveSentence({ kept: ["1"], archives: [{ error: "X's cookie jar is 70 minutes old", ids: ["1"] }] }), /^1 post kept but not archived now: X's cookie jar is 70 minutes old\.$/); +}); + +test("the watch and the purge post their bodies as given", async () => { + const r = recorder({ ok: true }); + await watch(r.ask, { slug: "lib", topic: "kettles", on: true, by: "operator" }); + await purge(r.ask, { slug: "lib", dryRun: true }); + assert.deepEqual(r.asked, [ + { route: "/api/ops/watch-trending", method: "POST", body: { slug: "lib", topic: "kettles", on: true, by: "operator" } }, + { route: "/api/ops/purge-trending", method: "POST", body: { slug: "lib", dryRun: true } }, + ]); +}); + +test("the CLI's asker: the bearer, the editor's words on a refusal, a sentence when nothing answers or no token is set", async () => { + const calls = []; + const ok = editorAsker({ editorUrl: "http://editor.invalid:1/", token: "t", doFetch: async (url, init) => (calls.push({ url, init }), new Response(JSON.stringify({ ok: true, n: 1 }))) }); + assert.deepEqual(await ok("/api/ops/trending"), { ok: true, n: 1 }); + assert.equal(calls[0].url, "http://editor.invalid:1/api/ops/trending"); + assert.equal(calls[0].init.headers.authorization, "Bearer t"); + const refused = editorAsker({ editorUrl: "http://editor.invalid:1", token: "t", doFetch: async () => new Response(JSON.stringify({ ok: false, error: "lib is not an X trending library" }), { status: 400 }) }); + await assert.rejects(refused("/x"), /lib is not an X trending library/); + const down = editorAsker({ editorUrl: "http://editor.invalid:1", token: "t", doFetch: async () => { throw new Error("ECONNREFUSED"); } }); + await assert.rejects(down("/x"), /could not reach the editor at http:\/\/editor\.invalid:1: ECONNREFUSED/); + let asked = false; + const none = editorAsker({ editorUrl: "http://editor.invalid:1", token: "", doFetch: async () => ((asked = true), new Response("{}")) }); + await assert.rejects(none("/x"), /WORKER_TOKEN is not set/); + assert.equal(asked, false); +}); diff --git a/umtool/lib/library/filters.mjs b/umtool/lib/library/filters.mjs @@ -0,0 +1,91 @@ +// THE POSTS LIBRARY PAGE'S VIEW, AS ITS URL SAYS IT (lane posts-library): +// /tools/library?lib=&topic=&state=&gone=1&media=1&author=&q=&new=1&offset= +// A phone and a desktop open the same view from the same link. Plain ESM. + +import { LIBRARY_STATES } from "./client.mjs"; + +export const LIBRARY_PATH = "/tools/library"; +export const PAGE_SIZE = 50; + +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const TOPIC = /^[a-z0-9][a-z0-9-]{0,119}$/; +const HANDLE = /^@?[A-Za-z0-9_]{1,30}$/; +const one = (v) => (Array.isArray(v) ? v[0] : v); +const flag = (v) => one(v) === "1"; + +/** + * The view a page's search params ask for; anything ill-shaped is dropped, never thrown. + * @param {Record<string, string | string[] | undefined>} sp + * @returns {{ lib: string|null, topic: string|null, state: string|null, gone: boolean, media: boolean, author: string|null, q: string, fresh: boolean, offset: number }} + */ +export function parseLibraryView(sp) { + const str = (k) => (typeof one(sp[k]) === "string" ? one(sp[k]).trim() : ""); + const offset = Number(str("offset")); + return { + lib: SLUG.test(str("lib")) ? str("lib") : null, + topic: TOPIC.test(str("topic")) ? str("topic") : null, + state: LIBRARY_STATES.includes(str("state")) ? str("state") : null, + gone: flag(sp.gone), + media: flag(sp.media), + author: HANDLE.test(str("author")) ? str("author").replace(/^@/, "") : null, + q: str("q").slice(0, 200), + fresh: flag(sp.new), + offset: Number.isInteger(offset) && offset > 0 ? offset : 0, + }; +} + +/** The page's address for a view (a partial one: what is absent is off). */ +export function libraryHref(view = {}) { + const q = new URLSearchParams(); + if (view.lib) q.set("lib", view.lib); + if (view.topic) q.set("topic", view.topic); + if (view.state) q.set("state", view.state); + if (view.gone) q.set("gone", "1"); + if (view.media) q.set("media", "1"); + if (view.author) q.set("author", view.author); + if (view.q) q.set("q", view.q); + if (view.fresh) q.set("new", "1"); + if (view.offset) q.set("offset", String(view.offset)); + const s = q.toString(); + return s ? `${LIBRARY_PATH}?${s}` : LIBRARY_PATH; +} + +/** + * The editor's listing parameters for a view. `seenAt` is the topic's Mark + * seen time: "new" means first shown by a read after it (never marked: every + * post is new, so no `since`). + */ +export function listingParamsOf(view, { seenAt = null } = {}) { + return { + slug: view.lib, + topic: view.topic, + state: view.state, + gone: view.gone, + media: view.media, + author: view.author, + q: view.q, + since: view.fresh && seenAt ? seenAt : null, + }; +} + +/** The filters in force, in words, for a confirm ("unjudged, with media, by @x"); "" for none. */ +export function filterWords(view) { + const out = []; + if (view.state) out.push(view.state === "unjudged" ? "unjudged" : view.state === "keep" ? "kept" : view.state === "drop" ? "dropped" : "marked later"); + if (view.fresh) out.push("new since Mark seen"); + if (view.gone) out.push("gone from the page"); + if (view.media) out.push("with media"); + if (view.author) out.push(`by @${view.author}`); + if (view.q) out.push(`matching “${view.q}”`); + return out.join(", "); +} + +/** "gone from the page at <time>": the one sentence for a gone mark. Never "deleted". */ +export function goneSentence(gone, fmt = (iso) => iso) { + return gone && typeof gone.at === "string" ? `Gone from the page at ${fmt(gone.at)}` : ""; +} + +/** A capture's own state, verbatim: "capture: <state> at <time>". */ +export function captureSentence(capture, fmt = (iso) => iso) { + return capture && typeof capture.state === "string" ? `capture: ${capture.state} at ${fmt(capture.at)}` : ""; +} diff --git a/umtool/lib/library/keys.mjs b/umtool/lib/library/keys.mjs @@ -0,0 +1,47 @@ +// THE POSTS LIBRARY'S KEYS (lane posts-library), one table: the page's +// handler, its key bar and the `?` sheet all read it. Plain ESM. + +export const LIBRARY_KEYS = [ + { key: "j", action: "next", label: "next post" }, + { key: "k", action: "prev", label: "previous post" }, + { key: "a", action: "keep", label: "keep" }, + { key: "d", action: "drop", label: "drop" }, + { key: "l", action: "later", label: "later" }, + { key: "c", action: "clear", label: "clear the judgement" }, + { key: "t", action: "scope", label: "judge the post or its whole thread" }, + { key: "n", action: "note", label: "note" }, + { key: "x", action: "select", label: "select" }, + { key: "A", action: "bulk-keep", label: "keep everything in the filter" }, + { key: "D", action: "bulk-drop", label: "drop everything in the filter" }, + { key: "L", action: "bulk-later", label: "mark everything in the filter later" }, + { key: "u", action: "undo", label: "undo the last press" }, + { key: "/", action: "search", label: "search" }, + { key: "g", action: "gone", label: "only gone from the page" }, + { key: "m", action: "media", label: "only with media" }, + { key: "?", action: "help", label: "this list" }, +]; + +const BY_KEY = new Map(LIBRARY_KEYS.map((k) => [k.key, k.action])); + +/** + * The action a key press asks for, or null: nothing while typing in a field, + * nothing with Ctrl / Meta / Alt held (the browser's own keys). + * @param {{ key: string, ctrlKey?: boolean, metaKey?: boolean, altKey?: boolean, typing?: boolean }} e + */ +export function libraryAction(e) { + if (e.typing || e.ctrlKey || e.metaKey || e.altKey) return null; + return BY_KEY.get(e.key) ?? null; +} + +/** Whether a key event's target is a field being typed in. */ +export function isTyping(target) { + if (!target || typeof target !== "object") return false; + const tag = String(target.tagName ?? "").toLowerCase(); + return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable === true; +} + +/** The judge state an action sets ("undecided" removes the judgement), or null. */ +export function stateOfAction(action) { + const a = String(action ?? "").replace(/^bulk-/, ""); + return a === "keep" || a === "drop" || a === "later" ? a : a === "clear" ? "undecided" : null; +} diff --git a/umtool/lib/library/media.mjs b/umtool/lib/library/media.mjs @@ -0,0 +1,63 @@ +// A LIBRARY'S CAPTURED MEDIA, FOUND FOR THE ONE ROUTE THAT SERVES IT (lane +// posts-library): GET /api/library/media/<lib>/<id>/<name>. +// +// A trending library is PRIVATE. Every other reader of the corpus in umtool +// refuses a library by its marker; this is the one that REQUIRES it, and it +// can name exactly one kind of file: +// +// <channelsDir>/<lib>/trending/posts-media/<id>/<name> +// +// lib a slug whose config.json carries the library marker +// id digits only +// name one path segment of [A-Za-z0-9._-], not starting with a dot, with a +// picture's or a video's extension — so never capture.json, an +// article's text, the raw reads, the judgements or the index +// and the file's REAL path must sit under the real trending/posts-media of +// that library: a name that is a symlink out of it is refused. (The media +// files are hardlinks into the library's store, which are plain files.) +// +// It lists nothing: no directory, no index of ids. Plain ESM. +import { realpath, stat } from "node:fs/promises"; +import path from "node:path"; +import { isTrendingLibrary } from "../report/xTrendingMarker.mjs"; + +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const ID = /^\d{1,32}$/; +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +export const LIBRARY_MEDIA_TYPES = Object.freeze({ + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + ".gif": "image/gif", + ".mp4": "video/mp4", + ".m4v": "video/mp4", + ".mov": "video/quicktime", + ".webm": "video/webm", +}); + +/** The address the page gives a captured file. */ +export function libraryMediaSrc(lib, id, name) { + return `/api/library/media/${encodeURIComponent(lib)}/${encodeURIComponent(id)}/${encodeURIComponent(name)}`; +} + +/** + * The file a media request names, or why not. + * @param {{ channelsDir: string, lib: string, id: string, name: string }} o + * @returns {Promise<{ ok: true, abs: string, size: number, type: string } | { ok: false, status: 400 | 404 }>} + */ +export async function resolveLibraryMedia({ channelsDir, lib, id, name }) { + if (typeof lib !== "string" || typeof id !== "string" || typeof name !== "string") return { ok: false, status: 400 }; + if (!SLUG.test(lib) || !ID.test(id) || !NAME.test(name) || name.includes("..")) return { ok: false, status: 400 }; + const type = LIBRARY_MEDIA_TYPES[path.extname(name).toLowerCase()]; + if (!type) return { ok: false, status: 404 }; + if (!(await isTrendingLibrary(channelsDir, lib))) return { ok: false, status: 404 }; + const root = path.join(/* turbopackIgnore: true */ channelsDir, lib, "trending", "posts-media"); + const abs = path.join(/* turbopackIgnore: true */ root, id, name); + const [real, realRoot] = await Promise.all([realpath(/* turbopackIgnore: true */ abs).catch(() => null), realpath(/* turbopackIgnore: true */ root).catch(() => null)]); + if (!real || !realRoot || !real.startsWith(realRoot + path.sep)) return { ok: false, status: 404 }; + const st = await stat(/* turbopackIgnore: true */ real).catch(() => null); + if (!st?.isFile()) return { ok: false, status: 404 }; + return { ok: true, abs: real, size: st.size, type }; +} diff --git a/umtool/lib/library/media.test.mjs b/umtool/lib/library/media.test.mjs @@ -0,0 +1,95 @@ +// The one file a library's media route may name (lane posts-library), over a +// temp corpus: only a picture or a video under +// channels/<lib>/trending/posts-media/<id>/ of a channel carrying the library +// marker — never the record, the raw reads, another channel, or a name that +// resolves outside the directory. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { link, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { libraryMediaSrc, resolveLibraryMedia } from "./media.mjs"; + +const ID = "1900000000000006001"; + +async function corpus() { + const channels = await mkdtemp(path.join(tmpdir(), "umtool-library-media-")); + const lib = path.join(channels, "trending-lib"); + const cap = path.join(lib, "trending", "posts-media", ID); + await mkdir(cap, { recursive: true }); + await writeFile(path.join(lib, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); + await writeFile(path.join(cap, "shot.png"), "SHOT"); + await writeFile(path.join(cap, "capture.json"), "{}"); + await writeFile(path.join(cap, "article.md"), "words"); + // A media file as the store leaves it: a hardlink to its blob. + await mkdir(path.join(lib, "trending", "media-store", "ab"), { recursive: true }); + await writeFile(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), "VIDEO-BYTES"); + await link(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), path.join(cap, `${ID}_1.mp4`)); + // What must never be served. + await mkdir(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000"), { recursive: true }); + await writeFile(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), "RAW-PAGE"); + await writeFile(path.join(lib, "trending", "judgements.json"), "{}"); + await writeFile(path.join(channels, "outside.png"), "OUTSIDE"); + // An ordinary posts channel with a capture of the same shape. + const account = path.join(channels, "kettle-org-x"); + await mkdir(path.join(account, "posts-media", ID), { recursive: true }); + await mkdir(path.join(account, "trending", "posts-media", ID), { recursive: true }); + await writeFile(path.join(account, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", url: "https://x.com/kettle_org" })); + await writeFile(path.join(account, "trending", "posts-media", ID, "shot.png"), "NOT-A-LIBRARY"); + return { channels, lib, cap }; +} + +test("a picture and a video of a library's capture are found, with their type and size", async () => { + const { channels, cap } = await corpus(); + try { + const shot = await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: "shot.png" }); + assert.deepEqual(shot, { ok: true, abs: path.join(cap, "shot.png"), size: 4, type: "image/png" }); + const video = await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: `${ID}_1.mp4` }); + assert.equal(video.ok && video.type, "video/mp4"); + assert.equal(video.ok && video.size, 11); + assert.equal(libraryMediaSrc("trending-lib", ID, "shot.png"), `/api/library/media/trending-lib/${ID}/shot.png`); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); + +test("refused: the record and any non-media name, a traversal, another id shape, a channel that is no library, a missing file", async () => { + const { channels } = await corpus(); + try { + const no = async (lib, id, name) => (await resolveLibraryMedia({ channelsDir: channels, lib, id, name })).ok; + for (const name of ["capture.json", "article.md", "shot", ".hidden.png", "..", "../shot.png", "a/b.png", "shot.png/..", "x..png", ""]) { + assert.equal(await no("trending-lib", ID, name), false, name); + } + for (const id of ["..", "../reads", "_avatars", "", "19a", `${ID}/..`]) assert.equal(await no("trending-lib", id, "shot.png"), false, id); + for (const lib of ["kettle-org-x", "nope", "..", "trending-lib/..", ""]) assert.equal(await no(lib, ID, "shot.png"), false, lib); + assert.equal(await no("trending-lib", ID, "missing.png"), false); + // A directory with a media-looking name is not a file. + assert.equal(await no("trending-lib", "1900000000000006009", "shot.png"), false); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: undefined })).ok, false); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); + +test("a name planted in the capture directory whose real path is OUTSIDE posts-media is refused: the raw read, the corpus, the directory itself", async () => { + const { channels, lib, cap } = await corpus(); + try { + await symlink(path.join(lib, "trending", "reads", "tr-01JA0000000000000000000000", "page.png"), path.join(cap, "raw.png")); + await symlink(path.join(channels, "outside.png"), path.join(cap, "outside.png")); + await symlink(path.join(lib, "trending", "media-store", "ab", "blob.mp4"), path.join(cap, "viastore.mp4")); + await symlink(path.join(lib, "trending", "reads"), path.join(lib, "trending", "posts-media", "1900000000000006002")); + for (const name of ["raw.png", "outside.png", "viastore.mp4"]) { + assert.deepEqual(await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name }), { ok: false, status: 404 }, name); + } + // An id that is a link to another directory. + await writeFile(path.join(lib, "trending", "reads", "x.png"), "RAW"); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: "1900000000000006002", name: "x.png" })).ok, false); + // A link that stays inside posts-media is the file it names. + await symlink(path.join(cap, "shot.png"), path.join(cap, "alias.png")); + assert.equal((await resolveLibraryMedia({ channelsDir: channels, lib: "trending-lib", id: ID, name: "alias.png" })).ok, true); + } finally { + await rm(channels, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/library/seen.mjs b/umtool/lib/library/seen.mjs @@ -0,0 +1,111 @@ +// "NEW SINCE LAST VISIT" (lane posts-library): when the operator pressed Mark +// seen on a topic. UMTOOL'S OWN STATE, beside the projects, never a file of +// the library (umtool writes none of those): +// +// REPORTS_ROOT/.umtool/posts-library.json +// { format: "umtool-posts-library", version: 1, +// libraries: { "<slug>": { topics: { "<topicId>": { seenAt, previous? } } } } } +// +// MOVED ONLY BY AN EXPLICIT PRESS (the page's Mark seen, `umtool library +// seen`): opening the page moves nothing, so "new" stays new until the +// 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. +// +// Plain ESM. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; + +export const SEEN_FORMAT = "umtool-posts-library"; +const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const TOPIC = /^[a-z0-9][a-z0-9-]{0,119}$/; + +export function seenFile(reportsRoot) { + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "posts-library.json"); +} + +const isIso = (v) => typeof v === "string" && Number.isFinite(Date.parse(v)); + +function clean(raw) { + const libraries = {}; + const src = raw && typeof raw === "object" && raw.libraries && typeof raw.libraries === "object" ? raw.libraries : {}; + for (const [slug, lib] of Object.entries(src)) { + if (!SLUG.test(slug) || !lib || typeof lib !== "object") continue; + const topics = {}; + for (const [topic, t] of Object.entries(lib.topics && typeof lib.topics === "object" ? lib.topics : {})) { + if (!TOPIC.test(topic) || !t || !isIso(t.seenAt)) continue; + topics[topic] = { seenAt: t.seenAt, ...(isIso(t.previous) ? { previous: t.previous } : {}) }; + } + libraries[slug] = { topics }; + } + return libraries; +} + +/** + * Every mark: `{ libraries, error? }`. A missing file is empty; an unreadable one is empty with `error`. + * @param {string} reportsRoot + */ +export async function readSeen(reportsRoot) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ seenFile(reportsRoot), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { libraries: {} }; + return { libraries: {}, error: `posts-library.json cannot be read: ${err?.message ?? err}` }; + } + try { + return { libraries: clean(JSON.parse(text)) }; + } catch { + return { libraries: {}, error: "posts-library.json does not parse: nothing is marked seen until it is fixed" }; + } +} + +/** A library's marks: { [topicId]: seenAt }. */ +export async function seenOf(reportsRoot, slug) { + const { libraries } = await readSeen(reportsRoot); + return Object.fromEntries(Object.entries(libraries[slug]?.topics ?? {}).map(([t, v]) => [t, v.seenAt])); +} + +let chain = Promise.resolve(); + +/** + * Mark topics of a library seen now. Refuses (throws) an ill-shaped name, and + * a file that is there and does not parse. + * @param {string} reportsRoot + * @param {{ slug: string, topics: string[], now?: number }} o + * @returns {Promise<{ slug: string, topics: Record<string, { seenAt: string, previous?: string }> }>} + */ +export function markSeen(reportsRoot, { slug, topics, now = Date.now() }) { + if (!SLUG.test(String(slug))) return Promise.reject(new Error(`"${slug}" is not a library's slug`)); + if (!Array.isArray(topics) || topics.length === 0 || !topics.every((t) => TOPIC.test(String(t)))) return Promise.reject(new Error("Mark seen needs the topic ids to mark")); + const run = async () => { + const current = await readSeen(reportsRoot); + if (current.error) throw new Error(current.error); + const lib = current.libraries[slug] ?? { topics: {} }; + const seenAt = new Date(now).toISOString(); + const marked = {}; + for (const t of topics) { + const was = lib.topics[t]?.seenAt; + lib.topics[t] = { seenAt, ...(was ? { previous: was } : {}) }; + marked[t] = lib.topics[t]; + } + current.libraries[slug] = lib; + const file = seenFile(reportsRoot); + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = tmpPathFor(file); + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify({ format: SEEN_FORMAT, version: 1, libraries: current.libraries }, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + 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 @@ -0,0 +1,51 @@ +// Mark seen (lane posts-library): umtool's own state under a reports root's +// .umtool/, moved only by the press. A temp root, never the operator's. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { markSeen, readSeen, 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-")); + try { + assert.deepEqual(await readSeen(root), { libraries: {} }); + assert.deepEqual(await seenOf(root, "lib"), {}); + // Reading wrote nothing. + assert.deepEqual(await readdir(root), []); + + const t1 = Date.parse("2026-11-18T10:00:00.000Z"); + assert.deepEqual(await markSeen(root, { slug: "lib", topics: ["kettles"], now: t1 }), { slug: "lib", topics: { kettles: { seenAt: "2026-11-18T10:00:00.000Z" } } }); + assert.equal(seenFile(root), path.join(root, ".umtool", "posts-library.json")); + assert.deepEqual(await seenOf(root, "lib"), { kettles: "2026-11-18T10:00:00.000Z" }); + + const t2 = Date.parse("2026-11-18T12:00:00.000Z"); + await Promise.all([markSeen(root, { slug: "lib", topics: ["kettles", "cups"], now: t2 }), markSeen(root, { slug: "other", topics: ["cups"], now: t2 })]); + const doc = JSON.parse(await readFile(seenFile(root), "utf8")); + assert.equal(doc.format, "umtool-posts-library"); + assert.deepEqual(doc.libraries.lib.topics, { kettles: { seenAt: "2026-11-18T12:00:00.000Z", previous: "2026-11-18T10:00:00.000Z" }, cups: { seenAt: "2026-11-18T12:00:00.000Z" } }); + assert.deepEqual(await seenOf(root, "other"), { cups: "2026-11-18T12:00:00.000Z" }); + assert.deepEqual((await readdir(path.join(root, ".umtool"))).sort(), ["posts-library.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("refused: an ill-shaped slug or topic, no topics; a file that does not parse is never written over", async () => { + const root = await mkdtemp(path.join(tmpdir(), "umtool-library-seen-")); + try { + await assert.rejects(markSeen(root, { slug: "../x", topics: ["kettles"] }), /not a library's slug/); + await assert.rejects(markSeen(root, { slug: "lib", topics: [] }), /topic ids/); + await assert.rejects(markSeen(root, { slug: "lib", topics: ["../x"] }), /topic ids/); + await mkdir(path.join(root, ".umtool"), { recursive: true }); + await writeFile(seenFile(root), "{ not json"); + assert.match((await readSeen(root)).error, /does not parse/); + await assert.rejects(markSeen(root, { slug: "lib", topics: ["kettles"] }), /does not parse/); + assert.equal(await readFile(seenFile(root), "utf8"), "{ not json"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/library/undo.mjs b/umtool/lib/library/undo.mjs @@ -0,0 +1,43 @@ +// UNDO OF THE LAST PRESS (lane posts-library): the judge-trending set that +// puts back what each judged id (a post, or a thread) held before the press +// — its OWN entry's state and note, or "undecided" when it had none. +// +// It is sent with `archive: false`: an undo starts no capture, and it does not +// cancel one a keep already queued (the capture job asks, before each +// download, whether the post is still kept). The entry it restores is written +// by the operator's hand, whoever wrote the one before. +// +// Plain ESM, no imports. + +export const UNDO_SAYS = "Undo puts the judgements back. 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" }); + +/** + * The set that undoes a press on `targets`, read from the rows as they were + * BEFORE it (the listing's detail rows: `detail.ownJudgement`, `detail.threadJudgement`). + * A target no row speaks for goes back to undecided. + * + * @param {Array<{id: string, thread: string, detail?: {ownJudgement?: object, threadJudgement?: object}}>} rows + * @param {Array<{id?: string, thread?: string}>} targets + * @returns {Array<{id?: string, thread?: string, state: string, note?: string}>} + */ +export function undoSetOf(rows, targets) { + const byId = new Map(rows.map((r) => [r.id, r])); + const byThread = new Map(); + for (const r of rows) if (!byThread.has(r.thread)) byThread.set(r.thread, r); + return targets.map((t) => + t.thread !== undefined + ? { thread: t.thread, ...before(byThread.get(t.thread)?.detail?.threadJudgement) } + : { id: t.id, ...before(byId.get(t.id)?.detail?.ownJudgement) }, + ); +} + +/** The set a press sends: every target with the state (and the note, for a judgement that is not removed). */ +export function pressSetOf(targets, state, note = "") { + return targets.map((t) => ({ + ...(t.thread !== undefined ? { thread: t.thread } : { id: t.id }), + state, + ...(note && state !== "undecided" ? { note } : {}), + })); +} diff --git a/umtool/lib/library/view.test.mjs b/umtool/lib/library/view.test.mjs @@ -0,0 +1,68 @@ +// The Posts library's view, keys and undo (lane posts-library): pure rules. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { captureSentence, filterWords, goneSentence, libraryHref, listingParamsOf, parseLibraryView } from "./filters.mjs"; +import { isTyping, LIBRARY_KEYS, libraryAction, stateOfAction } from "./keys.mjs"; +import { pressSetOf, UNDO_SAYS, undoSetOf } from "./undo.mjs"; + +test("a view is read from the URL and written back; an ill-shaped value is dropped", () => { + const view = parseLibraryView({ lib: "trending-lib", topic: "kettles", state: "unjudged", gone: "1", media: "1", author: "@teapot_news", q: " lid ", new: "1", offset: "50" }); + assert.deepEqual(view, { lib: "trending-lib", topic: "kettles", state: "unjudged", gone: true, media: true, author: "teapot_news", q: "lid", fresh: true, offset: 50 }); + assert.equal(libraryHref(view), "/tools/library?lib=trending-lib&topic=kettles&state=unjudged&gone=1&media=1&author=teapot_news&q=lid&new=1&offset=50"); + assert.deepEqual(parseLibraryView({ lib: "../x", topic: "A B", state: "deleted", gone: "yes", author: "a/b", offset: "-3", q: ["two", "three"] }), { lib: null, topic: null, state: null, gone: false, media: false, author: null, q: "two", fresh: false, offset: 0 }); + assert.equal(libraryHref({}), "/tools/library"); + assert.equal(libraryHref({ lib: "l", state: "keep" }), "/tools/library?lib=l&state=keep"); +}); + +test("\"new\" is first shown since the topic's Mark seen; a topic never marked has no since", () => { + const view = parseLibraryView({ lib: "l", topic: "kettles", new: "1" }); + assert.equal(listingParamsOf(view, { seenAt: "2026-11-17T10:00:00.000Z" }).since, "2026-11-17T10:00:00.000Z"); + assert.equal(listingParamsOf(view).since, null); + assert.equal(listingParamsOf(parseLibraryView({ lib: "l", topic: "kettles" }), { seenAt: "2026-11-17T10:00:00.000Z" }).since, null); +}); + +test("the sentences: the filters in words, gone from the page (never deleted), a capture's state verbatim", () => { + assert.equal(filterWords(parseLibraryView({ state: "unjudged", media: "1", author: "x_y", q: "lid", gone: "1", new: "1" })), "unjudged, new since Mark seen, gone from the page, with media, by @x_y, matching “lid”"); + assert.equal(filterWords(parseLibraryView({})), ""); + assert.equal(goneSentence({ at: "2026-11-17T11:00:00.000Z", read: "r", trendId: "1" }), "Gone from the page at 2026-11-17T11:00:00.000Z"); + assert.equal(goneSentence(undefined), ""); + assert.doesNotMatch(goneSentence({ at: "t" }), /delet/i); + assert.equal(captureSentence({ state: "deleted", at: "2026-11-17T12:00:00.000Z" }), "capture: deleted at 2026-11-17T12:00:00.000Z"); + assert.equal(captureSentence({ state: "captured", at: "T" }, () => "noon"), "capture: captured at noon"); +}); + +test("the keys: one action per key, none while typing or with a modifier held", () => { + assert.equal(new Set(LIBRARY_KEYS.map((k) => k.key)).size, LIBRARY_KEYS.length); + const of = (key, extra = {}) => libraryAction({ key, ...extra }); + assert.deepEqual(["j", "k", "a", "d", "l", "c", "t", "n", "x", "u", "/", "g", "m", "?"].map((k) => of(k)), ["next", "prev", "keep", "drop", "later", "clear", "scope", "note", "select", "undo", "search", "gone", "media", "help"]); + assert.deepEqual(["A", "D", "L"].map((k) => of(k)), ["bulk-keep", "bulk-drop", "bulk-later"]); + assert.equal(of("a", { typing: true }), null); + assert.equal(of("a", { ctrlKey: true }), null); + assert.equal(of("d", { metaKey: true }), null); + assert.equal(of("q"), null); + assert.equal(isTyping({ tagName: "TEXTAREA" }), true); + assert.equal(isTyping({ tagName: "DIV", isContentEditable: true }), true); + assert.equal(isTyping({ tagName: "BUTTON" }), false); + assert.deepEqual(["keep", "drop", "later", "clear", "bulk-drop", "next"].map(stateOfAction), ["keep", "drop", "later", "undecided", "drop", null]); +}); + +test("undo puts back each id's OWN entry, or removes the judgement it had none of; a thread press restores the thread's", () => { + const rows = [ + { id: "1", thread: "1", detail: { ownJudgement: { state: "later", note: "check", by: "agent", at: "t" }, threadJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "2", thread: "1", detail: { threadJudgement: { state: "keep", by: "operator", at: "t" } } }, + { id: "3", thread: "3", detail: {} }, + ]; + assert.deepEqual(undoSetOf(rows, [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "9" }]), [ + { id: "1", state: "later", note: "check" }, + // 2 had only its thread's judgement: its own goes back to none. + { id: "2", state: "undecided" }, + { id: "3", state: "undecided" }, + { id: "9", state: "undecided" }, + ]); + assert.deepEqual(undoSetOf(rows, [{ thread: "1" }, { thread: "3" }]), [{ thread: "1", state: "keep" }, { thread: "3", state: "undecided" }]); + 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/); +});