// The watch scan over temp libraries and stand-in deps: nothing here opens a // browser, enqueues a real job or asks X anything. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xTrendingWatch.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { readXTrendingTopics, recordXTrendingRead, TRENDING_DIRNAME, writeXTrendingPosts } from "../lib/xTrending/store"; import { describeXTrendingWatch, readXTrendingWatches, setXTrendingWatch, xTrendingWatchPath } from "../lib/xTrending/watch"; import { xTrendingWatchTerms } from "../lib/xTrending/config"; import type { Post } from "../lib/posts"; import { armXTrendingWatch, disarmXTrendingWatch, isXTrendingWatchArmed, noteXTrendingWatchRead, pausedXTrendingWatches, runXTrendingWatchScan, scanXTrendingWatches, watchRefusal, xTrendingWatchFollowUp, type WatchRefusal, type WatchScanDeps, type WatchTick, } from "./xTrendingWatch"; const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-watch-")); after(() => rmSync(TMP, { recursive: true, force: true })); const T0 = Date.parse("2026-11-18T10:00:00.000Z"); const MIN = 60_000; const trend = (n: number) => ({ trendId: `190000000000000000${n}`, url: `https://x.com/i/trending/190000000000000000${n}` }); const readId = (n: number) => `tr-01J${String.fromCharCode(64 + n)}0000000000000000000000`; function post(id: string): Post { return { id, slug: `lib/${id}`, channelSlug: "lib", author: "kettle_fan", createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text: `post ${id}`, url: `https://x.com/kettle_fan/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], }; } let n = 0; // A corpus with libraries; each topic gets one read of one page per `pages`. async function corpus(libs: Record>): Promise { const dir = path.join(TMP, `c${++n}`); const paths = { transcriptsDir: dir, channelsDir: path.join(dir, "channels") } as Paths; let r = 0; for (const [slug, topics] of Object.entries(libs)) { const root = path.join(paths.channelsDir, slug); mkdirSync(root, { recursive: true }); writeFileSync(path.join(root, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", xTrending: {} })); for (const [topic, pages] of Object.entries(topics)) { for (const p of pages) { const id = `9${p}0${++r}`; await writeXTrendingPosts(root, [post(id)]); await recordXTrendingRead(root, { readId: readId(r), at: new Date(T0 - 60 * MIN).toISOString(), ref: trend(p), topic, postIds: [id], added: 1 }); } } } return paths; } type Harness = { deps: WatchScanDeps; ticks: WatchTick[]; state: { now: number; refusal: WatchRefusal | null; busy: Set; refuse: string | null; jar: string[] } }; function harness(paths: Paths, libraries: string[]): Harness { const ticks: WatchTick[] = []; const state: Harness["state"] = { now: T0, refusal: null, busy: new Set(), refuse: null, jar: [] }; return { ticks, state, deps: { paths, now: () => state.now, libraries: async () => libraries, busy: () => state.busy.size > 0, refusal: async () => state.refusal, enqueue: async (tick) => { if (state.refuse) return { ok: false, error: state.refuse }; ticks.push(tick); return { ok: true, jobId: `job-${ticks.length}` }; }, noteJarStale: async (line) => void state.jar.push(line), jitter: () => 0, }, }; } const root = (paths: Paths, slug = "lib") => path.join(paths.channelsDir, slug); const on = async (paths: Paths, topic: string, over: Partial[1]> = {}, slug = "lib") => setXTrendingWatch(root(paths, slug), { topics: await readXTrendingTopics(root(paths, slug)), topic, on: true, intervalMinutes: 30, hours: 48, by: "agent", maxTopics: 4, now: T0, ...over }); test("the switch: a topic with a page is watched with an interval and an end time; at most the library's limit; off ends it", async () => { const paths = await corpus({ lib: { Kettles: [1], Saucers: [2], Lids: [3] } }); const first = await on(paths, "Kettles"); assert.equal(first.ok, true); if (!first.ok) return; assert.equal(first.topic, "kettles"); assert.deepEqual( { on: first.watch.on, intervalMinutes: first.watch.intervalMinutes, until: first.watch.until, shots: first.watch.shots, ticks: first.watch.ticks }, { on: true, intervalMinutes: 30, until: "2026-11-20T10:00:00.000Z", shots: false, ticks: 0 }, ); assert.match(describeXTrendingWatch(first.watch, T0), /^Watched every 30 min until 2026-11-20 10:00 UTC; 0 ticks so far, next at the next scan\.$/); // By title too; a topic that does not exist is refused by name. assert.equal((await on(paths, "saucers", { maxTopics: 2 })).ok, true); const none = await on(paths, "Spouts"); assert.equal(none.ok, false); assert.match(none.ok ? "" : none.error, /no topic "Spouts" \(its topics: kettles, saucers, lids\)/); // The limit counts the OTHER live watches. const third = await on(paths, "Lids", { maxTopics: 2 }); assert.match(third.ok ? "" : third.error, /already watches 2 topics \(at most 2\)/); // Switching a live one on again changes its terms and is not a new watch. const again = await on(paths, "Kettles", { intervalMinutes: 60, shots: true, maxTopics: 2, now: T0 + 5 * MIN }); assert.equal(again.ok && again.watch.intervalMinutes, 60); assert.equal(again.ok && again.watch.shots, true); assert.equal(again.ok && again.watch.startedAt, "2026-11-18T10:00:00.000Z"); // Off. const off = await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 + 6 * MIN }); assert.equal(off.ok && off.watch.ended?.sentence, 'The watch of "Kettles" was switched off.'); assert.match((await setXTrendingWatch(root(paths), { topics: await readXTrendingTopics(root(paths)), topic: "kettles", on: false, intervalMinutes: 30, hours: 48, by: "operator", maxTopics: 2, now: T0 })).ok ? "" : "not watched", /not watched/); // Now there is room for the third. assert.equal((await on(paths, "Lids", { maxTopics: 2 })).ok, true); }); test("the watch's terms: the ask's, else the library's, else 30 minutes and 48 hours; out of range is refused", () => { assert.deepEqual(xTrendingWatchTerms(undefined), { ok: true, terms: { intervalMinutes: 30, hours: 48 } }); assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45, watchHours: 12 }), { ok: true, terms: { intervalMinutes: 45, hours: 12 } }); assert.deepEqual(xTrendingWatchTerms({ watchIntervalMinutes: 45 }, { intervalMinutes: 20, hours: 6 }), { ok: true, terms: { intervalMinutes: 20, hours: 6 } }); const short = xTrendingWatchTerms(undefined, { intervalMinutes: 5 }); assert.match(short.ok ? "" : short.error, /"intervalMinutes" is a whole number, 15–1440/); const long = xTrendingWatchTerms(undefined, { hours: 169 }); assert.match(long.ok ? "" : long.error, /"hours" is a whole number, 1–168/); }); test("one scan starts at most one read — the longest overdue — and the next tick is an interval away, never sooner", async () => { const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] }, other: { Lids: [3] } }); await on(paths, "Kettles", { now: T0 - 10 * MIN }); await on(paths, "Saucers", { now: T0 - 20 * MIN }); await on(paths, "Lids", { now: T0 - 5 * MIN }, "other"); const h = harness(paths, ["lib", "other"]); const first = await scanXTrendingWatches(h.deps); assert.deepEqual(h.ticks, [{ slug: "lib", topic: "saucers", url: trend(2).url, trendId: trend(2).trendId }]); assert.equal(first.enqueued?.jobId, "job-1"); assert.equal(first.live, 3); let w = (await readXTrendingWatches(root(paths))).saucers; assert.deepEqual([w.lastTickAt, w.lastJobId, w.nextTickAt, w.ticks], ["2026-11-18T10:00:00.000Z", "job-1", "2026-11-18T10:30:00.000Z", 1]); // A minute later: the next longest overdue, one again. h.state.now = T0 + MIN; await scanXTrendingWatches(h.deps); h.state.now = T0 + 2 * MIN; await scanXTrendingWatches(h.deps); assert.deepEqual(h.ticks.map((t) => `${t.slug}/${t.topic}`), ["lib/saucers", "lib/kettles", "other/lids"]); // Nothing is due until an interval has passed. h.state.now = T0 + 29 * MIN; assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); h.state.now = T0 + 30 * MIN; assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "saucers"); // Hours missed (the editor was down): ONE catch-up tick, not several. h.state.now = T0 + 6 * 60 * MIN; const before = h.ticks.length; await scanXTrendingWatches(h.deps); assert.equal(h.ticks.length, before + 1); // (Kettles was the longest overdue by then.) assert.equal((await readXTrendingWatches(root(paths))).kettles.ticks, 2); assert.equal((await readXTrendingWatches(root(paths))).saucers.ticks, 2); }); test("no tick is started for a library while a read or capture of it waits its turn", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles"); const h = harness(paths, ["lib"]); h.state.busy.add("lib"); assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); assert.equal((await readXTrendingWatches(root(paths))).kettles.paused, undefined); h.state.busy.clear(); assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); }); test("a stale jar PAUSES the watches, raises X's jar-age alert and enqueues nothing; they resume at the first scan after a Refresh", async () => { const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } }); await on(paths, "Kettles"); await on(paths, "Saucers"); const h = harness(paths, ["lib"]); h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 61 min ago (limit 60 min): press Refresh cookies (or Connect X account) on /cookies, then fetch again." }; const scan = await scanXTrendingWatches(h.deps); assert.deepEqual(h.ticks, []); assert.deepEqual(scan.paused.map((p) => [p.topic, p.reason]).sort(), [["kettles", "jar"], ["saucers", "jar"]]); assert.equal(h.state.jar.length, 1); assert.match(h.state.jar[0], /2 watched topics of lib paused: X cookies were last refreshed 61 min ago.*A watch runs only while X's cookie jar is fresh: it resumes at the first scan after Refresh cookies on \/cookies\./); let w = (await readXTrendingWatches(root(paths))).kettles; assert.deepEqual(w.paused && [w.paused.reason, w.paused.since], ["jar", "2026-11-18T10:00:00.000Z"]); assert.match(describeXTrendingWatch(w, T0), /PAUSED since 2026-11-18 10:00 UTC: X cookies were last refreshed 61 min ago/); // /review's rows: the paused watches, by library and topic, each with its sentence. assert.deepEqual( (await pausedXTrendingWatches(paths)).map((r) => [r.slug, r.topic, r.title, r.reason, r.since, r.until]), [ ["lib", "kettles", "Kettles", "jar", "2026-11-18T10:00:00.000Z", "2026-11-20T10:00:00.000Z"], ["lib", "saucers", "Saucers", "jar", "2026-11-18T10:00:00.000Z", "2026-11-20T10:00:00.000Z"], ], ); // Still stale ten minutes later: paused since the same moment, said once more to the alert, nothing enqueued. h.state.now = T0 + 10 * MIN; const still = await scanXTrendingWatches(h.deps); assert.deepEqual(still.paused, []); assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.since, "2026-11-18T10:00:00.000Z"); assert.deepEqual(h.ticks, []); // Review 1 S4: the same reason with another age in its sentence changes // nothing — watch.json is not rewritten, and the alert is not raised again // (a banner the operator dismissed stays dismissed). const before = readFileSync(xTrendingWatchPath(root(paths)), "utf8"); h.state.refusal = { reason: "jar", sentence: "X cookies were last refreshed 72 min ago (limit 60 min for a watch): press Refresh cookies." }; h.state.now = T0 + 11 * MIN; await scanXTrendingWatches(h.deps); assert.equal(readFileSync(xTrendingWatchPath(root(paths)), "utf8"), before); assert.equal(h.state.jar.length, 1); // Refreshed: resumed at this scan, and the overdue tick is taken. h.state.refusal = null; h.state.now = T0 + 12 * MIN; const resumed = await scanXTrendingWatches(h.deps); assert.deepEqual(resumed.resumed.map((r) => r.topic).sort(), ["kettles", "saucers"]); assert.equal(h.ticks.length, 1); w = (await readXTrendingWatches(root(paths))).kettles; assert.equal(w.paused, undefined); assert.deepEqual(await pausedXTrendingWatches(paths), []); }); test("the X alert, a cooldown and a missing profile pause too, each by its reason; only the jar raises the jar alert", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles"); const h = harness(paths, ["lib"]); for (const reason of ["alert", "cooldown", "no-profile"] as const) { h.state.refusal = { reason, sentence: `why: ${reason}` }; const scan = await scanXTrendingWatches(h.deps); assert.deepEqual(scan.paused, [{ slug: "lib", topic: "kettles", reason }]); assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.sentence, `why: ${reason}`); } assert.deepEqual(h.ticks, []); assert.deepEqual(h.state.jar, []); }); test("a read refused at its enqueue pauses that watch and is not asked again for an interval", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles"); const h = harness(paths, ["lib"]); h.state.refuse = "X's Refresh is running and holds the connected profile."; const scan = await scanXTrendingWatches(h.deps); assert.equal(scan.refused?.error, "X's Refresh is running and holds the connected profile."); let w = (await readXTrendingWatches(root(paths))).kettles; assert.equal(w.paused?.reason, "refused"); assert.equal(w.nextTickAt, "2026-11-18T10:30:00.000Z"); assert.equal(w.ticks, 0); // A minute later nothing is asked; the pause stands. h.state.refuse = null; h.state.now = T0 + MIN; assert.equal((await scanXTrendingWatches(h.deps)).enqueued, undefined); assert.equal((await readXTrendingWatches(root(paths))).kettles.paused?.reason, "refused"); // An interval later it is taken, and the pause is over. h.state.now = T0 + 30 * MIN; assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); w = (await readXTrendingWatches(root(paths))).kettles; assert.equal(w.paused, undefined); }); test("a watch ends at its end time, with a sentence, and is not ticked again", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles", { hours: 1 }); const h = harness(paths, ["lib"]); await scanXTrendingWatches(h.deps); h.state.now = T0 + 60 * MIN; const scan = await scanXTrendingWatches(h.deps); assert.deepEqual(scan.ended, [{ slug: "lib", topic: "kettles", sentence: 'The watch of "Kettles" ended at its end time (2026-11-18 11:00 UTC), after 1 tick.' }]); assert.equal(scan.live, 0); assert.equal(h.ticks.length, 1); h.state.now = T0 + 120 * MIN; await scanXTrendingWatches(h.deps); assert.equal(h.ticks.length, 1); }); test("a topic of several pages reads one page per tick, in turn; a page X retired is skipped, and the last one gone ends the watch", async () => { const paths = await corpus({ lib: { Kettles: [1, 2] } }); await on(paths, "Kettles"); const h = harness(paths, ["lib"]); for (let i = 0; i < 3; i++) { h.state.now = T0 + i * 30 * MIN; await scanXTrendingWatches(h.deps); } assert.deepEqual(h.ticks.map((t) => t.trendId), [trend(1).trendId, trend(2).trendId, trend(1).trendId]); // Page 1 is gone: the watch goes on with page 2 alone. assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(1).trendId, outcome: "gone", now: h.state.now }), null); assert.equal(await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "read" }), null); h.state.now = T0 + 90 * MIN; await scanXTrendingWatches(h.deps); h.state.now = T0 + 120 * MIN; await scanXTrendingWatches(h.deps); assert.deepEqual(h.ticks.slice(3).map((t) => t.trendId), [trend(2).trendId, trend(2).trendId]); // Page 2 gone as well: the watch ends, saying so. const sentence = await noteXTrendingWatchRead(root(paths), { trendId: trend(2).trendId, outcome: "gone", now: h.state.now }); assert.equal(sentence, 'X no longer has the trending page of "Kettles" (trending pages expire): the watch ended.'); const w = (await readXTrendingWatches(root(paths))).kettles; assert.deepEqual([w.on, w.ended?.reason], [false, "gone"]); h.state.now = T0 + 150 * MIN; await scanXTrendingWatches(h.deps); assert.equal(h.ticks.length, 5); }); test("after a read into a watched topic one capture takes its new posts with media, then what a capture left owed to a later one", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); const dir = root(paths); const ids = ["7001", "7002", "7003", "7004", "7005"]; await writeXTrendingPosts(dir, ids.map(post)); await recordXTrendingRead(dir, { readId: readId(20), at: new Date(T0).toISOString(), ref: trend(1), topic: "Kettles", postIds: ids, added: 5, media: { "7001": { count: 1, kinds: ["image"] }, "7003": { count: 1, kinds: ["video"] }, "7004": { count: 2, kinds: ["image"] }, "7005": { count: 1, kinds: ["image"] } }, }); // Not watched: nothing follows a read. assert.equal(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), null); await on(paths, "Kettles"); const capture = (id: string, rec: Record) => { mkdirSync(path.join(dir, "trending", "posts-media", id), { recursive: true }); writeFileSync(path.join(dir, "trending", "posts-media", id, "capture.json"), JSON.stringify({ version: 1, id, capturedAt: "2026-11-18T09:00:00.000Z", state: "captured", media: [], ...rec })); }; capture("7003", { mediaState: "error", mediaOwed: "next" }); capture("7004", { mediaState: "error", mediaOwed: "kept" }); capture("7005", { mediaState: "error", error: "7005_1.jpg: the CDN answered 404" }); // 7002 has no media: not captured by a media-only watch. 7003 is owed to a // later capture: taken. 7004 (owed until kept) and 7005 (failed) are not. // (The topic's first post, read before the watch and never captured, carries no media: not taken.) assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7003"], shots: false, fresh: 1, owed: 1, uncaptured: 0 }); // "Screenshot everything new": the post without media is taken too. await on(paths, "Kettles", { shots: true }); assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["7001", "7002"] }), { ids: ["7001", "7002", "7003"], shots: true, fresh: 2, owed: 1, uncaptured: 0 }); // A read into another topic's posts takes nothing of this one's new ids. // ...but (review 1 S7) 7001, which has media and was never captured — the // new post of an earlier tick whose capture was refused — is asked for again. assert.deepEqual(await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: ["424242"] }), { ids: ["7003", "7001"], shots: true, fresh: 0, owed: 1, uncaptured: 1 }); // Once it has a record, whatever the record says, it is not "never captured". capture("7001", { mediaState: "none" }); assert.deepEqual((await xTrendingWatchFollowUp(dir, { topic: "kettles", newIds: [] }))?.ids, ["7003"]); }); test("the scan is not armed on an idle boot; armed, it is one timer, and disarms", () => { const deps = { paths: {} as Paths, busy: () => false, enqueue: async () => ({ ok: false as const, error: "never" }) }; disarmXTrendingWatch(); assert.equal(armXTrendingWatch(deps, { env: { ARCHILYZER_IDLE_BOOT: "1" }, everyMs: 0 }), false); assert.equal(isXTrendingWatchArmed(), false); assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true); assert.equal(armXTrendingWatch(deps, { env: {}, everyMs: 0 }), true); assert.equal(isXTrendingWatchArmed(), true); disarmXTrendingWatch(); assert.equal(isXTrendingWatchArmed(), false); }); // Review 1 M1: the watch's own jar rule, whatever the guard would let a person's job do. test("M1: the watch asks a jar under its limit whatever the source, the setting or the settings file say", async () => { const now = T0; type Report = Awaited>; const report = (over: Partial): (() => Promise) => async () => ({ source: "profile", sourceChosen: true, profileDir: "p", cookieFile: "c", hasProfile: true, hasCookies: true, looksAuthenticated: true, cookiesUpdatedAt: new Date(now - 10 * MIN).toISOString(), ageMinutes: 10, maxAgeMinutes: 60, ageChecked: true, alert: null, cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: false }, // What the guard says of a person's job: allowed, in every case below. allowed: true, reason: null, ...over, }) as Report; const ask = (over: Partial, settingsReadable = true) => watchRefusal({} as Paths, "lib", now, { report: report(over) as never, settingsReadable: () => settingsReadable, held: async () => null }); const old = new Date(now - 3 * 60 * MIN).toISOString(); // The control: a fresh jar ticks. assert.equal(await ask({}), null); // Added scope R2: X's job cap is reached — a pause like a cooldown's (the tick is skipped, no strike, it goes on by itself), not the jar's. const cap = "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …"; assert.deepEqual(await ask({ allowed: false, reason: cap, cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never), { reason: "cooldown", sentence: cap }); // Review 2, ruling R-a: a job that does not count (a library's media-only capture) is not held by the cap — // the report it is asked with says so (`counts: false` reaches xSessionReport), and the cap clause stands aside. let asked: unknown; const notCounted = await watchRefusal({} as Paths, "lib", now, { report: (async (o: unknown) => ((asked = o), report({ cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never)())) as never, settingsReadable: () => true, held: async () => null, counts: false, }); assert.equal(notCounted, null); assert.equal((asked as { counts?: boolean }).counts, false); assert.deepEqual(await ask({ allowed: false, reason: "X's job count cannot be read (f): no X job starts while it is unreadable", cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: true, unreadable: true } } as never), { reason: "cooldown", sentence: "X's job count cannot be read (f): no X job starts while it is unreadable", }); // Exemption 1: the login comes from the browser — the guard cannot read its age and lets a job through. const browser = await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 }); assert.equal(browser?.reason, "jar"); assert.match(browser?.sentence ?? "", /last refreshed 3 h ago \(limit 60 min for a watch\)/); // ...and with no exported jar at all. assert.equal((await ask({ source: "browser", ageChecked: false, cookiesUpdatedAt: null, ageMinutes: null, hasCookies: false }))?.reason, "jar"); // Exemption 2: the setting is 0 (the rule off for a person's jobs): a watch still asks 60 minutes. const off = await ask({ maxAgeMinutes: 0, ageChecked: false, cookiesUpdatedAt: old, ageMinutes: 180 }); assert.match(off?.sentence ?? "", /limit 60 min for a watch/); assert.equal(await ask({ maxAgeMinutes: 0, ageChecked: false }), null); // A stricter setting is kept. assert.match((await ask({ maxAgeMinutes: 5 }))?.sentence ?? "", /10 min ago \(limit 5 min for a watch\)/); // Exemption 3: settings cannot be read. const unreadable = await ask({}, false); assert.equal(unreadable?.reason, "jar"); assert.match(unreadable?.sentence ?? "", /settings\.json cannot be read/); // A clock set back: the jar is dated after now. const future = await ask({ cookiesUpdatedAt: new Date(now + 5 * MIN).toISOString(), ageMinutes: 0 }); assert.match(future?.sentence ?? "", /dated in the future/); // A jar with no login. assert.equal((await ask({ looksAuthenticated: false }))?.reason, "jar"); // The alert and the profile, as before. assert.equal((await ask({ alert: { raisedAt: "x", line: "l" }, allowed: false, reason: "alert up" }))?.reason, "alert"); assert.equal((await ask({ hasProfile: false }))?.reason, "no-profile"); }); test("the watch's file sits where the library's other files do", () => { assert.equal(xTrendingWatchPath("/x"), path.join("/x", TRENDING_DIRNAME, "watch.json")); }); // Review 1 M3: the libraries share ONE stream of ticks. test("M3: a trending job of any library waiting its turn stops every library's tick; two libraries never stack two reads", async () => { const paths = await corpus({ lib: { Kettles: [1] }, other: { Lids: [3] } }); await on(paths, "Kettles"); await on(paths, "Lids", {}, "other"); const h = harness(paths, ["lib", "other"]); // As the editor's registry answers: busy once a read has been enqueued. h.deps.busy = () => h.ticks.length > 0 || h.state.busy.size > 0; await scanXTrendingWatches(h.deps); assert.deepEqual(h.ticks.map((t) => t.slug), ["lib"]); // The other library is due, and its tick waits: the first read is still queued. h.state.now = T0 + MIN; const second = await scanXTrendingWatches(h.deps); assert.equal(second.enqueued, undefined); assert.equal(h.ticks.length, 1); assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.ticks, 0); // Not a pause: nothing is wrong, it is only not its turn. assert.equal((await readXTrendingWatches(root(paths, "other"))).lids.paused, undefined); // The first read (and its capture) done: now the other library's turn. h.deps.busy = () => false; h.state.now = T0 + 2 * MIN; assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.slug, "other"); }); // Review 1 S1. test("S1: three reads in a row that do not end \"read\" pause the watch until a person switches it on again", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles"); const h = harness(paths, ["lib"]); const dir = root(paths); const fail = (outcome: string) => noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome, now: h.state.now, sentence: "X answered 429 (rate limit)." }); assert.equal(await fail("rate-limit"), null); assert.equal(await fail("error"), null); // A clean read between failures starts the count again. assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "read" }), null); assert.equal((await readXTrendingWatches(dir)).kettles.failures, 0); assert.equal(await fail("forbidden"), null); assert.equal(await fail("rate-limit"), null); // A probe is nobody's failure. assert.equal(await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "probe" }), null); const third = await fail("rate-limit"); assert.match(third ?? "", /^The last 3 reads of "Kettles" failed \(the last: rate-limit — X answered 429 \(rate limit\)\.\): its watch is paused until the operator switches it on again/); let w = (await readXTrendingWatches(dir)).kettles; assert.deepEqual([w.on, w.paused?.reason, w.failures], [true, "failing", 3]); assert.match(describeXTrendingWatch(w, T0), /PAUSED since .* UTC, until the operator switches it on again: The last 3 reads/); // No scan resumes it — not with X fine, not an interval later — and none ticks it. for (const at of [T0 + MIN, T0 + 31 * MIN, T0 + 5 * 60 * MIN]) { h.state.now = at; const scan = await scanXTrendingWatches(h.deps); assert.deepEqual([scan.enqueued, scan.resumed], [undefined, []]); } // Nor does a refusal overwrite the reason. h.state.refusal = { reason: "jar", sentence: "stale" }; await scanXTrendingWatches(h.deps); assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); h.state.refusal = null; assert.deepEqual(h.ticks, []); // /review lists it. assert.deepEqual((await pausedXTrendingWatches(paths)).map((r) => [r.topic, r.reason]), [["kettles", "failing"]]); // A person switches it on again: the count starts over and it ticks. await on(paths, "Kettles", { now: h.state.now, by: "operator" }); w = (await readXTrendingWatches(dir)).kettles; assert.deepEqual([w.paused, w.failures], [undefined, 0]); assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); }); // Review 1 S6. test("S6: two asks for a scan at once are one scan and one read", async () => { const paths = await corpus({ lib: { Kettles: [1], Saucers: [2] } }); await on(paths, "Kettles"); await on(paths, "Saucers"); const h = harness(paths, ["lib"]); let built = 0; const deps = () => (built++, h.deps); const [a, b] = await Promise.all([runXTrendingWatchScan(deps), runXTrendingWatchScan(deps)]); assert.equal(a, b); assert.equal(built, 1); assert.equal(h.ticks.length, 1); // A later ask is a scan of its own. h.state.now = T0 + MIN; await runXTrendingWatchScan(deps); assert.equal(h.ticks.length, 2); }); // Review 2 N5. test("N5: only the operator starts a failing watch again; an enqueue does not erase a failing pause set meanwhile", async () => { const paths = await corpus({ lib: { Kettles: [1] } }); await on(paths, "Kettles"); const dir = root(paths); const h = harness(paths, ["lib"]); // While the tick is being enqueued, three reads end badly: the watch is failing. const enqueue = h.deps.enqueue; h.deps.enqueue = async (tick) => { for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); return enqueue(tick); }; assert.equal((await scanXTrendingWatches(h.deps)).enqueued?.topic, "kettles"); let w = (await readXTrendingWatches(dir)).kettles; assert.equal(w.paused?.reason, "failing"); assert.equal(w.ticks, 1); // The same when the enqueue is refused: the failing pause is not overwritten. h.deps.enqueue = async () => ({ ok: false, error: "refused for another reason" }); await on(paths, "Kettles", { by: "operator", now: h.state.now }); h.deps.enqueue = async () => { for (let i = 0; i < 3; i++) await noteXTrendingWatchRead(dir, { trendId: trend(1).trendId, outcome: "error", now: h.state.now }); return { ok: false, error: "refused for another reason" }; }; h.state.now = T0 + 31 * MIN; await scanXTrendingWatches(h.deps); assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); // An agent cannot switch it on again... const agent = await on(paths, "Kettles", { by: "agent", now: h.state.now }); assert.equal(agent.ok, false); assert.match(agent.ok ? "" : agent.error, /is paused because its reads kept failing .* Only the operator starts it again/); assert.equal((await readXTrendingWatches(dir)).kettles.paused?.reason, "failing"); // ...the operator can. const op = await on(paths, "Kettles", { by: "operator", now: h.state.now }); assert.equal(op.ok, true); w = (await readXTrendingWatches(dir)).kettles; assert.deepEqual([w.paused, w.failures], [undefined, 0]); });