Archilyzer · Source

archilyzer

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

commit 63e7a318b97f6f7616daa5c7e9d508025b440b96
parent 3bae7d22e4c57950e0a55f9ca71b0caf43899c91
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 19:29:25 -0500

review 1 S1-S5 and the nits: a search-phase place is checked exactly; an old place says what it will do; the tab, the name and the publish say where they come from

- S1. A walk resumed from a search-phase place `3_<N>/` stops when a first-page post is above N: the
  place lists only posts at or below it. The check against the archive's newest id stays for a
  timeline-phase place, where a deleted newest post or an imported newer one could hide a restart.
- S2. A resumed backfill whose place is in the timeline phase says once that it may pass through
  posts already archived first. The place is not rewritten to one below the archive's oldest post:
  nothing in gallery-dl's source proves the archive is unbroken down to it.
- S3. A read's tab is the one NAMED timeline's; a post first seen in an answer that named no
  timeline inherits it, and only when exactly one was named.
- S4. A topic is named from what its source holds after the update, under the same age guard: an
  older read parsed again never names a topic by an older title.
- S5. A publish dry run says when the topic is named by X's page (`titleFrom`), and that the slug is
  still the caller's to name.
- A topic's `titleFrom` ("page", "ask", "rename") is a field of its own that no merge or move
  writes; a name asked for is a set name even when it is the fallback's words.
- A listing gives at most 600 characters of X's summary (the MCP and umtool's CLI the same); the
  source keeps all of it.
- An architecture pin: no shipped module imports common/testing.
- The invented fixture constants are named INVENTED_, not REAL_.

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

Diffstat:
Mcommon/architecture.test.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchPosts.test.ts | 38++++++++++++++++++++++++++++++++++++++
Mcommon/controller/publishXTrending.test.ts | 39+++++++++++++++++++++++++++++++++++++++
Mcommon/controller/publishXTrending.ts | 17++++++++++++++++-
Mcommon/controller/readXTrending.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++------------------------
Mcommon/controller/readXTrending.ts | 12++++++++++--
Mcommon/lib/xTrending/organise.ts | 5++++-
Mcommon/lib/xTrending/store.test.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mcommon/social/__fixtures__/xTrendingRealShape.ts | 48+++++++++++++++++++++++++-----------------------
Mcommon/social/xGalleryDlFetcher.test.ts | 23+++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 67++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/social/xTrendingParse.test.ts | 42+++++++++++++++++++++---------------------
Mmcp/src/xTrending.test.ts | 12++++++++++++
Mmcp/src/xTrending.ts | 12+++++++++++-
Mumtool/lib/library/cli.mjs | 2+-
Mumtool/lib/library/cli.test.mjs | 9+++++++++
17 files changed, 535 insertions(+), 99 deletions(-)

