// Recurring reports (umtool R5): the store and its one writer, the runner's // due/lock logic, and the tick over stubbed steps. Temp stores only. // // Run with: node_modules/.bin/tsx --test controller/reportSchedule.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, 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 { sanitizeGeneration } from "../lib/generationSettings"; import { listPendingArticles, listArticleDirs } from "../lib/report/registry"; import { createIteration, readIterationFile, updateIteration, writeIterationFile } from "../lib/report/iterations"; import { livingFile, listSchedules, readSchedule, seriesFile } from "../lib/report/schedule/store"; import { parseCadence } from "../lib/report/schedule/cadence"; import { editionWindow } from "../lib/report/schedule/types"; import { claimTick, createSchedule, deleteSchedule, parseCreate, planCreate, planDelete, setPaused, updateSchedule, } from "./reportSchedule"; import { editionGenerator, notWiredFetch, notWiredRefresh, runTick, type StepOutcome, type TickDeps, type TickSteps } from "./reportTick"; import { scanSchedules } from "./reportScheduleRunner"; import { reportScheduleAction as action } from "./reportScheduleOps"; // The answers, read loosely (each test says which keys it expects). // eslint-disable-next-line @typescript-eslint/no-explicit-any const reportScheduleAction = (b: Record, d: Parameters[1]): Promise => action(b, d); const ROOTS: string[] = []; after(() => { for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); }); const TZ = "America/New_York"; // Wed 2026-10-14 08:00 New York. const NOW = new Date("2026-10-14T12:00:00.000Z"); function store() { const root = mkdtempSync(path.join(tmpdir(), "report-schedule-")); ROOTS.push(root); const paths = { articlesDir: path.join(root, "reports"), exportIndexDir: path.join(root, ".export-index"), generationUsageFile: path.join(root, "usage.jsonl"), jobsDir: path.join(root, ".jobs"), } as unknown as Paths; mkdirSync(paths.articlesDir, { recursive: true }); return paths; } const gen = (over: Record = {}) => sanitizeGeneration({ routes: { sweep: "api" }, ...over }); function depsOf(paths: Paths, steps: Partial = {}, now: Date = NOW, extra: Partial = {}): TickDeps { return { paths, now: () => now, settings: () => ({ generation: gen() }), knownChannels: async () => ["chan-a", "chan-b"], steps: { fetchAndBuild: async () => ({ ok: true }), refresh: async () => ({ status: "no-change", usd: 0 }), generateEdition: async () => ({ status: "quiet", usd: 0, matched: 0 }), ...steps, }, ...extra, }; } const ctx = () => ({ log: () => {}, signal: new AbortController().signal }); const reportDoc = (id: string, title = `Article ${id}`) => ({ format: "archilyzer-report", version: 1, id, kind: "sweep", title, sections: [{ id: "s1", title: "One", body: "Plain words." }], }); async function doneIteration(paths: Paths, article: string, title?: string) { const it = await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?", scope: { channels: ["chan-a"] } }, paths); await writeIterationFile(article, it.n, "report.json", reportDoc(article, title), paths); await updateIteration(article, it.n, { status: "done" }, paths); return it.n; } const weekly = { kind: "weekly", dow: 1, at: "06:00" }; // ─── the store and its writer ─── test("create: a series in .series/, a living report beside a NEW article that is in the making; dryRun writes nothing", async () => { const paths = store(); const deps = depsOf(paths); const plan = await reportScheduleAction({ action: "create", dryRun: true, shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }, deps); assert.equal(plan.ok, true); const p = (plan as { plan: { id: string; firstTick: string; firstTickWords: string; firstWindow: { from: string; to: string }; firstTitle: string; capUsd: number; provider: string } }).plan; assert.equal(p.id, "co-host-updates"); assert.equal(p.firstTick, "2026-10-19T10:00:00.000Z"); assert.equal(p.firstTickWords, "Mon 06:00"); // The first Monday tick covers the Mon … Sun before it. assert.deepEqual(p.firstWindow, { from: "2026-10-12", to: "2026-10-18" }); assert.equal(p.firstTitle, "Co-host updates · week of 2026-10-12"); assert.equal(p.capUsd, 5); assert.equal(p.provider, "api"); assert.deepEqual(await listSchedules(paths), []); const made = await reportScheduleAction({ action: "create", shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: "weekly mon 06:00", tz: TZ, terms: "co-host" }, deps); assert.equal(made.ok, true, JSON.stringify(made)); assert.ok(existsSync(seriesFile(paths, "co-host-updates"))); // A second one with the same topic takes the next id. const again = await reportScheduleAction({ action: "create", shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }, deps); assert.equal((again as { schedule: { id: string } }).schedule.id, "co-host-updates-2"); const living = await reportScheduleAction({ action: "create", shape: "living", topic: "The shop story", question: "What does she say about the shop?", channels: ["chan-b"], cadence: { kind: "daily", at: "07:30" }, tz: TZ }, deps); assert.equal(living.ok, true, JSON.stringify(living)); const s = (living as { schedule: { id: string; article: string; nextTick: string; autoMakeCurrent: boolean; chip: string } }).schedule; assert.equal(s.id, "the-shop-story"); assert.equal(s.article, "the-shop-story"); assert.equal(s.autoMakeCurrent, false); assert.equal(s.nextTick, "2026-10-15T11:30:00.000Z"); assert.equal(s.chip, "daily · next Thu 07:30"); assert.ok(existsSync(livingFile(paths, "the-shop-story"))); // An article in the making, never a broken article. assert.deepEqual(await listPendingArticles(paths), ["the-shop-story"]); assert.deepEqual(await listArticleDirs(paths), []); const list = await reportScheduleAction({ action: "list" }, { ...deps, lane: () => ({ held: false, armed: false }) }); assert.deepEqual( (list as { schedules: { id: string }[] }).schedules.map((x) => x.id), ["co-host-updates", "co-host-updates-2", "the-shop-story"], ); }); test("create refuses: an unknown shape, no scope, an unknown channel, an edition flag on the wrong shape, a cap over max", async () => { const paths = store(); const deps = depsOf(paths); const ask = (b: Record) => reportScheduleAction({ action: "create", topic: "T", channels: ["chan-a"], cadence: weekly, tz: TZ, shape: "series", ...b }, deps); assert.match(((await ask({ shape: "nope" })) as { error: string }).error, /"shape" is one of living, series, watch/); assert.match(((await ask({ shape: "watch", triageFirst: true })) as { error: string }).error, /a watch always triages first/); assert.match(((await ask({ threshold: { strong: 1 } })) as { error: string }).error, /"threshold" is/); assert.match(((await ask({ channels: [] })) as { error: string }).error, /scope/); assert.match(((await ask({ channels: ["nope"] })) as { error: string }).error, /no such channel in this editor: nope/); assert.match(((await ask({ autoMakeCurrent: true })) as { error: string }).error, /living report/); assert.match(((await ask({ cadence: { kind: "every", days: 1 } })) as { error: string }).error, /2 to 365/); assert.match(((await ask({ maxUsd: 50 })) as { error: string }).error, /over the settings' max/); assert.match(((await ask({ tz: "Mars/Olympus" })) as { error: string }).error, /time zone/); assert.deepEqual(await listSchedules(paths), []); }); test("update re-plans on a new cadence; pause holds; resume re-plans from now (no catch-up of a pause)", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Weekly", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths)); const later = new Date("2026-10-30T12:00:00.000Z"); const u = await updateSchedule("weekly", { cadence: parseCadence("every 3 days 09:00") }, depsOf(paths, {}, later)); assert.equal(u.nextTick, "2026-10-30T13:00:00.000Z"); assert.equal(u.anchor, "2026-10-30"); const p = await setPaused("weekly", true, depsOf(paths)); assert.equal(p.paused, true); const r = await setPaused("weekly", false, depsOf(paths, {}, new Date("2026-11-20T15:00:00.000Z"))); assert.equal(r.paused, false); // On the anchor's grid (Oct 30 + 3k), the first after Nov 20 15:00 local-ish: Nov 23 09:00 EST. assert.equal(r.nextTick, "2026-11-23T14:00:00.000Z"); await assert.rejects(updateSchedule("weekly", { autoMakeCurrent: true }, depsOf(paths)), /living report/); }); test("delete: a plan first (what goes, what stays), refused while a tick runs, then gone", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "series", topic: "Gone", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); const plan = await reportScheduleAction({ action: "delete", id: "gone" }, deps); assert.equal((plan as { confirmed: boolean }).confirmed, false); assert.match((plan as { plan: { removes: string } }).plan.removes, /the series gone/); assert.ok(existsSync(seriesFile(paths, "gone"))); await claimTick("gone", { jobId: "job-1", trigger: "now" }, deps); assert.match((await planDelete("gone", deps)).refused ?? "", /job job-1/); assert.match(((await reportScheduleAction({ action: "delete", id: "gone", confirm: true }, deps)) as { error: string }).error, /cancel it or let it end/); await updateSchedule("gone", { topic: "Gone" }, deps); // Released, it goes. const { recordTick } = await import("./reportSchedule"); await recordTick("gone", { at: NOW.toISOString(), trigger: "now", jobId: "job-1", status: "quiet", usd: 0 }, deps); const done = await reportScheduleAction({ action: "delete", id: "gone", confirm: true }, deps); assert.equal((done as { confirmed: boolean }).confirmed, true); assert.equal(existsSync(seriesFile(paths, "gone")), false); await assert.rejects(deleteSchedule("gone", deps), /no schedule/); }); // ─── the runner ─── test("the runner: a due schedule gets ONE tick (missed windows counted); paused, ticking and not-due ones none; the gate holds all", async () => { const paths = store(); const base = depsOf(paths, {}, new Date("2026-10-01T12:00:00.000Z")); await createSchedule(parseCreate({ shape: "series", topic: "Due", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ }), base); await createSchedule(parseCreate({ shape: "series", topic: "Paused", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ }), base); await createSchedule(parseCreate({ shape: "series", topic: "Later", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths, {}, NOW)); await setPaused("paused", true, base); // The editor was away from Oct 2 06:00 to Oct 5 08:00 (local): four daily windows. const now = new Date("2026-10-05T12:00:00.000Z"); const asked: { id: string; o: unknown }[] = []; const enqueue = async (id: string, o: { next: string }) => { asked.push({ id, o }); await claimTick(id, { jobId: `job-${id}`, trigger: "schedule", next: o.next }, depsOf(paths, {}, now)); return { ok: true as const, jobId: `job-${id}` }; }; const held = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => true, enqueue, isLive: () => true }); assert.equal(held.held, true); assert.equal(asked.length, 0); const r = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => false, enqueue, isLive: () => true }); assert.deepEqual(r.enqueued.map((e) => [e.id, e.scheduledFor, e.missed]), [["due", "2026-10-02T10:00:00.000Z", 3]]); assert.deepEqual(asked[0].o, { trigger: "schedule", scheduledFor: "2026-10-02T10:00:00.000Z", next: "2026-10-06T10:00:00.000Z", missed: 3 }); assert.equal((await readSchedule("due", paths))?.nextTick, "2026-10-06T10:00:00.000Z"); // A second scan while the tick runs: nothing (never two ticks of one schedule). const again = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => false, enqueue, isLive: () => true }); assert.equal(again.enqueued.length, 0); // The editor died mid-tick: the claim is released, the tick recorded interrupted. const dead = await scanSchedules({ deps: depsOf(paths, {}, now), held: () => true, enqueue, isLive: () => false }); assert.deepEqual(dead.interrupted, ["due"]); const s = await readSchedule("due", paths); assert.equal(s?.running, null); assert.equal(s?.ticks.at(-1)?.status, "interrupted"); }); test("claims: a second claim of one schedule is refused", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "series", topic: "One", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); assert.ok(await claimTick("one", { jobId: "a", trigger: "now" }, deps)); assert.equal(await claimTick("one", { jobId: "b", trigger: "schedule" }, deps), null); const r = await reportScheduleAction({ action: "tick-now", id: "one" }, deps); assert.equal(r.ok, false); assert.match((r as { error: string }).error, /already queued or running \(job a\)/); }); // ─── the tick, over stubbed steps ─── test("living, no change: refresh says so, $0, nothing made current", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "living", topic: "Shop", channels: ["chan-a"], cadence: weekly, tz: TZ, autoMakeCurrent: true }), deps); await doneIteration(paths, "shop"); const asked: string[] = []; const t = await runTick("shop", { trigger: "now", jobId: "j1" }, depsOf(paths, { refresh: async (a) => (asked.push(a), { status: "no-change", usd: 0, reason: "nothing new" }) }, NOW, { makeCurrent: async () => assert.fail("not made current") }), ctx()); assert.deepEqual(asked, ["shop"]); assert.equal(t.status, "no-change"); assert.equal(t.usd, 0); const s = await readSchedule("shop", paths); assert.equal(s?.ticks.length, 1); assert.equal(s?.lastTick, NOW.toISOString()); }); test("living, updated: the new iteration is left ready — or made current when autoMakeCurrent", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "living", topic: "Kept", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); await createSchedule(parseCreate({ shape: "living", topic: "Auto", channels: ["chan-a"], cadence: weekly, tz: TZ, autoMakeCurrent: true }), deps); await doneIteration(paths, "kept"); await doneIteration(paths, "auto"); const made: string[] = []; const steps = { refresh: async (): Promise => ({ status: "done", usd: 0.42, iteration: 2 }) }; const extra = { makeCurrent: async (a: string, n: number) => made.push(`${a}/${n}`) }; const kept = await runTick("kept", { trigger: "schedule", jobId: "j1", scheduledFor: NOW.toISOString() }, depsOf(paths, steps, NOW, extra), ctx()); assert.equal(kept.status, "done"); assert.equal(kept.iteration, 2); assert.equal(kept.usd, 0.42); assert.deepEqual(made, []); const auto = await runTick("auto", { trigger: "now", jobId: "j2" }, depsOf(paths, steps, NOW, extra), ctx()); assert.equal(auto.status, "done"); assert.deepEqual(made, ["auto/2"]); }); test("living with no report yet: its first tick is the article's first sweep, not a refresh", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "living", topic: "Fresh", channels: ["chan-a"], cadence: { kind: "daily", at: "06:00" }, tz: TZ, from: "2026-01-01" }), deps); const asked: unknown[] = []; const t = await runTick( "fresh", { trigger: "now", jobId: "j1" }, depsOf(paths, { refresh: async () => assert.fail("no report to refresh"), generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, quiet: i.quietCheck, title: i.title }), { status: "done", usd: 1.5, iteration: 1 }), }), ctx(), ); assert.equal(t.status, "done"); assert.deepEqual(asked, [{ article: "fresh", window: { from: "2026-01-01", to: "2026-10-14" }, quiet: false, title: null }]); }); test("series: an edition over whole days since the last one, titled; then a quiet edition; a Tick now with nothing to cover makes none", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "series", topic: "Co-host updates", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); const asked: { article: string; window: unknown; title: string | null }[] = []; const t1 = await runTick( "co-host-updates", { trigger: "now", jobId: "j1" }, depsOf(paths, { generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, title: i.title }), { status: "done", usd: 2.25, iteration: 1, matched: 4, jobId: "draft-1" }) }), ctx(), ); assert.equal(t1.status, "done"); assert.equal(t1.edition, 1); assert.equal(t1.article, "co-host-updates-2026-10-14"); // The cadence's length back, through the day before the tick. assert.deepEqual(asked[0], { article: "co-host-updates-2026-10-14", window: { from: "2026-10-07", to: "2026-10-13" }, title: "Co-host updates · week of 2026-10-07" }); let s = await readSchedule("co-host-updates", paths); assert.deepEqual( s?.editions?.map((e) => [e.n, e.status, e.article, e.usd, e.matched]), [[1, "done", "co-host-updates-2026-10-14", 2.25, 4]], ); // A Tick now the same day: nothing to cover -- no edition, $0, said plainly. const again = await runTick("co-host-updates", { trigger: "now", jobId: "j1b" }, depsOf(paths, { generateEdition: async () => assert.fail("nothing to cover") }), ctx()); assert.equal(again.status, "no-change"); assert.equal(again.usd, 0); assert.equal(again.edition, undefined); assert.equal(again.reason, "Nothing to cover yet — the next edition starts 2026-10-14"); assert.equal((await readSchedule("co-host-updates", paths))?.editions?.length, 1); // A week on: the window starts the day after the last ended; nothing matches. const week = new Date("2026-10-21T12:00:00.000Z"); const t2 = await runTick("co-host-updates", { trigger: "schedule", jobId: "j2" }, depsOf(paths, { generateEdition: async (i) => (asked.push({ article: i.article, window: i.window, title: i.title }), { status: "quiet", usd: 0, matched: 0, reason: "nothing matches" }) }, week), ctx()); assert.equal(t2.status, "quiet"); assert.equal(t2.usd, 0); assert.equal(t2.edition, 2); assert.equal(t2.article, undefined); assert.deepEqual(asked[1].window, { from: "2026-10-14", to: "2026-10-20" }); s = await readSchedule("co-host-updates", paths); assert.deepEqual(s?.editions?.[1], { n: 2, at: week.toISOString(), window: { from: "2026-10-14", to: "2026-10-20" }, title: "Co-host updates · week of 2026-10-14", status: "quiet", usd: 0, reason: "nothing matches", matched: 0 }); // The next window continues the day after the quiet one's end. assert.deepEqual(editionWindow(s!, "2026-10-28"), { window: { from: "2026-10-21", to: "2026-10-27" } }); }); test("series held by a cap: no edition (the next tick covers the window), the tick held with its reason and estimate", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "series", topic: "Capped", channels: ["chan-a"], cadence: weekly, tz: TZ }), deps); const t = await runTick( "capped", { trigger: "schedule", jobId: "j1" }, depsOf(paths, { generateEdition: async () => ({ status: "held-by-cap", usd: 0, reason: "the day's Claude API spend is $20.00 … daily cap", estimateUsd: 5 }) }), ctx(), ); assert.equal(t.status, "held-by-cap"); assert.equal(t.estimateUsd, 5); const s = await readSchedule("capped", paths); assert.deepEqual(s?.editions, []); assert.equal(s?.ticks.at(-1)?.status, "held-by-cap"); assert.equal(s?.running, null); }); test("without R4's steps (no editor door): the fetch step refuses, and the tick fails saying so", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Unwired", channels: ["chan-a"], cadence: weekly, tz: TZ }), depsOf(paths)); const t = await runTick("unwired", { trigger: "now", jobId: "j1" }, depsOf(paths, { fetchAndBuild: notWiredFetch, refresh: notWiredRefresh }), ctx()); assert.equal(t.status, "failed"); assert.match(t.reason ?? "", /^not wired: no fetch-and-build step/); }); // ─── the real generateEdition, as far as it runs without a model ─── test("generateEdition: a window with nothing in it is quiet ($0, no job); past the daily cap it is held, before any job", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Real", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths)); const s = (await readSchedule("real", paths))!; const draft = { paths, corpusTools: async () => assert.fail("no corpus read"), settings: () => ({ generation: gen() }), now: () => NOW }; const quiet = await editionGenerator({ draft, countWindow: async (q) => (assert.equal(q.terms, "co-host"), { recordings: 0 }) })( { schedule: s, article: "real-2026-10-14", title: "Real · week of 2026-10-07", window: { from: "2026-10-07", to: "2026-10-14" }, quietCheck: true }, ctx(), ); assert.deepEqual(quiet, { status: "quiet", usd: 0, matched: 0, reason: "nothing in 2026-10-07 … 2026-10-14 matches co-host" }); writeFileSync(paths.generationUsageFile, JSON.stringify({ at: NOW.toISOString(), day: "2026-10-14", jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }) + "\n"); const held = await editionGenerator({ draft, countWindow: async () => ({ recordings: 3 }) })( { schedule: s, article: "real-2026-10-14", title: "t", window: { from: "2026-10-07", to: "2026-10-14" }, quietCheck: true }, ctx(), ); assert.equal(held.status, "held-by-cap"); assert.equal(held.estimateUsd, 5); assert.equal(held.matched, 3); assert.match(held.reason ?? "", /daily cap/); // Nothing was made. assert.equal(existsSync(path.join(paths.articlesDir, "real-2026-10-14")), false); assert.equal(await readIterationFile("real-2026-10-14", 1, "report.json", paths).catch(() => null), null); void readFileSync; }); // ─── R4's steps, wired (r4Steps), over stubbed calls ─── import { r4Steps, type R4Calls } from "./reportTick"; type FetchResult = Awaited>; const okJob = (jobId: string) => ({ ok: true as const, jobId, stream: new ReadableStream(), done: Promise.resolve({ status: "done" as const, jobId }) }); test("r4Steps.fetchAndBuild: stage 1 over the scope; a held platform is a warning, not a failure; a failed build fails", async () => { const paths = store(); const draft = { paths, corpusTools: async () => assert.fail("no corpus") }; const asked: unknown[] = []; const result = (over: Partial = {}): FetchResult => ({ fetch: [ { channel: "chan-a", action: "sync", status: "done", jobId: "j1" }, { channel: "chan-b", action: "sync", status: "refused", reason: "youtube is held: skipped, as polite scraping asks" }, ], build: { site: "site-x", status: "done", jobIds: ["b1"] }, warnings: ["chan-c is on no site"], ...over, }); const steps = r4Steps(draft, { fetchScope: async (scope, _d, o) => (asked.push({ scope, signal: !!o?.signal }), result()) }); const ok = await steps.fetchAndBuild({ channels: ["chan-a", "chan-b"], from: "2026-10-12", to: "2026-10-18" }, ctx()); assert.deepEqual(asked, [{ scope: { channels: ["chan-a", "chan-b"], from: "2026-10-12", to: "2026-10-18" }, signal: true }]); assert.equal(ok.ok, true); assert.deepEqual(ok.warnings, ["chan-c is on no site", "chan-b sync: youtube is held: skipped, as polite scraping asks"]); const failed = await r4Steps(draft, { fetchScope: async () => result({ build: { site: "site-x", status: "failed", reason: "next build exited 1" } }) }).fetchAndBuild({ channels: ["chan-a"] }, ctx()); assert.deepEqual({ ok: failed.ok, status: !failed.ok && failed.status, reason: !failed.ok && failed.reason }, { ok: false, status: "failed", reason: "the local build of site-x failed: next build exited 1" }); }); test("r4Steps.refresh: report-draft refresh awaited; refresh.json's status is the outcome (updated, no-change, held-by-cap); a cap refusal is held", async () => { const paths = store(); await doneIteration(paths, "shop"); const it2 = await createIteration("shop", { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?", scope: { channels: ["chan-a"] } }, paths); await updateIteration("shop", it2.n, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.8, inputTokens: 1, outputTokens: 1 } } }, paths); const draft = { paths, corpusTools: async () => assert.fail("no corpus") }; const asked: Record[] = []; const file = (status: string, extra: Record = {}) => ({ format: "archilyzer-refresh", status, summary: `${status} summary`, warnings: [], fetch: [{ channel: "chan-b", action: "sync", status: "refused", reason: "rumble is cooling down" }], ...extra }); const run = (status: string, extra: Record = {}) => r4Steps(draft, { enqueueReportDraft: (async (b: Record) => (asked.push(b), { result: okJob("rj"), iteration: it2.n })) as never, readRefreshFile: (async () => file(status, extra)) as never, }).refresh("shop", { maxUsd: 3 }, ctx()); const updated = await run("updated"); assert.deepEqual(asked[0], { task: "refresh", article: "shop", maxUsd: 3 }); assert.deepEqual({ status: updated.status, iteration: updated.iteration, usd: updated.usd, jobId: updated.jobId }, { status: "done", iteration: it2.n, usd: 0.8, jobId: "rj" }); assert.deepEqual(updated.warnings, ["chan-b sync: rumble is cooling down"]); assert.equal((await run("no-change")).status, "no-change"); const held = await run("held-by-cap", { update: { model: "m", estimateUsd: 4.5, capUsd: 5, refusal: "the day's Claude API spend is $20.00 … daily cap" } }); assert.deepEqual({ status: held.status, estimateUsd: held.estimateUsd, reason: held.reason }, { status: "held-by-cap", estimateUsd: 4.5, reason: "the day's Claude API spend is $20.00 … daily cap" }); const refused = await r4Steps(draft, { enqueueReportDraft: (async () => ({ result: { ok: false, error: "the day's Claude API spend is $20.00 (2026-10-14, UTC), at or past the $20.00 daily cap (settings.generation.caps.daily) — refused" } })) as never, }).refresh("shop", {}, ctx()); assert.equal(refused.status, "held-by-cap"); }); test("the wired tick: living updated + autoMakeCurrent is made current (only on updated); a series fetches its window, its warnings on the tick, nothing fetched for an empty window", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "living", topic: "Auto", channels: ["chan-a"], cadence: weekly, tz: TZ, autoMakeCurrent: true }), depsOf(paths)); await doneIteration(paths, "auto"); const made: string[] = []; const extra = { makeCurrent: async (a: string, n: number) => made.push(`${a}/${n}`) }; const fetchCalls: unknown[] = []; const steps = (refresh: StepOutcome): Partial => ({ fetchAndBuild: async (scope) => (fetchCalls.push(scope), { ok: true, warnings: ["youtube is held: skipped"] }), refresh: async () => refresh, }); const noChange = await runTick("auto", { trigger: "now", jobId: "j1" }, depsOf(paths, steps({ status: "no-change", usd: 0, iteration: 2 }), NOW, extra), ctx()); assert.equal(noChange.status, "no-change"); const held = await runTick("auto", { trigger: "now", jobId: "j2" }, depsOf(paths, steps({ status: "held-by-cap", usd: 0, iteration: 3, estimateUsd: 4, reason: "daily cap", warnings: ["rumble is cooling down"] }), NOW, extra), ctx()); assert.deepEqual({ status: held.status, estimateUsd: held.estimateUsd, warnings: held.warnings }, { status: "held-by-cap", estimateUsd: 4, warnings: ["rumble is cooling down"] }); assert.deepEqual(made, []); const updated = await runTick("auto", { trigger: "now", jobId: "j3" }, depsOf(paths, steps({ status: "done", usd: 1.1, iteration: 4 }), NOW, extra), ctx()); assert.equal(updated.status, "done"); assert.deepEqual(made, ["auto/4"]); // A living report with a report: the refresh runs its own stage 1. assert.deepEqual(fetchCalls, []); await createSchedule(parseCreate({ shape: "series", topic: "Wired", channels: ["chan-a", "chan-b"], cadence: weekly, tz: TZ }), depsOf(paths)); const series = await runTick("wired", { trigger: "now", jobId: "j4" }, depsOf(paths, { ...steps({ status: "no-change", usd: 0 }), generateEdition: async () => ({ status: "done", usd: 0.5, iteration: 1 }) }), ctx()); assert.deepEqual(fetchCalls, [{ channels: ["chan-a", "chan-b"], from: "2026-10-07", to: "2026-10-13" }]); assert.deepEqual({ status: series.status, warnings: series.warnings }, { status: "done", warnings: ["youtube is held: skipped"] }); assert.deepEqual((await readSchedule("wired", paths))?.ticks.at(-1)?.warnings, ["youtube is held: skipped"]); // At once again: nothing to cover, nothing fetched. await runTick("wired", { trigger: "now", jobId: "j5" }, depsOf(paths, steps({ status: "no-change", usd: 0 })), ctx()); assert.equal(fetchCalls.length, 1); }); // ─── R6: triage first, and the watch ─── import { escalationCapRefusal, triageStep, type EditionInput, type TriageStepInput, type TriageStepOutcome } from "./reportTick"; import { TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, type TriageFile, type TriageFlag } from "../lib/report/draft/triage/types"; const flag = (id: string, strength: "strong" | "weak", f = "f1"): TriageFlag => ({ f, id, channel: "chan-a", title: id, date: "2026-10-13", window: { start: 0, end: 30 }, line: `a line of ${id} the judge flagged`, at: 5, score: strength === "strong" ? 3 : 2, strength, reason: `why ${id}`, checked: "cues", }); function triageFile(owner: string, k: number, flags: TriageFlag[], o: Partial = {}): TriageFile { const threshold = { strong: 1, weak: 3 }; return { format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner, k, status: "done", model: "qwen3:8b", provider: "local", question: "Q?", scope: { channels: ["chan-a"] }, terms: "co-host", regex: false, topics: [], threshold, since: "2026-10-07", knownCount: 10, createdAt: NOW.toISOString(), tier0: { candidates: [...new Set(flags.map((f) => f.id)), "quiet-1"].map((id) => ({ id, channel: "Chan A", title: id, date: "2026-10-13", matches: 1, by: ["terms"] })), scanned: 12, newCount: 3, cut: [], partial: false, unreached: [], perQuery: [], newBy: "id" }, tier1: { model: "qwen3:8b", flags, dismissed: [{ id: "quiet-1", stage: "judge", reason: "not relevant to the question" }], read: 2, windows: 2, chunks: 2, usd: 0 }, escalation: escalationOf(flags, threshold), cost: { tier0: 0, tier1: 0 }, summary: "summary", warnings: [], ...o, }; } /** A triage step over a canned triage.json, recording what it was asked. */ function triageOf(flags: TriageFlag[], asked: TriageStepInput[] = [], o: Partial = {}): NonNullable { let k = 0; return async (input): Promise => { asked.push(input); return { status: "done", file: triageFile(input.schedule.id, ++k, flags, o), jobId: `tj${k}` }; }; } test("a watch: create (no article, its plan names the triage), then a tick below the threshold ends no-change, $0, its triage on the line", async () => { const paths = store(); const deps = depsOf(paths); const plan = await reportScheduleAction({ action: "create", dryRun: true, shape: "watch", topic: "Co-host watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", topics: ["guest"], threshold: { strong: 1, weak: 2 } }, deps); assert.equal(plan.ok, true, JSON.stringify(plan)); assert.deepEqual(plan.plan.triage, { model: "qwen3:8b", provider: "local", threshold: { strong: 1, weak: 2 }, thresholdWords: "1 strong or 2 weak", maxEscalationsPerDay: 3, topics: ["guest"], terms: "co-host" }); assert.equal(plan.plan.article, null); assert.equal(plan.plan.firstWindow, null); const made = await reportScheduleAction({ action: "create", shape: "watch", topic: "Co-host watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", topics: ["guest"], threshold: { strong: 1, weak: 2 } }, deps); assert.equal(made.ok, true, JSON.stringify(made)); assert.ok(existsSync(seriesFile(paths, "co-host-watch"))); assert.deepEqual(made.schedule.scope.topics, ["guest"]); assert.deepEqual(made.schedule.triage, { threshold: { strong: 1, weak: 2 } }); const asked: TriageStepInput[] = []; const editions: EditionInput[] = []; const fetched: unknown[] = []; const tick = await runTick( "co-host-watch", { trigger: "now", jobId: "w1" }, depsOf(paths, { fetchAndBuild: async (scope) => (fetched.push(scope), { ok: true }), triage: triageOf([flag("v1", "weak")], asked), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 1, iteration: 1 }) }), ctx(), ); assert.deepEqual(fetched, [{ channels: ["chan-a"] }]); assert.deepEqual(asked[0]!.scope, { channels: ["chan-a"] }); // No last run: "new" counts from the cadence's length back. assert.equal(asked[0]!.since, "2026-10-07"); assert.equal(tick.status, "no-change"); assert.equal(tick.usd, 0); assert.match(tick.reason!, /^triage: 0 strong flags, 1 weak flag \(threshold: 1 strong or 3 weak\) — below the threshold, nothing escalated$/); assert.deepEqual({ k: tick.triage!.k, candidates: tick.triage!.candidates, flagged: tick.triage!.flagged, escalated: tick.triage!.escalated }, { k: 1, candidates: 2, flagged: 1, escalated: false }); assert.equal(editions.length, 0); }); test("a watch escalates: an API sweep of the flagged ids as -, the triage named; usd is tier 1 + tier 2; the day's escalation cap holds the next", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "watch", topic: "Watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths)); const editions: EditionInput[] = []; const steps = (): Partial => ({ triage: triageOf([flag("v1", "strong"), flag("v2", "weak", "f2"), flag("v1", "weak", "f3")], [], { cost: { tier0: 0, tier1: 0.02 } }), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 0.9, iteration: 1, jobId: "sweep-1" }), }); const gen1 = () => ({ generation: gen({ triage: { maxEscalationsPerDay: 1 } }) }); const tick = await runTick("watch", { trigger: "now", jobId: "w1" }, depsOf(paths, steps(), NOW, { settings: gen1 }), ctx()); assert.equal(tick.status, "done", tick.reason); assert.equal(tick.article, "watch-2026-10-14"); assert.equal(tick.iteration, 1); assert.equal(tick.usd, 0.92); assert.deepEqual(editions[0]!.ids, ["v1", "v2"]); assert.deepEqual(editions[0]!.triage, { owner: "watch", k: 1 }); assert.equal(editions[0]!.title, "Watch · 2026-10-14"); assert.equal(editions[0]!.quietCheck, false); assert.deepEqual({ escalated: tick.triage!.escalated, ids: tick.triage!.ids, usd: tick.triage!.usd }, { escalated: true, ids: ["v1", "v2"], usd: { tier1: 0.02, tier2: 0.9 } }); assert.equal(tick.triage!.top[0]!.score, 3); // The cap: one escalation a day, and one ran. assert.match((await escalationCapRefusal(paths, NOW, 1))!, /the day's escalation cap is reached: 1 escalation today \(2026-10-14, UTC\), the cap 1/); assert.equal(await escalationCapRefusal(paths, NOW, 0), null); const held = await runTick("watch", { trigger: "now", jobId: "w2" }, depsOf(paths, steps(), NOW, { settings: gen1 }), ctx()); assert.equal(held.status, "held-by-cap"); assert.match(held.reason!, /escalation cap is reached/); assert.equal(held.triage!.escalated, false); assert.match(held.triage!.capped!, /escalation cap/); assert.equal(editions.length, 1); }); test("triage first: a series below the threshold is a quiet edition ($0); above, its edition sweeps the flagged ids (no window check); a living report's refresh reads them with no second fetch", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Tri", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths)); const editions: EditionInput[] = []; const quiet = await runTick("tri", { trigger: "now", jobId: "s1" }, depsOf(paths, { triage: triageOf([]), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 1, iteration: 1 }) }), ctx()); assert.equal(quiet.status, "quiet"); assert.equal(quiet.edition, 1); const s1 = (await readSchedule("tri", paths))!; assert.deepEqual({ status: s1.editions![0]!.status, window: s1.editions![0]!.window }, { status: "quiet", window: { from: "2026-10-07", to: "2026-10-13" } }); assert.equal(editions.length, 0); // A week on: one strong flag, the edition sweeps it. const later = new Date("2026-10-21T12:00:00.000Z"); const made = await runTick("tri", { trigger: "now", jobId: "s2" }, depsOf(paths, { triage: triageOf([flag("late-old", "strong")]), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 0.7, iteration: 1 }) }, later), ctx()); assert.equal(made.status, "done", made.reason); assert.deepEqual({ ids: editions[0]!.ids, quietCheck: editions[0]!.quietCheck, window: editions[0]!.window }, { ids: ["late-old"], quietCheck: false, window: { from: "2026-10-14", to: "2026-10-20" } }); await createSchedule(parseCreate({ shape: "living", topic: "Live tri", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths)); await doneIteration(paths, "live-tri"); const refreshed: Record[] = []; const fetched: unknown[] = []; const living = await runTick( "live-tri", { trigger: "now", jobId: "l1" }, depsOf(paths, { fetchAndBuild: async (sc) => (fetched.push(sc), { ok: true }), triage: triageOf([flag("v9", "strong")]), refresh: async (_a, o) => (refreshed.push(o), { status: "done", usd: 0.5, iteration: 2 }) }), ctx(), ); assert.equal(living.status, "done"); assert.deepEqual(fetched, [{ channels: ["chan-a"] }]); assert.deepEqual(refreshed, [{ ids: ["v9"], fetch: false }]); const below = await runTick("live-tri", { trigger: "now", jobId: "l2" }, depsOf(paths, { triage: triageOf([]), refresh: async () => assert.fail("below the threshold: no refresh") }), ctx()); assert.deepEqual({ status: below.status, usd: below.usd }, { status: "no-change", usd: 0 }); }); test("triageStep: report-draft triage for the schedule (its terms, topics, threshold, since), awaited; its triage.json is the outcome", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "watch", topic: "Step", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", regex: true, topics: ["guest"], threshold: { strong: 2, weak: 4 } }), depsOf(paths)); const s = (await readSchedule("step", paths))!; const asked: Record[] = []; const draft = { paths, corpusTools: async () => assert.fail("no corpus") }; const step = triageStep(draft as never, { enqueueReportDraft: (async (b: Record) => (asked.push(b), { result: okJob("tj"), iteration: 3 })) as never, readTriageFile: (async (owner: string, k: number) => triageFile(owner, k, [flag("v1", "strong")])) as never, }); const out = await step({ schedule: s, scope: { channels: ["chan-a"] }, since: "2026-10-07" }, ctx()); assert.deepEqual(asked[0], { task: "triage", article: "step", question: "Step", channels: ["chan-a"], terms: "co-host", regex: true, topics: ["guest"], threshold: { strong: 2, weak: 4 }, since: "2026-10-07" }); assert.deepEqual({ status: out.status, k: out.file?.k, jobId: out.jobId }, { status: "done", k: 3, jobId: "tj" }); const refused = await triageStep(draft as never, { enqueueReportDraft: (async () => ({ result: { ok: false, error: "no composed build holds chan-a" } })) as never })({ schedule: s, scope: { channels: ["chan-a"] }, since: null }, ctx()); assert.deepEqual({ status: refused.status, reason: refused.reason }, { status: "failed", reason: "the triage could not start: no composed build holds chan-a" }); }); // ─── R6.1: no silent zeros; recovering a bad run ─── import { callOf } from "../lib/report/schedule/types"; import { planResetTriage, resetTriage } from "./reportSchedule"; import { createTriageRun, listTriageRuns, readTriageSeen, writeTriageSeen } from "../lib/report/draft/triage/store"; import { TRIAGE_SEEN_FORMAT } from "../lib/report/draft/triage/types"; const partialTier0 = (flags: TriageFlag[]) => ({ tier0: { ...triageFile("x", 1, flags).tier0!, partial: true, unreached: ["Jeremy Hambly", "TheQuartering (Rumble)"], }, }); test("R6.1: a partial triage below the threshold is never quiet — a series' tick is partial (the operator's call), no edition covers its window; above it escalates with a warning", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Pilot", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths)); const t = await runTick("pilot", { trigger: "now", jobId: "p1" }, depsOf(paths, { triage: triageOf([], [], partialTier0([])), generateEdition: async () => assert.fail("below the threshold: no sweep") }), ctx()); assert.equal(t.status, "partial"); assert.equal(t.usd, 0); assert.equal(t.edition, undefined); assert.match(t.reason!, /^partial — not reached: Jeremy Hambly, TheQuartering \(Rumble\); nothing flagged in what was read \(no flag/); assert.equal(t.triage!.partial, "not reached: Jeremy Hambly, TheQuartering (Rumble)"); const s = (await readSchedule("pilot", paths))!; assert.deepEqual(s.editions, [], "the window is not covered: the next tick covers it"); assert.equal(callOf(s)?.status, "partial", "a Your call card"); // The next window still starts where the first would have. assert.deepEqual(editionWindow(s, "2026-10-21"), { window: { from: "2026-10-14", to: "2026-10-20" } }); const later = new Date("2026-10-21T12:00:00.000Z"); assert.deepEqual(editionWindow(s, "2026-10-14"), { window: { from: "2026-10-07", to: "2026-10-13" } }); // A watch, partial and above the threshold: the escalation runs, the partial said. await createSchedule(parseCreate({ shape: "watch", topic: "Pw", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths)); const w = await runTick("pw", { trigger: "now", jobId: "p2" }, depsOf(paths, { triage: triageOf([flag("v1", "strong")], [], partialTier0([flag("v1", "strong")])), generateEdition: async () => ({ status: "done", usd: 0.4, iteration: 1 }) }, later), ctx()); assert.equal(w.status, "done", w.reason); assert.ok(w.warnings?.some((x) => /the triage was partial \(not reached: Jeremy Hambly/.test(x)), JSON.stringify(w.warnings)); // A living report, partial and below: partial, not no-change. await createSchedule(parseCreate({ shape: "living", topic: "Pl", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths)); await doneIteration(paths, "pl"); const l = await runTick("pl", { trigger: "now", jobId: "p3" }, depsOf(paths, { triage: triageOf([], [], partialTier0([])), refresh: async () => assert.fail("no refresh") }), ctx()); assert.equal(l.status, "partial"); }); test("R6.1: the window check — 0 from a capped scan is partial (not quiet), naming what it did not reach; a capped scan with matches still sweeps", async () => { const paths = store(); await createSchedule(parseCreate({ shape: "series", topic: "Win", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths)); const s = (await readSchedule("win", paths))!; const draft = { paths, corpusTools: async () => assert.fail("no corpus read"), settings: () => ({ generation: gen() }), now: () => NOW }; const input = { schedule: s, article: "win-2026-10-14", title: "Win · week of 2026-10-07", window: { from: "2026-10-07", to: "2026-10-13" }, quietCheck: true }; const part = await editionGenerator({ draft, countWindow: async () => ({ recordings: 0, partial: true, unreached: ["Chan B"] }) })(input, ctx()); assert.equal(part.status, "partial"); assert.match(part.reason!, /^partial — the window check of 2026-10-07 … 2026-10-13 was capped \(not reached: Chan B\)/); // Through the tick: partial, no quiet edition. const t = await runTick("win", { trigger: "now", jobId: "w1" }, depsOf(paths, { generateEdition: async () => part }), ctx()); assert.equal(t.status, "partial"); assert.deepEqual((await readSchedule("win", paths))!.editions, []); // With matches the capped check does not stop the edition (held here by the daily cap, past the check). writeFileSync(paths.generationUsageFile, JSON.stringify({ at: NOW.toISOString(), day: "2026-10-14", jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }) + "\n"); const some = await editionGenerator({ draft, countWindow: async () => ({ recordings: 2000, partial: true, unreached: ["Chan B"] }) })(input, ctx()); assert.equal(some.status, "held-by-cap"); assert.equal(some.matched, 2000); }); test("R6.1: r4Steps — a refresh that ended partial is a partial tick; a routine skip is not a warning, a cancelled step is", async () => { const paths = store(); await doneIteration(paths, "shop"); const draft = { paths, corpusTools: async () => assert.fail("no corpus") }; const steps = r4Steps(draft as never, { fetchScope: async () => ({ fetch: [ { channel: "chan-a", action: "sync", status: "done", jobId: "j1" }, { channel: "chan-a", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe", routine: true }, { channel: "chan-b", action: "transcribe-bucket", status: "skipped", reason: "transcription is paused (no transcription worker is enabled) — 7 recordings wait; a later run reads them once transcribed" }, ], build: { site: "site-x", status: "done" }, warnings: ["chan-c: sync cancelled — the job ended cancelled"], }), enqueueReportDraft: (async () => ({ result: okJob("rj"), iteration: 2 })) as never, readRefreshFile: (async () => ({ status: "partial", summary: "partial — not reached: Chan B; Nothing new since 2026-10-07 in what was read", warnings: [], fetch: [] })) as never, }); const f = await steps.fetchAndBuild({ channels: ["chan-a", "chan-b"] }, ctx()); assert.deepEqual(f.warnings, [ "chan-c: sync cancelled — the job ended cancelled", "chan-b transcribe-bucket: transcription is paused (no transcription worker is enabled) — 7 recordings wait; a later run reads them once transcribed", ]); const r = await steps.refresh("shop", {}, ctx()); assert.equal(r.status, "partial"); assert.match(r.reason!, /^partial — not reached: Chan B/); }); test("R6.1: reset-triage — the plan names the runs, seen.json and the quiet editions they covered; refused while a tick runs; confirm discards them", async () => { const paths = store(); const deps = depsOf(paths); await createSchedule(parseCreate({ shape: "series", topic: "Bad run", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), deps); // Tick 1: a triage (run 1, its seen.json) and a quiet edition. const quiet = await runTick("bad-run", { trigger: "now", jobId: "b1" }, depsOf(paths, { triage: triageOf([]) }), ctx()); assert.equal(quiet.status, "quiet"); const mk = (k: number) => triageFile("bad-run", k, []); await createTriageRun(mk, paths, "bad-run"); await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "bad-run", k: 1, at: NOW.toISOString(), ids: ["a", "b", "c"] }, paths); const plan = await reportScheduleAction({ action: "reset-triage", id: "bad-run" }, deps); assert.equal(plan.ok, true, JSON.stringify(plan)); assert.equal(plan.confirmed, false); assert.deepEqual(plan.plan.runs, [1]); assert.deepEqual(plan.plan.seen, { k: 1, ids: 3 }); assert.equal(plan.plan.seenRemoved, true); assert.deepEqual(plan.plan.editions.map((e: { n: number }) => e.n), [1]); assert.match(plan.plan.removes.join(" | "), /1 triage run \(#1\) in \.triage\/bad-run\/ \| seen\.json — the 3 recording ids run #1 counted as known .* \| 1 quiet edition line those runs covered \(2026-10-07 … 2026-10-13\)/); assert.equal(plan.plan.refused, null); // Nothing was written by the plan. assert.deepEqual(await listTriageRuns("bad-run", paths), [1]); // Refused while a tick runs. await claimTick("bad-run", { jobId: "busy", trigger: "now" }, deps); assert.match((await planResetTriage("bad-run", null, deps)).refused!, /a tick is queued or running \(job busy\)/); const refused = await reportScheduleAction({ action: "reset-triage", id: "bad-run", confirm: true }, deps); assert.equal(refused.ok, false); const { releaseClaim } = await import("./reportSchedule"); await releaseClaim("bad-run", "busy", deps); const done = await reportScheduleAction({ action: "reset-triage", id: "bad-run", confirm: true }, deps); assert.equal(done.ok, true, JSON.stringify(done)); assert.equal(done.confirmed, true); assert.deepEqual(await listTriageRuns("bad-run", paths), []); assert.equal(await readTriageSeen("bad-run", paths), null); const s = (await readSchedule("bad-run", paths))!; assert.deepEqual(s.editions, []); assert.equal(s.ticks.length, 1, "the tick log keeps its lines"); // The next window is the one the discarded edition covered. assert.deepEqual(editionWindow(s, "2026-10-14"), { window: { from: "2026-10-07", to: "2026-10-13" } }); // Nothing left: the plan refuses; a bad k is an input error. assert.match(((await resetTriage("bad-run", null, deps).catch((e: Error) => e)) as Error).message, /has no triage state to discard/); const badK = await reportScheduleAction({ action: "reset-triage", id: "bad-run", k: 0 }, deps); assert.equal(badK.ok, false); assert.match(badK.error, /"k" is a triage run's number/); });