diff --git a/common/architecture.test.ts b/common/architecture.test.ts @@ -316,3 +316,63 @@ test("views/ never calls a singleton getter, a disk reader or the clock", async `Found: ${offenders.join(", ")}`, ); }); + +// ── the test kit stays out of production code (review 1 of lane x-followups) ── +// +// `common/testing/` is helpers for tests only (its README: "nothing in an app +// imports from here"). One of them, testing/jobs/asEditorJob.ts, makes a call +// stand where the editor's job does — the context an X fetch asks for before +// it asks X anything (controller/fetchPosts.ts X_ONLY_AS_A_JOB). Imported by +// production code it would be a way past that rule, so the README's sentence +// is enforced here: no module that ships — under common/ outside testing/, or +// in the editor, umtool, the MCP, the export, the homepage or scripts/ — +// imports from the test kit. Tests, e2e suites and fixtures may. +const REPO = path.resolve(HERE, ".."); +const SHIPPED_ROOTS = ["common", "editor/app", "umtool/app", "umtool/lib", "umtool/components", "umtool/bin", "umtool/report-to-video", "mcp/src", "export/app", "homepage/app", "scripts"]; +const SOURCE_FILE = /\.(?:ts|tsx|mts|cts|mjs|cjs|js|jsx)$/; +// Not shipped: a test, an e2e spec's unit, a fixture, the kit itself. +const TEST_ONLY = /(?:\.test\.|\.unit\.|\.fixtures?\.|(?:^|\/)(?:__fixtures__|fixtures|e2e|testing|node_modules|\.next|test-results[^/]*)\/)/; +const TESTING_IMPORT = /(?:from\s+|import\s*\(\s*|require\s*\(\s*|import\s+)["'](?:[^"']*\/)?(?:common\/testing|yt-dlp-transcript-common\/testing|\.\.?\/(?:\.\.\/)*testing)\/[^"']*["']/; + +async function sourceFilesUnder(dir: string, out: string[] = []): Promise<string[]> { + for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) { + const full = path.join(dir, entry.name); + const rel = path.relative(REPO, full).split(path.sep).join("/"); + if (entry.isDirectory()) { + if (!TEST_ONLY.test(`${rel}/`) && entry.name !== "node_modules" && !entry.name.startsWith(".")) await sourceFilesUnder(full, out); + } else if (SOURCE_FILE.test(entry.name) && !TEST_ONLY.test(rel)) { + out.push(full); + } + } + return out; +} + +test("no shipped module imports the test kit (common/testing)", async () => { + // The pattern sees each way of writing the import… + for (const line of [ + 'import { asEditorJob } from "../testing/jobs/asEditorJob";', + 'const kit = await import("../../testing/jobs/asEditorJob");', + 'import { x } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";', + 'import { x } from "../../common/testing/chartPixels";', + "const kit = require('./testing/makeZip');", + ]) { + assert.match(line, TESTING_IMPORT, line); + } + // …and not a module that merely has the word in its name. + for (const line of ['import { x } from "../lib/testingLibrary";', 'import { y } from "@testing-library/react";', 'import { z } from "./quiesce";']) { + assert.doesNotMatch(line, TESTING_IMPORT, line); + } + const offenders: string[] = []; + let scanned = 0; + for (const root of SHIPPED_ROOTS) { + for (const file of await sourceFilesUnder(path.join(REPO, root))) { + scanned++; + const text = await readFile(file, "utf8"); + for (const [i, line] of text.split("\n").entries()) { + if (TESTING_IMPORT.test(line)) offenders.push(`${path.relative(REPO, file)}:${i + 1}: ${line.trim()}`); + } + } + } + assert.ok(scanned > 500, `the walk found the code (${scanned} files)`); + assert.deepEqual(offenders, [], "shipped code imports common/testing:\n" + offenders.join("\n")); +}); diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -702,3 +702,41 @@ test("M1: no fetcher of the twitter platform probes X — the answer is read off assert.equal(fetched, 0); assert.equal(await spawned(), before, "gallery-dl was not started"); }); + +// ── review 1 S1, S2 ──────────────────────────────────────────────────────── + +test("S1: a walk resumed from a search-phase place stops when it reads a post above that place, though the archive holds newer ones", async () => { + const { X_RESUME_POINT_NOT_HONOURED } = await import("../social/xGalleryDlFetcher"); + // Post n has id 1899000000000000100 - n: the place below is "at or below post 60". + const { root, run } = await scripted("ceiling", { + "": [{ posts: [0, 59] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000040" }, RATE_LIMIT, { wait: 60_000 }], + // Not honoured, and NOT from the top either: the walk comes back ten posts above its place. + "3_1899000000000000040/": [{ posts: [50, 300] }, { wait: 60_000 }], + }); + await run({}, /rate limit/); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000040/"); + const started = Date.now(); + const resumed = await run({ backfill: true }); + assert.ok(Date.now() - started < 30_000); + assert.equal(resumed.result.ok, false); + assert.equal(resumed.result.error, X_RESUME_POINT_NOT_HONOURED); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000040/"); + assert.equal((await readSeenPostIds(root)).size, 60); +}); + +test("S2: a resumed backfill whose place is in the timeline phase says it may pass through archived posts first; a search-phase place says nothing", async () => { + const { X_TIMELINE_PHASE_PLACE_NOTE } = await import("../social/xGalleryDlFetcher"); + const { root, run } = await scripted("old-place", { + "": [{ posts: [0, 5] }, { err: "[twitter][debug] Cursor: 1/TL-P1" }, RATE_LIMIT, { wait: 60_000 }], + "1/TL-P1": [{ posts: [6, 8] }, { err: "[twitter][debug] Next 'max_id': 1899000000000000091" }, RATE_LIMIT, { wait: 60_000 }], + "3_1899000000000000091/": [{ posts: [9, 9] }], + }); + const first = await run({}, /rate limit/); + assert.ok(!first.log.includes(X_TIMELINE_PHASE_PLACE_NOTE)); + const old = await run({ backfill: true }, /rate limit/); + assert.equal(old.log.filter((l) => l === X_TIMELINE_PHASE_PLACE_NOTE).length, 1); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "3_1899000000000000091/"); + const next = await run({ backfill: true }); + assert.ok(!next.log.includes(X_TIMELINE_PHASE_PLACE_NOTE)); + assert.equal(next.result.complete, true); +}); diff --git a/common/controller/publishXTrending.test.ts b/common/controller/publishXTrending.test.ts @@ -631,3 +631,42 @@ test("S8: a file whose bytes are no longer what its capture recorded is not publ await deleteChannel(paths, "zzlibs8"); await deleteChannel(paths, "s8-channel"); }); + +// Review 1 S5. +test("S5: a dry run says when the topic is named by X's page, not by a person; the slug is still the caller's to name; a rename ends it", async () => { + const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); + const lib = "zzpagetitledlib"; + const libRoot = path.join(paths.channelsDir, lib); + await createChannel(paths, lib, { name: "A library", handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} }); + await writeXTrendingPosts(libRoot, [post(lib, "901", "words of 901"), post(lib, "902", "words of 902")]); + // Nobody named the topic: it took the page's title. + await recordXTrendingRead(libRoot, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["901"], added: 1, page: { title: "Kettle festival opens" } }); + await recordXTrendingRead(libRoot, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["902"], added: 1 }); + await judgeXTrending(libRoot, { by: "operator", set: [{ id: "901", state: "keep" }, { id: "902", state: "keep" }] }); + const ask = { slug: lib, topic: `t-${REF.trendId}`, deriveSlug: derive, busy: IDLE }; + const dry = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(dry.ok, dry.ok ? "" : dry.error); + assert.equal(dry.result.titleFrom, "page"); + assert.equal(dry.result.channel, "kettle-festival-opens"); + assert.equal( + dry.result.sentence, + 'Publishing "Kettle festival opens" would make the channel "kettle-festival-opens", on no site, writing 1 post and 0 files (0 B); 0 of the 1 kept post are there already. ' + + `The topic is named by X's page: "Kettle festival opens" — the channel would carry that name. Rename the topic first to publish under your own name; "channel" names another slug than "kettle-festival-opens".` + + " 1 post has no capture yet and is published as its words alone: a later publish adds the files.", + ); + // The slug is the caller's to name, as before. + const named = await publishXTrendingTopic(paths, { ...ask, channel: "my-kettles", dryRun: true }); + assert.ok(named.ok && named.result.channel === "my-kettles" && named.result.titleFrom === "page"); + // A topic made under a name asked for: said to be so, and no such sentence. + const cups = await publishXTrendingTopic(paths, { ...ask, topic: "cups", dryRun: true }); + assert.ok(cups.ok); + assert.equal(cups.result.titleFrom, "ask"); + assert.doesNotMatch(cups.result.sentence, /named by X's page/); + // Renamed by a person: the name is theirs. + assert.equal((await renameXTrendingTopic(libRoot, { topic: `t-${REF.trendId}`, title: "Kettles, my pick", by: "operator", readInFlight: IDLE })).ok, true); + const after = await publishXTrendingTopic(paths, { ...ask, dryRun: true }); + assert.ok(after.ok); + assert.equal(after.result.titleFrom, "rename"); + assert.doesNotMatch(after.result.sentence, /named by X's page/); + rmSync(libRoot, { recursive: true, force: true }); +}); diff --git a/common/controller/publishXTrending.ts b/common/controller/publishXTrending.ts @@ -83,6 +83,8 @@ import { readXTrendingPosts, readXTrendingTopics, resolveXTrendingTopic, + xTrendingTitleFrom, + type XTrendingTitleFrom, xTrendingPostsMediaDir, xTrendingPostsRoot, } from "../lib/xTrending/store"; @@ -313,6 +315,11 @@ export type PublishXTrendingResult = { dryRun: boolean; library: string; topic: { id: string; title: string }; + // WHERE THE TOPIC'S NAME CAME FROM (review 1 S5): "page" — nobody named it + // and it carries its trending page's title, X's words; "ask" or "rename" — + // a person or an agent set it. Absent for the fallback name. The channel a + // first publish makes is called by the topic's name. + titleFrom?: XTrendingTitleFrom; // The channel the posts go into, and whether this publish makes it. channel: string; creates: boolean; @@ -409,10 +416,16 @@ export function publishSentence(r: Omit<PublishXTrendingResult, "sentence">): st const gone = r.noLongerKept.length ? ` ${n(r.noLongerKept.length, "post")} published before ${r.noLongerKept.length === 1 ? "is" : "are"} no longer kept: ${r.noLongerKept.length === 1 ? "it stays" : "they stay"} in the channel (a publish removes nothing).` : ""; + // A channel about to be made under X's own words for the page (review 1 S5). + const named = + r.creates && r.titleFrom === "page" + ? ` The topic is named by X's page: "${r.topic.title}" — the channel ${would ? "would carry" : "carries"} that name. ` + + (would ? `Rename the topic first to publish under your own name; "channel" names another slug than "${r.channel}".` : "A rename of the channel is its own step.") + : ""; const copies = r.files > 0 ? " The files are copies: the library keeps its own." : ""; const site = r.creates && !would && r.sites.length === 0 ? " Adding the channel to a site is a separate step." : ""; const waits = r.inFlight ? " A read or a capture of this library is queued or running: the publish waits for it." : ""; - return `${head}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; + return `${head}${named}${sites}${moved}${text}${bad}${gone}${copies}${site}${waits}`; } // ── the plan ─────────────────────────────────────────────────────────────── @@ -655,11 +668,13 @@ export async function publishXTrendingTopic( const look = async () => plan(paths, { library: ask.slug, libRoot, topicId: topic.id, channel, record: (await readXTrendingPublished(libRoot))[topic.id], digests }); const digest = (p: Plan) => xTrendingPublishConfirm({ library: ask.slug, topic: topic.id, channel, ids: p.fresh.map((x) => x.id), files: p.files.map((f) => `${f.id}/${f.name}`), sites: p.sites }); + const titleFrom = xTrendingTitleFrom(topic); const answer = (p: Plan, dryRun: boolean, inFlight: boolean): PublishXTrendingResult => { const r: Omit<PublishXTrendingResult, "sentence"> = { dryRun, library: ask.slug, topic: { id: topic.id, title: topic.title }, + ...(titleFrom ? { titleFrom } : {}), channel, creates: p.creates, sites: p.sites, diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -616,30 +616,30 @@ test("the real shape: a read with no topic named makes one called by the page's const paths = corpus("real-read"); const all = real.realCaptureResponses(); // The real read's order: the page's answers on load, one continuation per scroll. - const { result } = await run(paths, { load: all.slice(0, 6), scrolls: all.slice(6).map((r) => [r]) }, { url: real.REAL_TREND_URL }); + const { result } = await run(paths, { load: all.slice(0, 6), scrolls: all.slice(6).map((r) => [r]) }, { url: real.INVENTED_TREND_URL }); assert.equal(result.outcome, "read"); assert.deepEqual(result.posts, { onPage: 6, added: 6 }); - assert.deepEqual(result.topic, { id: `t-${real.REAL_TREND_ID}`, title: real.REAL_TITLE, created: true }); + assert.deepEqual(result.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: true }); assert.deepEqual(result.tabs, [{ tab: "Top", posts: 6 }]); assert.equal( result.sentence, - `Read ${real.REAL_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.REAL_TITLE}" (t-${real.REAL_TREND_ID}), shown by the page's "Top" tab.`, + `Read ${real.INVENTED_TREND_URL}: 6 posts on the page, 6 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), shown by the page's "Top" tab.`, ); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); // read.json: names, labels and sizes — no timeline id, no summary, no post. const recordText = readFileSync(path.join(root(paths), "trending", "reads", READ_1, "read.json"), "utf8"); - for (const never of [real.REAL_TOP_TIMELINE, real.REAL_LATEST_TIMELINE, real.REAL_SUMMARY, "festival opens today", "teapot_news", real.realBottomCursor(1)]) { + for (const never of [real.INVENTED_TOP_TIMELINE, real.INVENTED_LATEST_TIMELINE, real.INVENTED_SUMMARY, "festival opens today", "teapot_news", real.realBottomCursor(1)]) { assert.ok(!recordText.includes(never), `read.json carries no "${never}"`); } const listing = await listXTrending(root(paths)); assert.deepEqual(listing.topics[0].sources, [ { - trendId: real.REAL_TREND_ID, - url: real.REAL_TREND_URL, - title: real.REAL_TITLE, - summary: real.REAL_SUMMARY, - lastUpdatedAt: new Date(real.REAL_LAST_UPDATED_MS).toISOString(), + trendId: real.INVENTED_TREND_ID, + url: real.INVENTED_TREND_URL, + title: real.INVENTED_TITLE, + summary: real.INVENTED_SUMMARY, + lastUpdatedAt: new Date(real.INVENTED_LAST_UPDATED_MS).toISOString(), tabs: ["Top", "Latest"], lastReadTab: "Top", reads: 1, @@ -655,7 +655,7 @@ test("the real shape: a library read before titles were parsed is put right by a const real = await import("../social/__fixtures__/xTrendingRealShape"); const { renameXTrendingTopic } = await import("../lib/xTrending/organise"); const all = real.realCaptureResponses(); - const fallback = `Trending ${real.REAL_TREND_ID}`; + const fallback = `Trending ${real.INVENTED_TREND_ID}`; const topicsFile = (paths: Paths) => path.join(root(paths), "trending", "topics.json"); const membersFile = (paths: Paths) => path.join(root(paths), "trending", "membership.json"); // What slice 1 left of such a read: the fallback name, a source with no words, sightings with no tab. @@ -676,40 +676,40 @@ test("the real shape: a library read before titles were parsed is put right by a }; const paths = corpus("real-reparse"); - await run(paths, { load: all, scrolls: [] }, { url: real.REAL_TREND_URL }); + await run(paths, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); asSlice1Left(paths); const done = await reparse(paths); assert.equal(done.ok, true); assert.deepEqual(done.posts, { onPage: 6, added: 0 }); - assert.deepEqual(done.topic, { id: `t-${real.REAL_TREND_ID}`, title: real.REAL_TITLE, created: false, renamed: { was: fallback } }); + assert.deepEqual(done.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE, created: false, renamed: { was: fallback } }); assert.equal( done.sentence, - `Parsed ${READ_1} again (${real.REAL_TREND_URL}): 6 posts in the capture, 0 new, in topic "${real.REAL_TITLE}" (t-${real.REAL_TREND_ID}), ` + + `Parsed ${READ_1} again (${real.INVENTED_TREND_URL}): 6 posts in the capture, 0 new, in topic "${real.INVENTED_TITLE}" (t-${real.INVENTED_TREND_ID}), ` + `shown by the page's "Top" tab. X was asked nothing. The topic was "${fallback}" until now: it took the page's title.`, ); const topic = JSON.parse(readFileSync(topicsFile(paths), "utf8")).topics[0]; - assert.equal(topic.title, real.REAL_TITLE); - assert.equal(topic.sources[0].summary, real.REAL_SUMMARY); + assert.equal(topic.title, real.INVENTED_TITLE); + assert.equal(topic.sources[0].summary, real.INVENTED_SUMMARY); assert.equal(topic.sources[0].reads[0].tab, "Top"); const members = JSON.parse(readFileSync(membersFile(paths), "utf8")).posts as Record<string, { seen: Array<{ tab?: string }> }>; assert.ok(Object.values(members).every((m) => m.seen.length === 1 && m.seen[0].tab === "Top")); const record = await readXTrendingReadRecord(root(paths), READ_1); assert.deepEqual(record?.tabs, [{ tab: "Top", posts: 6 }]); - assert.deepEqual(record?.topic, { id: `t-${real.REAL_TREND_ID}`, title: real.REAL_TITLE }); + assert.deepEqual(record?.topic, { id: `t-${real.INVENTED_TREND_ID}`, title: real.INVENTED_TITLE }); // A second reparse renames nothing and says nothing of a rename. assert.doesNotMatch((await reparse(paths)).sentence, /until now/); // The operator (or an agent) renamed the topic first: the reparse fills X's words on the source and leaves the name. const named = corpus("real-reparse-named"); - await run(named, { load: all, scrolls: [] }, { url: real.REAL_TREND_URL }); + await run(named, { load: all, scrolls: [] }, { url: real.INVENTED_TREND_URL }); asSlice1Left(named); - assert.equal((await renameXTrendingTopic(root(named), { topic: `t-${real.REAL_TREND_ID}`, title: "Kettles, my pick", by: "operator", readInFlight: () => false })).ok, true); + assert.equal((await renameXTrendingTopic(root(named), { topic: `t-${real.INVENTED_TREND_ID}`, title: "Kettles, my pick", by: "operator", readInFlight: () => false })).ok, true); const kept = await reparse(named); assert.equal(kept.topic?.title, "Kettles, my pick"); assert.equal(kept.topic?.renamed, undefined); const after = JSON.parse(readFileSync(topicsFile(named), "utf8")).topics[0]; assert.equal(after.title, "Kettles, my pick"); - assert.equal(after.sources[0].title, real.REAL_TITLE); + assert.equal(after.sources[0].title, real.INVENTED_TITLE); }); test("the real shape: gone from the page is said after a read whose bottom continuation (cursors in TimelineReplaceEntry) brought nothing new, and never after a capped or failed one", async () => { @@ -718,21 +718,42 @@ test("the real shape: gone from the page is said after a read whose bottom conti // First read: the three posts of the first page and the two of the second. const seed = async (name: string) => { const paths = corpus(name); - await run(paths, { load: [...base, real.realContinuation(real.REAL_SECOND, { n: 2 })], scrolls: [] }, { url: real.REAL_TREND_URL }); + await run(paths, { load: [...base, real.realContinuation(real.INVENTED_SECOND, { n: 2 })], scrolls: [] }, { url: real.INVENTED_TREND_URL }); return paths; }; const second = (paths: Paths, scrolls: FakeTrendingPage["scrolls"]) => - run(paths, { load: base, scrolls }, { url: real.REAL_TREND_URL }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); + run(paths, { load: base, scrolls }, { url: real.INVENTED_TREND_URL }, { readId: READ_2, at: "2026-11-17T12:00:00.000Z" }); // To the end: the continuation from the first answer's bottom cursor brings one post, the one after it none. - const ended = await second(await seed("real-gone-end"), [[real.realContinuation([real.REAL_SECOND[0]], { n: 2 })], [real.realContinuation([], { n: 3 })], []]); + const ended = await second(await seed("real-gone-end"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [real.realContinuation([], { n: 3 })], []]); assert.equal(ended.result.stop, "idle"); assert.deepEqual(ended.result.gone, ["1900000000000003005"]); // Capped (the scroll cap, with posts still arriving): nothing. - const capped = await second(await seed("real-gone-capped"), [[real.realContinuation([real.REAL_SECOND[0]], { n: 2 })]]); + const capped = await second(await seed("real-gone-capped"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })]]); assert.equal(capped.result.gone, undefined); // The last answer failed: nothing. const last = real.realContinuation([], { n: 3 }); - const failed = await second(await seed("real-gone-failed"), [[real.realContinuation([real.REAL_SECOND[0]], { n: 2 })], [{ url: last.url, status: 500, text: "upstream error" }], []]); + const failed = await second(await seed("real-gone-failed"), [[real.realContinuation([real.INVENTED_SECOND[0]], { n: 2 })], [{ url: last.url, status: 500, text: "upstream error" }], []]); assert.equal(failed.result.stop, "idle"); assert.equal(failed.result.gone, undefined); }); + +// Review 1 S3. +test("S3: a post first seen in an answer that named no timeline does not drop the read's tab; it inherits the one named tab", async () => { + const real = await import("../social/__fixtures__/xTrendingRealShape"); + const { readTabOf } = await import("./readXTrending"); + assert.equal(readTabOf([{ tab: "Top" }, {}]), "Top"); + assert.equal(readTabOf([{ tab: "Top" }, { tab: "Latest" }, {}]), undefined); + assert.equal(readTabOf([{}]), undefined); + assert.equal(readTabOf([]), undefined); + const paths = corpus("s3-untagged"); + // One more answer listing a post, whose request names no timeline at all. + const stray = { url: "https://x.com/i/api/graphql/q/ExampleTrendTimeline?variables=%7B%7D", status: 200, body: fixtureTimelineBody([{ id: "1900000000000003099", handle: "stray_post", text: "Listed by an answer that names no timeline." }]) }; + const { result } = await run(paths, { load: [...real.realCaptureResponses({ later: [] }), stray], scrolls: [] }, { url: real.INVENTED_TREND_URL }); + assert.deepEqual(result.tabs, [{ tab: "Top", posts: 3 }, { posts: 1 }]); + assert.match(result.sentence, /shown by the page's "Top" tab\.$/); + const topic = JSON.parse(readFileSync(path.join(root(paths), "trending", "topics.json"), "utf8")).topics[0]; + assert.equal(topic.sources[0].reads[0].tab, "Top"); + const members = JSON.parse(readFileSync(path.join(root(paths), "trending", "membership.json"), "utf8")).posts; + assert.equal(members["1900000000000003099"].seen[0].tab, "Top"); + assert.equal(members["1900000000000003001"].seen[0].tab, "Top"); +}); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -330,6 +330,12 @@ type Ingested = { tabs?: Array<{ tab?: string; posts: number }>; }; +// The tab a capture's posts are the page's, when its timelines name exactly one. +export function readTabOf(timelines: ReadonlyArray<{ tab?: string }>): string | undefined { + const named = [...new Set(timelines.map((t) => t.tab).filter((t): t is string => Boolean(t)))]; + return named.length === 1 ? named[0] : undefined; +} + // `, shown by the page's "Top" tab` — what a read saw, in a sentence; "" when the // capture does not say. function tabText(tabs: Ingested["tabs"]): string { @@ -367,8 +373,10 @@ async function ingestCapture(o: { onPage: parsed.posts.length, ...(tabs.length ? { tabs } : {}), }; - // The ONE tab this capture lists, when it lists one and the page names it. - const tab = parsed.timelines.length === 1 ? parsed.timelines[0].tab : undefined; + // The ONE tab this capture names (review 1 S3): a post first seen in an + // answer whose request named no timeline does not drop the read's tab — it + // inherits it (store.ts), and only when exactly one tab was named. + const tab = readTabOf(parsed.timelines); if (!o.write || parsed.posts.length === 0) return { ...base, added: 0 }; const had = await readXTrendingPostIds(o.channelRoot); const newIds = parsed.posts.map((p) => p.id).filter((id) => !had.has(id)); diff --git a/common/lib/xTrending/organise.ts b/common/lib/xTrending/organise.ts @@ -123,6 +123,9 @@ export async function renameXTrendingTopic( } topic.title = title; topic.organised = { what: "rename", by: ask.by, at }; + // Its own field: a merge into this topic overwrites `organised`, and a + // read must still know the name was set. + topic.titleFrom = "rename"; return { write: true, result: { ok: true, op: "rename", topic: topic.id, title, was, changed: true, sentence: `Topic "${was}" is now "${title}". Its id stays ${topic.id}: its watch, its posts and their judgements are untouched.` }, @@ -198,7 +201,7 @@ export async function moveXTrendingPosts( const base = topicIdFromTitle(title) || "topic"; let id = base; for (let k = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); k++) id = `${base}-${k}`; - target = { id, title, createdAt: at, sources: [] }; + target = { id, title, createdAt: at, sources: [], titleFrom: "ask" }; topics.push(target); created = true; // THE TOPIC FIRST, THEN THE POSTS (review 1 S6): cut between the two diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -651,3 +651,94 @@ test("gone from the page is said per tab: a post only the other tab showed is no const unknown = await recordXTrendingRead(dir, { readId: "tr-01JE0000000000000000000000", at: at(13), ref: REF, topic: "T", postIds: ["701"], added: 0, complete: true }); assert.deepEqual(unknown.gone, ["703"]); }); + +// ── review 1: S4 and the set-name field ──────────────────────────────────── + +test("S4: an older read parsed again never names a topic by a title older than the one its source holds", async () => { + const { renameXTrendingTopic } = await import("./organise"); + const dir = root("s4-age"); + const fallback = `Trending ${REF.trendId}`; + // Another topic answers to the noon title, so the page's topic keeps its fallback at the noon read… + await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T08:00:00.000Z", ref: REF_2, topic: "Noon headline", postIds: ["201"], added: 1 }); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }); + const noon = await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T12:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Noon headline" } }); + assert.equal(noon.topic.title, fallback); + // …then that other topic is renamed away, and the MORNING read is parsed again: its title is older than the source's. + assert.equal((await renameXTrendingTopic(dir, { topic: "noon-headline", title: "Something else", by: "operator", readInFlight: () => false })).ok, true); + const morning = await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: { title: "Morning headline", summary: "Morning." } }); + assert.deepEqual(morning.topic.renamed, { was: fallback }); + assert.equal(morning.topic.title, "Noon headline"); + const topic = (await readXTrendingTopics(dir)).find((t) => t.id === `t-${REF.trendId}`)!; + assert.equal(topic.title, "Noon headline"); + assert.equal(topic.titleFrom, "page"); + assert.equal(topic.sources[0].title, "Noon headline"); + // What the source did not have yet is taken even from the older read: there is nothing newer to keep. + assert.equal(topic.sources[0].summary, "Morning."); +}); + +test("a name that was SET is recorded in a field no merge or move writes, and a read never changes it afterwards", async () => { + const { mergeXTrendingTopics, moveXTrendingPosts, renameXTrendingTopic } = await import("./organise"); + const { xTrendingTitleFrom, xTrendingTopicNameIsSet } = await import("./store"); + const IDLE = () => false; + const fallback = `Trending ${REF.trendId}`; + const first = { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1 }; + const later = { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, postIds: ["101"], added: 0, page: PAGE }; + const topicOf = async (dir: string, id = `t-${REF.trendId}`) => (await readXTrendingTopics(dir)).find((t) => t.id === id)!; + + // A name ASKED FOR that is literally the fallback's words is a set name. + const asked = root("set-asked-fallback"); + const made = await recordXTrendingRead(asked, { ...first, topic: fallback }); + assert.equal((await topicOf(asked, made.topic.id)).titleFrom, "ask"); + assert.equal((await recordXTrendingRead(asked, { ...later, topic: made.topic.id })).topic.title, fallback); + + // Renamed, then MERGED INTO (which overwrites `organised`): still a set name. + const merged = root("set-rename-then-merge"); + await recordXTrendingRead(merged, first); + await recordXTrendingRead(merged, { readId: READ_C, at: "2026-11-17T09:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["201"], added: 1 }); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback + " ", by: "agent", readInFlight: IDLE })).ok, true); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: "Kettles", by: "agent", readInFlight: IDLE })).ok, true); + assert.equal((await renameXTrendingTopic(merged, { topic: `t-${REF.trendId}`, title: fallback, by: "agent", readInFlight: IDLE })).ok, true); + const m = await mergeXTrendingTopics(merged, { into: `t-${REF.trendId}`, from: ["cups"], by: "operator", readInFlight: IDLE }); + assert.equal(m.ok, true, m.ok ? "" : m.error); + const after = await topicOf(merged); + assert.equal(after.organised?.what, "merge"); + assert.equal(after.titleFrom, "rename"); + assert.equal(xTrendingTopicNameIsSet(after), true); + assert.equal((await recordXTrendingRead(merged, later)).topic.title, fallback); + + // A topic made by a move, under the name given, is a set name too. + const moved = root("set-move"); + await recordXTrendingRead(moved, first); + const mv = await moveXTrendingPosts(moved, { ids: ["101"], to: "Picked", create: true, by: "agent" }); + assert.equal(mv.ok, true, mv.ok ? "" : mv.error); + assert.equal((await readXTrendingTopics(moved)).find((t) => t.title === "Picked")?.titleFrom, "ask"); + + // A topic that took its page's title says so, and is not "set". + const page = root("set-page"); + await recordXTrendingRead(page, { ...first, page: PAGE }); + assert.equal((await topicOf(page)).titleFrom, "page"); + assert.equal(xTrendingTopicNameIsSet(await topicOf(page)), false); + // Topics from before the field: a rename as the last organise step, a name that is no fallback (asked), a fallback. + const legacy = (title: string, organised?: { what: "rename" | "merge"; by: "agent"; at: string }) => ({ title, sources: [{ trendId: REF.trendId, url: REF.url, reads: [] }], ...(organised ? { organised } : {}) }); + assert.equal(xTrendingTitleFrom(legacy("Kettles")), "ask"); + assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "rename", by: "agent", at: "x" })), "rename"); + assert.equal(xTrendingTitleFrom(legacy(fallback)), undefined); + assert.equal(xTrendingTitleFrom(legacy(fallback, { what: "merge", by: "agent", at: "x" })), undefined); +}); + +test("a listing gives at most 600 characters of X's summary, cut at a word; the source keeps all of it", async () => { + const { listedXTrendingSummary, X_TRENDING_SUMMARY_LIST_MAX } = await import("./store"); + assert.equal(X_TRENDING_SUMMARY_LIST_MAX, 600); + const dir = root("summary-cap"); + const summary = Array.from({ length: 150 }, (_, i) => `word${i}`).join(" "); + assert.ok(summary.length > 900); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, postIds: ["101"], added: 1, page: { title: "T", summary } }); + assert.equal((await readXTrendingTopics(dir))[0].sources[0].summary, summary); + const listed = (await listXTrending(dir)).topics[0].sources[0].summary!; + assert.ok(listed.length <= 600, String(listed.length)); + assert.match(listed, /^word0 word1 .* word\d+…$/); + assert.ok(summary.startsWith(listed.slice(0, -1))); + // A short one is given whole; one unbroken run is cut hard. + assert.equal(listedXTrendingSummary("Short."), "Short."); + assert.equal(listedXTrendingSummary("x".repeat(700)).length, 600); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -361,8 +361,33 @@ export type XTrendingTopic = { aliases?: string[]; // Its last rename or merge. organised?: XTrendingOrganised; + // WHERE ITS NAME CAME FROM, in a field of its own that no merge or move + // writes (review 1): "ask" — a read was asked to make it under that name; + // "rename" — somebody renamed it; "page" — nobody named it and it took its + // trending page's title. Absent: the fallback name, or a topic from before + // this field (xTrendingTitleFrom reads those). A name that was SET ("ask", + // "rename") is never changed by a read. + titleFrom?: XTrendingTitleFrom; }; +export type XTrendingTitleFrom = "page" | "ask" | "rename"; + +// Whether somebody set the topic's name. A topic from before `titleFrom`: a +// rename is its last organise step, or its name is not a fallback name (it was +// asked for: no read gave a topic a page's title then). +export function xTrendingTopicNameIsSet(t: Pick<XTrendingTopic, "title" | "titleFrom" | "organised" | "sources">): boolean { + const from = xTrendingTitleFrom(t); + return from === "ask" || from === "rename"; +} + +// Where a topic's name came from; undefined for the fallback name. +export function xTrendingTitleFrom(t: Pick<XTrendingTopic, "title" | "titleFrom" | "organised" | "sources">): XTrendingTitleFrom | undefined { + if (t.titleFrom) return t.titleFrom; + if (t.organised?.what === "rename") return "rename"; + if (/^Trending \d+$/.test(t.title) && (t.sources.length === 0 || t.sources.some((s) => t.title === xTrendingFallbackTitle(s.trendId)))) return undefined; + return "ask"; +} + // One sighting: the read, the page, when, its rank on the page, and the tab // of the page that showed it (as XTrendingSourceRead.tab). export type XTrendingSeen = { read: string; trendId: string; at: string; rank: number; tab?: string }; @@ -434,6 +459,7 @@ function parseTopics(raw: unknown): XTrendingTopic[] { sources, ...(aliases.length ? { aliases: [...new Set<string>(aliases)] } : {}), ...(organised ? { organised } : {}), + ...(t.titleFrom === "page" || t.titleFrom === "ask" || t.titleFrom === "rename" ? { titleFrom: t.titleFrom } : {}), }); } return out; @@ -625,8 +651,9 @@ function pageTitleAsName(title: string | undefined): string | undefined { // <number>". A topic STILL CARRYING THAT FALLBACK for this page takes the // page's title in any later pass that finds one — a read or a reparse. A // topic somebody named is never renamed by a read: one made with a name -// asked for, and one renamed since (`organised.what === "rename"`, by the -// operator or an agent — even back to the fallback's words). A title another +// asked for, and one renamed since (`titleFrom`, a field no merge or move +// writes; by the operator or an agent — even back to the fallback's words, and +// even when the name asked for IS the fallback's words). A title another // topic already answers to is not taken (a topic's name is its own): the // fallback stays, and the source carries X's title all the same. export async function recordXTrendingRead(channelRoot: string, input: RecordReadInput): Promise<RecordReadResult> { @@ -643,27 +670,16 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead let created = false; let renamed: { was: string } | undefined; const fallback = xTrendingFallbackTitle(input.ref.trendId); - const pageName = pageTitleAsName(input.page?.title); - // The page's title as a name, unless another topic answers to it. - const freeName = (self?: XTrendingTopic) => - pageName && !resolveXTrendingTopic(topics.filter((t) => t !== self), pageName) ? pageName : undefined; if (!found) { - const title = asked || freeName() || fallback; const base = (asked && topicIdFromTitle(asked)) || `t-${input.ref.trendId}`; let id = base; // Never the id of a topic merged away: that id means the topic it went into. for (let n = 2; topics.some((t) => t.id === id || t.aliases?.includes(id)); n++) id = `${base}-${n}`; - found = { id, title, createdAt: input.at, sources: [] }; + // A name asked for is a SET name, whatever its words ("Trending <number>" included). + found = { id, title: asked || fallback, createdAt: input.at, sources: [], ...(asked ? { titleFrom: "ask" as const } : {}) }; topics.push(found); created = true; } - else if (found.title === fallback && found.organised?.what !== "rename") { - const name = freeName(found); - if (name && name !== found.title) { - renamed = { was: found.title }; - found.title = name; - } - } let source = found.sources.find((s) => s.trendId === input.ref.trendId); if (!source) { source = { trendId: input.ref.trendId, url: input.ref.url, reads: [] }; @@ -671,15 +687,31 @@ export async function recordXTrendingRead(channelRoot: string, input: RecordRead } // X's own words for the page and its tabs, as THIS capture has them — only // from a pass no older than the source's latest read (a reparse of an old - // read does not put old words over newer ones). + // read does not put old words over newer ones), or where the source has + // none yet (there is nothing newer to keep). const newest = source.reads.reduce((a, r) => (r.at > a ? r.at : a), ""); - if (input.page && input.at >= newest) { + if (input.page) { + const current = input.at >= newest; const title = input.page.title?.replace(/\s+/g, " ").trim(); const summary = input.page.summary?.replace(/\s+/g, " ").trim(); - if (title) source.title = title; - if (summary) source.summary = summary; - if (input.page.lastUpdatedAt) source.lastUpdatedAt = input.page.lastUpdatedAt; - if (input.page.tabs?.length) source.tabs = input.page.tabs.map((t) => ({ label: t.label, timelineId: t.timelineId })); + if (title && (current || !source.title)) source.title = title; + if (summary && (current || !source.summary)) source.summary = summary; + if (input.page.lastUpdatedAt && (current || !source.lastUpdatedAt)) source.lastUpdatedAt = input.page.lastUpdatedAt; + if (input.page.tabs?.length && (current || !source.tabs?.length)) { + source.tabs = input.page.tabs.map((t) => ({ label: t.label, timelineId: t.timelineId })); + } + } + // THE NAME, from what the SOURCE now holds (review 1 S4): the same age + // guard as the words above, so an older read parsed again never names a + // topic by a title older than the one the source already has. + if (!xTrendingTopicNameIsSet(found) && found.title === fallback) { + const name = pageTitleAsName(source.title); + // Unless another topic answers to it: a topic's name is its own. + if (name && name !== found.title && !resolveXTrendingTopic(topics.filter((t) => t !== found), name)) { + if (!created) renamed = { was: found.title }; + found.title = name; + found.titleFrom = "page"; + } } const read = source.reads.find((r) => r.id === input.readId); if (!read) { @@ -1040,6 +1072,18 @@ export async function listXTrendingReadIds(channelRoot: string): Promise<string[ } } +// X'S SUMMARY, AS A LISTING GIVES IT (review 1): the whole text is kept on the +// source (topics.json); a listing — the channel page, `get trending`, the MCP, +// umtool — gives at most this much, cut at a word with an ellipsis. X writes +// these, and they are other people's words inside a list of topics. +export const X_TRENDING_SUMMARY_LIST_MAX = 600; +export function listedXTrendingSummary(summary: string, max: number = X_TRENDING_SUMMARY_LIST_MAX): string { + if (summary.length <= max) return summary; + const cut = summary.slice(0, max - 1); + const word = cut.lastIndexOf(" "); + return `${(word > max * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; +} + // The tab the source's latest read saw, when that read says. function lastReadTabOf(s: XTrendingSource): string | undefined { return s.reads.reduce<XTrendingSourceRead | undefined>((a, r) => (a === undefined || r.at > a.at ? r : a), undefined)?.tab; @@ -1176,7 +1220,7 @@ export async function listXTrending( trendId: s.trendId, url: s.url, ...(s.title ? { title: s.title } : {}), - ...(s.summary ? { summary: s.summary } : {}), + ...(s.summary ? { summary: listedXTrendingSummary(s.summary) } : {}), ...(s.lastUpdatedAt ? { lastUpdatedAt: s.lastUpdatedAt } : {}), ...(s.tabs?.length ? { tabs: s.tabs.map((t) => t.label) } : {}), ...(lastReadTabOf(s) ? { lastReadTab: lastReadTabOf(s)! } : {}), diff --git a/common/social/__fixtures__/xTrendingRealShape.ts b/common/social/__fixtures__/xTrendingRealShape.ts @@ -34,16 +34,18 @@ import { fixtureTweetResult, type FixtureResponse, type FixtureTweet } from "./xTrendingCapture"; -export const REAL_TREND_ID = "1900000000000000002"; -export const REAL_TREND_URL = `https://x.com/i/trending/${REAL_TREND_ID}`; +export const INVENTED_TREND_ID = "1900000000000000002"; +export const INVENTED_TREND_URL = `https://x.com/i/trending/${INVENTED_TREND_ID}`; +// The two operation names are X's own (they are in every such page's +// requests); everything named INVENTED_ below is made up. export const REAL_PAGE_OP = "AiTrendByRestId"; export const REAL_TIMELINE_OP = "GenericTimelineById"; -export const REAL_TITLE = "Kettle festival opens with a record queue"; -export const REAL_SUMMARY = +export const INVENTED_TITLE = "Kettle festival opens with a record queue"; +export const INVENTED_SUMMARY = "The annual kettle festival opened this morning. Visitors queued from dawn, and the organisers added a second hall for the afternoon demonstrations."; -export const REAL_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); -export const REAL_TOP_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS10b3A="; -export const REAL_LATEST_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS1sYXRlc3Q="; +export const INVENTED_LAST_UPDATED_MS = Date.UTC(2026, 10, 16, 11, 30, 0); +export const INVENTED_TOP_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS10b3A="; +export const INVENTED_LATEST_TIMELINE = "VGltZWxpbmU6Zml4dHVyZS1sYXRlc3Q="; const url = (op: string, variables: Record<string, unknown>) => `https://x.com/i/api/graphql/fixtureQueryId/${op}?variables=${encodeURIComponent(JSON.stringify(variables))}&features=${encodeURIComponent("{}")}`; @@ -58,10 +60,10 @@ export type RealPage = { // The page's own answer. export function realPageBody(o: RealPage = {}): Record<string, unknown> { - const trendId = o.trendId ?? REAL_TREND_ID; + const trendId = o.trendId ?? INVENTED_TREND_ID; const tabs = o.tabs ?? [ - { label: "Top", timelineId: REAL_TOP_TIMELINE }, - { label: "Latest", timelineId: REAL_LATEST_TIMELINE }, + { label: "Top", timelineId: INVENTED_TOP_TIMELINE }, + { label: "Latest", timelineId: INVENTED_LATEST_TIMELINE }, ]; return { data: { @@ -71,12 +73,12 @@ export function realPageBody(o: RealPage = {}): Record<string, unknown> { contexts: { topics: ["Food and drink"] }, page: { article: { - article_text: { entities: [], text: o.summary ?? REAL_SUMMARY }, - title: o.title ?? REAL_TITLE, + article_text: { entities: [], text: o.summary ?? INVENTED_SUMMARY }, + title: o.title ?? INVENTED_TITLE, }, available_actions: [], disclaimer: "This story is a summary of posts and may evolve over time.", - last_updated_at_ms: o.lastUpdatedAtMs ?? REAL_LAST_UPDATED_MS, + last_updated_at_ms: o.lastUpdatedAtMs ?? INVENTED_LAST_UPDATED_MS, post_timelines: tabs.map((t) => ({ label: t.label, post_timeline: { id: t.timelineId } })), }, rest_id: trendId, @@ -88,7 +90,7 @@ export function realPageBody(o: RealPage = {}): Record<string, unknown> { export function realPageAnswer(o: RealPage = {}): FixtureResponse { return { - url: url(REAL_PAGE_OP, { trendId: o.trendId ?? REAL_TREND_ID, includePromotedContent: false, withBirdwatchNotes: true, withVoice: true, withCommunity: true }), + url: url(REAL_PAGE_OP, { trendId: o.trendId ?? INVENTED_TREND_ID, includePromotedContent: false, withBirdwatchNotes: true, withVoice: true, withCommunity: true }), status: 200, body: realPageBody(o), }; @@ -158,7 +160,7 @@ export const realTopCursor = (n: number) => `fixture-top-cursor-${n}`; // A tab's FIRST answer: no cursor in the request; the cursors are entries. export function realFirstPage(tweets: FixtureTweet[], o: { timelineId?: string; bottom?: string } = {}): FixtureResponse { return { - url: url(REAL_TIMELINE_OP, { timelineId: o.timelineId ?? REAL_TOP_TIMELINE, count: 20, withQuickPromoteEligibilityTweetFields: true }), + url: url(REAL_TIMELINE_OP, { timelineId: o.timelineId ?? INVENTED_TOP_TIMELINE, count: 20, withQuickPromoteEligibilityTweetFields: true }), status: 200, body: timelineBody([ { type: "TimelineClearCache" }, @@ -186,7 +188,7 @@ export function realContinuation( const n = o.n ?? 2; return { url: url(REAL_TIMELINE_OP, { - timelineId: o.timelineId ?? REAL_TOP_TIMELINE, + timelineId: o.timelineId ?? INVENTED_TOP_TIMELINE, count: 20, cursor: o.asked ?? realBottomCursor(n - 1), withQuickPromoteEligibilityTweetFields: true, @@ -202,7 +204,7 @@ export function realContinuation( // The accounts the page names, under the page's own `data` key: a timeline // with instructions and no post. -export function realRelevantUsers(trendId: string = REAL_TREND_ID): FixtureResponse { +export function realRelevantUsers(trendId: string = INVENTED_TREND_ID): FixtureResponse { return { url: url("TrendRelevantUsers", { trendId }), status: 200, @@ -224,7 +226,7 @@ export function realStoryTopics(): FixtureResponse { id: `trend-${id}`, result: { __typename: "Trend", - core: { category: "Food and drink", created_at_ms: REAL_LAST_UPDATED_MS, hook: "An invented hook.", name }, + core: { category: "Food and drink", created_at_ms: INVENTED_LAST_UPDATED_MS, hook: "An invented hook.", name }, id: `trend-${id}`, post_count: "1.2K", rest_id: id, @@ -241,7 +243,7 @@ export function realStoryTopics(): FixtureResponse { const small = (op: string, body: unknown): FixtureResponse => ({ url: url(op, {}), status: 200, body }); -export const REAL_FIRST: FixtureTweet[] = [ +export const INVENTED_FIRST: FixtureTweet[] = [ { id: "1900000000000003001", handle: "teapot_news", name: "Teapot News", text: "The kettle festival opens today.", media: ["photo"] }, { id: "1900000000000003002", @@ -251,11 +253,11 @@ export const REAL_FIRST: FixtureTweet[] = [ }, { id: "1900000000000003003", handle: "spout_clips", name: "Spout Clips", text: "Video from the opening.", media: ["video"], namesInCore: true }, ]; -export const REAL_SECOND: FixtureTweet[] = [ +export const INVENTED_SECOND: FixtureTweet[] = [ { id: "1900000000000003004", handle: "lid_watch", text: "The queue at noon.", media: ["animated_gif"] }, { id: "1900000000000003005", handle: "kettle_org", text: "A second hall is open." }, ]; -export const REAL_THIRD: FixtureTweet[] = [ +export const INVENTED_THIRD: FixtureTweet[] = [ { id: "1900000000000003006", handle: "teapot_news", name: "Teapot News", text: "Afternoon demonstrations begin." }, ]; @@ -263,13 +265,13 @@ export const REAL_THIRD: FixtureTweet[] = [ // the page, its accounts, its story, the first page of the default tab, then // one continuation per scroll (`later`: the posts each brought). export function realCaptureResponses(o: { page?: RealPage; first?: FixtureTweet[]; later?: FixtureTweet[][] } = {}): FixtureResponse[] { - const later = o.later ?? [REAL_SECOND, REAL_THIRD]; + const later = o.later ?? [INVENTED_SECOND, INVENTED_THIRD]; return [ small("DataSaverMode", { data: { viewer: { data_saver_mode: false } } }), realPageAnswer(o.page), realRelevantUsers(o.page?.trendId), realStoryTopics(), - realFirstPage(o.first ?? REAL_FIRST), + realFirstPage(o.first ?? INVENTED_FIRST), small("ViewerBadgeCounts", { data: { viewer_v2: { badge_counts: { ntab_unread_count: 0 } } } }), ...later.map((tweets, i) => realContinuation(tweets, { n: i + 2 })), ]; diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -594,3 +594,26 @@ test("stream: a resumed backfill whose first posts are the timeline's newest res sync.pushStdout(jsonl(501)); assert.equal(sync.restartedFromTop, false); }); + +// Review 1 S1: the newest archived id is over the whole corpus (a deleted newest post, or a newer +// post imported from elsewhere, hides a restart). A search-phase place says exactly what may follow it. +test("stream: after a search-phase place `3_<N>/`, a first-page post above N means the place was not honoured", async () => { + const { resumePointCeiling, TOP_RESTART_WINDOW } = await import("./xGalleryDlFetcher"); + assert.equal(resumePointCeiling("3_1899000000000000300/"), 1899000000000000300n); + assert.equal(resumePointCeiling("3_1899000000000000300/API-CURSOR"), 1899000000000000300n); + assert.equal(resumePointCeiling("2_1899000000000000300/"), 1899000000000000300n); + // The timeline phase's places say nothing of ids. + assert.equal(resumePointCeiling("1/API-CURSOR"), null); + assert.equal(resumePointCeiling("1/"), null); + assert.equal(resumePointCeiling(undefined), null); + const after = (ns: number[]) => { + const s = newStream({ stopAtKnown: false, resumeCeiling: 1899000000000000300n }); + for (const n of ns) s.pushStdout(jsonl(n)); + return s.resumeNotHonoured; + }; + assert.equal(after([300, 299, 298]), false); + assert.equal(after([301]), true); + // Far below the archive's newest, and still above the place: caught, where the top check is blind. + assert.equal(after([299, 350]), true); + assert.equal(after([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 300 - i), 301]), false); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -621,6 +621,41 @@ export const X_BACKFILL_RESTARTED_FROM_TOP = 'walked again. Run Resume backfill again; if it says this twice, fetch-posts {"older": true} walks down from the ' + "oldest archived post instead."; +// A SEARCH-PHASE PLACE SAYS WHAT MAY FOLLOW IT (review 1 S1). `3_<N>/` asks +// `max_id:<N>`: every post the walk then reads is at or below N. The check +// above compares with the newest id the ARCHIVE holds, which a deleted newest +// post or a newer post imported from elsewhere moves; this one is exact. A +// first-page post above N means the place was not honoured, wherever the walk +// went instead. The timeline phase's places (`1/<API cursor>`) name no id. +export function resumePointCeiling(cursor: string | undefined): bigint | null { + const m = /^[23]_(\d+)\//.exec(cursor ?? ""); + return m ? BigInt(m[1]) : null; +} +export const X_RESUME_POINT_NOT_HONOURED = + "The walk did not continue from its saved resume point: gallery-dl read a post newer than the place it was given " + + "(a search-phase place lists only posts at or below it). Stopped at once; the resume point is kept and nothing was " + + 'walked again. Run it again; if it says this twice, fetch-posts {"older": true} walks down from the oldest ' + + "archived post instead."; + +// A TIMELINE-PHASE PLACE MAY BE AN OLD BUILD'S (review 1 S2). Before the +// search phase's marker was read, a walk that had gone on into its search +// phase saved the timeline phase's LAST cursor. Resumed, gallery-dl re-enters +// there and reads the search phase from its top: posts already archived, +// skipped one page of about twenty per request, before any new one. The place +// is not rewritten to one below the archive's oldest post: nothing in +// gallery-dl's source proves the archive is unbroken between the timeline +// phase's last post and its oldest (an older-posts walk or an imported post +// can have put the oldest there), and a rewrite would then skip what lies +// between. So the run says what it is about to do. +export const X_TIMELINE_PHASE_PLACE_NOTE = + "The saved place is in the timeline phase. If an earlier build saved it while the walk was already below what X's " + + "timeline pages back, this run first passes through posts already archived (skipped, about twenty per request) " + + "before it reaches new ones, and may spend its whole budget there; its place then moves down and the next run " + + 'continues. fetch-posts {"older": true} starts below the oldest archived post instead.'; +export function isTimelinePhasePlace(cursor: string | undefined): boolean { + return /^1\/.+/.test(cursor ?? ""); +} + // The newest of a set of post ids, as a number (X ids grow with time); null // when none is numeric. export function newestPostId(ids: Iterable<string>): bigint | null { @@ -681,6 +716,8 @@ export class GalleryDlStream { stopReached = false; // A resumed backfill whose first posts are the timeline's newest (opts.topRestartAt). restartedFromTop = false; + // A first-page post above the search-phase place the walk was given (opts.resumeCeiling). + resumeNotHonoured = false; // STOP_AFTER_KNOWN known posts in a row were met by a walk that does not stop at them. skippingKnown = false; cursor?: string; @@ -716,6 +753,9 @@ export class GalleryDlStream { // TOP_RESTART_WINDOW posts at or above it means the walk restarted from // the top (X_BACKFILL_RESTARTED_FROM_TOP). topRestartAt?: bigint; + // A walk resumed from a search-phase place: the id nothing it reads may + // exceed (resumePointCeiling). Judged on the first page, as above. + resumeCeiling?: bigint; // The account's handle, to recognise its `user` record. accountHandle?: string; onLog?: (line: string) => void; @@ -856,6 +896,14 @@ export class GalleryDlStream { ) { this.restartedFromTop = true; } + if ( + this.opts.resumeCeiling !== undefined && + this.distinct <= TOP_RESTART_WINDOW && + /^\d+$/.test(post.id) && + BigInt(post.id) > this.opts.resumeCeiling + ) { + this.resumeNotHonoured = true; + } const isKnown = this.opts.seenIds.has(post.id); const isOlder = !isKnown && Boolean(this.opts.since && post.createdAt <= this.opts.since); @@ -1404,6 +1452,9 @@ export const xGalleryDlFetcher: SocialFetcher = { // A resumed backfill given a real resume point ("1/" asks for the top). const resumedBackfill = input.resumedBackfill === true && Boolean(input.cursor) && input.cursor !== RESTART_FROM_TOP_CURSOR; const newestKnown = resumedBackfill ? newestPostId(seenIds) : null; + // Any walk resumed from a search-phase place, a sync's included. + const ceiling = resumePointCeiling(input.cursor); + if (resumedBackfill && isTimelinePhasePlace(input.cursor)) onLog?.(X_TIMELINE_PHASE_PLACE_NOTE); const stream = new GalleryDlStream({ channelSlug, seenIds, @@ -1413,6 +1464,7 @@ export const xGalleryDlFetcher: SocialFetcher = { stopAtKnown: input.stopAtKnown ?? Boolean(since), searchPhaseCursors: true, ...(resumedBackfill && newestKnown !== null ? { topRestartAt: newestKnown } : {}), + ...(ceiling !== null ? { resumeCeiling: ceiling } : {}), onLog, }); @@ -1485,9 +1537,13 @@ export const xGalleryDlFetcher: SocialFetcher = { const stdoutDone = readLines(subprocess.stdout, (line) => { if (line.trim()) betweenPages = false; stream.pushStdout(line); - if (stream.restartedFromTop && !stoppedAtTop && !stoppedAtKnown) { + if ((stream.restartedFromTop || stream.resumeNotHonoured) && !stoppedAtTop && !stoppedAtKnown) { stoppedAtTop = true; - onLog?.("The first posts read are the timeline's newest: the resume point was not honoured; stopping gallery-dl."); + onLog?.( + stream.resumeNotHonoured + ? "A post newer than the saved place was read: the resume point was not honoured; stopping gallery-dl." + : "The first posts read are the timeline's newest: the resume point was not honoured; stopping gallery-dl.", + ); subprocess.kill(); } if (stream.skippingKnown && !saidSkipping) { @@ -1566,7 +1622,12 @@ export const xGalleryDlFetcher: SocialFetcher = { // The walk began again from the top: its saved place is kept, and what it // read of the top (new posts, if any) is written like any other. if (stoppedAtTop) { - return { posts, complete: false, cursor: input.cursor, error: X_BACKFILL_RESTARTED_FROM_TOP }; + return { + posts, + complete: false, + cursor: input.cursor, + error: stream.resumeNotHonoured ? X_RESUME_POINT_NOT_HONOURED : X_BACKFILL_RESTARTED_FROM_TOP, + }; } if (stoppedAtKnown) return { posts, complete: true, caughtUp: true }; diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -225,18 +225,18 @@ test("the real shape: the page's title, summary, last update and tabs are read f const { trendPageOf } = await import("./xTrendingParse"); const real = await import("./__fixtures__/xTrendingRealShape"); assert.deepEqual(trendPageOf(real.realPageBody()), { - title: real.REAL_TITLE, - summary: real.REAL_SUMMARY, - lastUpdatedAt: new Date(real.REAL_LAST_UPDATED_MS).toISOString(), + title: real.INVENTED_TITLE, + summary: real.INVENTED_SUMMARY, + lastUpdatedAt: new Date(real.INVENTED_LAST_UPDATED_MS).toISOString(), tabs: [ - { label: "Top", timelineId: real.REAL_TOP_TIMELINE }, - { label: "Latest", timelineId: real.REAL_LATEST_TIMELINE }, + { label: "Top", timelineId: real.INVENTED_TOP_TIMELINE }, + { label: "Latest", timelineId: real.INVENTED_LATEST_TIMELINE }, ], }); // The accounts answer shares the page's `data` key and carries no page. assert.equal(trendPageOf(real.realRelevantUsers().body), undefined); assert.equal(trendPageOf(real.realStoryTopics().body), undefined); - assert.equal(trendPageOf(real.realFirstPage(real.REAL_FIRST).body), undefined); + assert.equal(trendPageOf(real.realFirstPage(real.INVENTED_FIRST).body), undefined); assert.equal(trendPageOf({ data: null }), undefined); assert.equal(trendPageOf("no"), undefined); // Words are one line; a title that is not text, a tab with no id and a date that is no number are left out. @@ -252,9 +252,9 @@ test("the real shape: a capture parses to the page's posts once each, the page, // Six posts: the quoted post rides on the post quoting it, the accounts of the module are no posts. assert.deepEqual(parsed.posts.map((p) => p.id), ["1900000000000003001", "1900000000000003002", "1900000000000003003", "1900000000000003004", "1900000000000003005", "1900000000000003006"]); assert.equal(parsed.posts[1].quoted?.id, "1900000000000002900"); - assert.equal(parsed.page?.title, real.REAL_TITLE); - assert.equal(parsed.page?.summary, real.REAL_SUMMARY); - assert.deepEqual(parsed.timelines, [{ timelineId: real.REAL_TOP_TIMELINE, tab: "Top", posts: 6 }]); + assert.equal(parsed.page?.title, real.INVENTED_TITLE); + assert.equal(parsed.page?.summary, real.INVENTED_SUMMARY); + assert.deepEqual(parsed.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 6 }]); assert.deepEqual(new Set(Object.values(parsed.tabs)), new Set(["Top"])); assert.equal(Object.keys(parsed.tabs).length, 6); assert.deepEqual( @@ -267,9 +267,9 @@ test("the real shape: a capture parses to the page's posts once each, the page, "1900000000000003004": { count: 1, kinds: ["gif"] }, }); // A capture with no page answer: posts all the same, no page, a timeline that is no known tab. - const bare = parseTrendingCapture(linesOf([real.realFirstPage(real.REAL_FIRST)]), "lib"); + const bare = parseTrendingCapture(linesOf([real.realFirstPage(real.INVENTED_FIRST)]), "lib"); assert.equal(bare.page, undefined); - assert.deepEqual(bare.timelines, [{ timelineId: real.REAL_TOP_TIMELINE, posts: 3 }]); + assert.deepEqual(bare.timelines, [{ timelineId: real.INVENTED_TOP_TIMELINE, posts: 3 }]); assert.deepEqual(bare.tabs, {}); // The old fixture names no timeline: one untagged timeline. assert.deepEqual(parseTrendingCapture(linesOf(fixtureTrendingResponses().load), "lib").timelines.map((t) => t.timelineId), [FIXTURE_TOP_TIMELINE]); @@ -279,12 +279,12 @@ test("the real shape: the bottom cursor is read from a cursor entry AND from Tim const { timelineShapeOf, requestVariablesOf } = await import("./xTrendingParse"); const real = await import("./__fixtures__/xTrendingRealShape"); // The first answer: a cursor entry (the top cursor beside it is not the bottom's). - assert.deepEqual(timelineShapeOf(real.realFirstPage(real.REAL_FIRST).body), { instructions: true, bottom: real.realBottomCursor(1) }); + assert.deepEqual(timelineShapeOf(real.realFirstPage(real.INVENTED_FIRST).body), { instructions: true, bottom: real.realBottomCursor(1) }); // A later answer: no cursor entry, two replacements. - const later = real.realContinuation(real.REAL_SECOND, { n: 2 }); + const later = real.realContinuation(real.INVENTED_SECOND, { n: 2 }); assert.deepEqual(timelineShapeOf(later.body), { instructions: true, bottom: real.realBottomCursor(2) }); - assert.deepEqual(requestVariablesOf(later.url), { cursor: real.realBottomCursor(1), timelineId: real.REAL_TOP_TIMELINE }); - assert.deepEqual(requestVariablesOf(real.realFirstPage([]).url), { timelineId: real.REAL_TOP_TIMELINE }); + assert.deepEqual(requestVariablesOf(later.url), { cursor: real.realBottomCursor(1), timelineId: real.INVENTED_TOP_TIMELINE }); + assert.deepEqual(requestVariablesOf(real.realFirstPage([]).url), { timelineId: real.INVENTED_TOP_TIMELINE }); // A replacement named only by the entry it replaces (no cursorType on the new entry) is still the bottom's. assert.deepEqual( timelineShapeOf({ instructions: [{ type: "TimelineReplaceEntry", entry_id_to_replace: "cursor-bottom-1", entry: { entryId: "x", content: { value: "next" } } }] }), @@ -308,7 +308,7 @@ test("the real shape: a capped read asserts nothing; the bottom continuation tha // The continuation from the last bottom cursor (carried by a TimelineReplaceEntry) brings no post… assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4 })]), true); // …or only posts already shown. - assert.equal(end([...real.realCaptureResponses(), real.realContinuation(real.REAL_THIRD, { n: 4 })]), true); + assert.equal(end([...real.realCaptureResponses(), real.realContinuation(real.INVENTED_THIRD, { n: 4 })]), true); // It must continue from the bottom cursor of the answer BEFORE it: the first answer's (an entry) is stale by then. assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realBottomCursor(1) })]), false); assert.equal(end([...real.realCaptureResponses(), real.realContinuation([], { n: 4, asked: real.realTopCursor(3) })]), false); @@ -326,25 +326,25 @@ test("the real shape: a capped read asserts nothing; the bottom continuation tha test("the real shape: two tabs in one capture show no end, and each post is the tab's that showed it first", async () => { const real = await import("./__fixtures__/xTrendingRealShape"); - const latest = { timelineId: real.REAL_LATEST_TIMELINE }; + const latest = { timelineId: real.INVENTED_LATEST_TIMELINE }; const responses = [ ...real.realCaptureResponses({ later: [] }), real.realContinuation([], { n: 2 }), // The other tab: a post of its own and one the first tab showed. - real.realFirstPage([real.REAL_SECOND[0], real.REAL_FIRST[0]], { ...latest, bottom: "latest-1" }), + real.realFirstPage([real.INVENTED_SECOND[0], real.INVENTED_FIRST[0]], { ...latest, bottom: "latest-1" }), real.realContinuation([], { ...latest, asked: "latest-1", bottom: "latest-2" }), ]; const parsed = parseTrendingCapture(linesOf(responses), "lib"); assert.equal(parsed.pageEnd, false); assert.deepEqual(parsed.timelines, [ - { timelineId: real.REAL_TOP_TIMELINE, tab: "Top", posts: 3 }, - { timelineId: real.REAL_LATEST_TIMELINE, tab: "Latest", posts: 1 }, + { timelineId: real.INVENTED_TOP_TIMELINE, tab: "Top", posts: 3 }, + { timelineId: real.INVENTED_LATEST_TIMELINE, tab: "Latest", posts: 1 }, ]); assert.equal(parsed.tabs["1900000000000003001"], "Top"); assert.equal(parsed.tabs["1900000000000003004"], "Latest"); // Each tab alone, read to its end, shows it: the continuation is its own timeline's. assert.equal(parseTrendingCapture(linesOf(responses.slice(0, -2)), "lib").pageEnd, true); // A continuation carrying ANOTHER timeline's bottom cursor is not this one's. - const crossed = [real.realFirstPage(real.REAL_FIRST), real.realContinuation([], { ...latest, asked: real.realBottomCursor(1) })]; + const crossed = [real.realFirstPage(real.INVENTED_FIRST), real.realContinuation([], { ...latest, asked: real.realBottomCursor(1) })]; assert.equal(parseTrendingCapture(linesOf(crossed), "lib").pageEnd, false); }); diff --git a/mcp/src/xTrending.test.ts b/mcp/src/xTrending.test.ts @@ -217,3 +217,15 @@ test("the MCP has a tool to read a library's accounts and none to organise or pu const names = (await client.listTools()).tools.map((t) => t.name).filter((n) => /trending/.test(n)); assert.deepEqual(names.sort(), ["x_trending_accounts", "x_trending_posts", "x_trending_topics"]); }); + +// Review 1: X's summary is listed at most 600 characters long. +test("x_trending_topics cuts a long summary of X's at 600 characters, at a word", async () => { + const summary = Array.from({ length: 150 }, (_, i) => `word${i}`).join(" "); + const listing = { ...LISTING, topics: [{ ...LISTING.topics[0], sources: [{ ...LISTING.topics[0].sources[0], summary }] }] }; + const { deps } = fakeEditor(() => ({ status: 200, body: listing }), env); + const client = await connectWith(deps); + const line = body(await client.callTool({ name: "x_trending_topics", arguments: { channel: "trending" } })).split("\n").find((l) => l.includes("X's summary: "))!; + const said = line.replace(" X's summary: ", ""); + assert.ok(said.length <= 600 && said.endsWith("…"), String(said.length)); + assert.ok(summary.startsWith(said.slice(0, -1))); +}); diff --git a/mcp/src/xTrending.ts b/mcp/src/xTrending.ts @@ -60,6 +60,16 @@ type PostRow = { type ListingBody = { name?: string; topics?: Topic[]; posts?: PostRow[]; total?: number; reads?: string[] }; +// X's summary of a page, at most this long here (the editor's listing cuts it +// the same way; the whole text stays in the library). +export const X_TRENDING_SUMMARY_MAX = 600; +function listedSummary(summary: string): string { + if (summary.length <= X_TRENDING_SUMMARY_MAX) return summary; + const cut = summary.slice(0, X_TRENDING_SUMMARY_MAX - 1); + const word = cut.lastIndexOf(" "); + return `${(word > X_TRENDING_SUMMARY_MAX * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; +} + const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "?"); export function renderXTrendingTopics(slug: string, body: ListingBody): string { @@ -74,7 +84,7 @@ export function renderXTrendingTopics(slug: string, body: ListingBody): string { : ""; lines.push(` ${s.url} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC${tab}`); if (s.title) lines.push(` X's title: ${s.title}${s.lastUpdatedAt ? ` (X updated it ${day(s.lastUpdatedAt)} UTC)` : ""}`); - if (s.summary) lines.push(` X's summary: ${s.summary}`); + if (s.summary) lines.push(` X's summary: ${listedSummary(s.summary)}`); } if (t.watch) lines.push(` watch: ${t.watch.sentence}`); } diff --git a/umtool/lib/library/cli.mjs b/umtool/lib/library/cli.mjs @@ -137,7 +137,7 @@ export async function libraryCommand(args, deps = {}) { (t.sources ?? []) .flatMap((src) => [ src.title ? ` X's title: ${src.title}` : "", - src.summary ? ` X's summary: ${src.summary}` : "", + src.summary ? ` X's summary: ${src.summary.length > 600 ? `${src.summary.slice(0, 599).trimEnd()}…` : src.summary}` : "", src.lastReadTab ? ` The last read saw the "${src.lastReadTab}" tab${src.tabs?.length > 1 ? ` of ${src.tabs.map((tab) => `"${tab}"`).join(", ")}` : ""}.` : "", ]) .filter(Boolean) diff --git a/umtool/lib/library/cli.test.mjs b/umtool/lib/library/cli.test.mjs @@ -148,6 +148,15 @@ test("topics says X's own title and summary of each page, and the tab the last r }); }); +test("topics cuts a long summary of X's at 600 characters", async () => { + await withRoot(async (root) => { + const h = harness({ sources: [{ trendId: "1", url: "https://x.com/i/trending/1", summary: "s".repeat(900), reads: 1, lastReadAt: null }] }); + assert.equal(await libraryCommand(["topics", "lib"], { ...h.deps, reportsRoot: root }), 0); + const said = h.lines[0].split("\n").find((l) => l.includes("X's summary: ")).replace(" X's summary: ", ""); + assert.equal(said, `${"s".repeat(599)}…`); + }); +}); + test("seen marks topics in umtool's own state, and --new counts from it", async () => { await withRoot(async (root) => { const h = harness();