// A RECURRING REPORT'S SCHEDULE — THE ONE WRITER (umtool R5; plans/umtool- // redesign.md "R5 — Recurring reports"). Every write of a schedule is here: // create, update, pause/resume, delete, and the tick's own bookkeeping (the // claim that a tick is queued, its record when it ends, an edition's line). // Each is a read-patch-write under the article store's lock // (lib/report/registry.ts withArticleStoreLock), validated, and written whole // and atomically; lib/report/schedule/store.ts says where. The ops action // (`pnpm ops report-schedule`, controller/reportScheduleOps.ts) and the // editor's runner are its only callers; umtool reads the files and writes // through the ops action. // // A tick's own work is controller/reportTick.ts; when a tick is due is // lib/report/schedule/cadence.ts. import { mkdir, rm, stat } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { withArticleStoreLock, RESERVED_ARTICLE_IDS, ARTICLE_ITERATIONS_DIRNAME } from "../lib/report/registry"; import { isReportId } from "../lib/report/schema"; import { capFor, triageModelOf, type GenerationSettings } from "../lib/generationSettings"; import { thresholdWords } from "../lib/report/draft/triage/types"; import { listTriageRuns, readTriageSeen, triageOwnerDir, triageRunDir, triageSeenPath } from "../lib/report/draft/triage/store"; import { providerOf } from "../lib/llm"; import { CadenceError, anchorFor, cadenceWords, isTimeZone, localDate, localTimeZone, nextTickAfter, parseCadence, tickWords, type Cadence, } from "../lib/report/schedule/cadence"; import { OFFERED_SHAPES, SCHEDULE_FORMAT, SCHEDULE_ID_RE, SCHEDULE_VERSION, TICKS_KEPT, editionTitle, editionWindow, parseSchedule, type Edition, type Schedule, type ScheduleShape, type Tick, } from "../lib/report/schedule/types"; import { livingFile, readScheduleById, scheduleFile, seriesDir, seriesFile, type SchedulePaths, } from "../lib/report/schedule/store"; export class ScheduleInputError extends Error {} // A claim taken before its job's id is known (controller/reportTick.ts // enqueueTick), moved onto the job as soon as it is. export const PENDING_PREFIX = "pending-"; export type ScheduleDeps = { paths: SchedulePaths & Partial>; now?: () => Date; settings?: () => { generation: GenerationSettings }; // The channels a scope may name (the editor's); absent: not checked. knownChannels?: () => Promise; }; const nowOf = (deps: ScheduleDeps) => deps.now?.() ?? new Date(); const fail = (msg: string): never => { throw new ScheduleInputError(msg); }; // ─── the model and the cap a tick runs on ─── /** * The model a tick's generation runs on: the schedule's, else the sweep * route's — a sweep routed to Claude Code runs the API model here (a * schedule runs in the editor; R4's refresh says the same). */ export function tickModel(gen: GenerationSettings, s: { model?: string; caps?: { maxUsd?: number } }): { model: string; provider: "api" | "local"; capUsd: number | null; note?: string } { const route = gen.routes.sweep; const model = s.model ?? (route === "local" ? gen.models.local : gen.models.api); const provider = providerOf(model) === "local" ? "local" : "api"; return { model, provider, capUsd: provider === "api" ? capFor(gen.caps, "sweep", s.caps?.maxUsd) : null, ...(!s.model && route === "code" ? { note: "sweeps are routed to Claude Code: a tick runs the API model here" } : {}), }; } // ─── ids ─── export function slugOf(text: string, max = 48): string { const s = text .toLowerCase() .normalize("NFKD") .replace(/[^\p{L}\p{N}]+/gu, "-") .replace(/[^a-z0-9-]/g, "") .replace(/-+/g, "-") .replace(/^-|-$/g, ""); return (s.slice(0, max).replace(/-$/, "") || "report").replace(/^[^a-z0-9]+/, "") || "report"; } const exists = (p: string) => stat(p).then(() => true, () => false); async function idTaken(paths: SchedulePaths, id: string): Promise { return (await exists(seriesFile(paths, id))) || (isReportId(id) && (await exists(livingFile(paths, id)))); } /** A free id from `base`: itself, else base-2, base-3, … */ async function freeId(base: string, taken: (id: string) => Promise): Promise { for (let k = 1; k < 1000; k++) { const id = k === 1 ? base : `${base.slice(0, 44)}-${k}`; if (!(await taken(id))) return id; } return fail(`no free id near "${base}"`); } // ─── create ─── export type CreateInput = { shape: ScheduleShape; topic: string; question?: string; id?: string; article?: string; channels: string[]; case?: string; from?: string; terms?: string; regex?: boolean; cadence: Cadence; tz: string; autoMakeCurrent?: boolean; model?: string; maxUsd?: number; // umtool R6: triage first (living, series; a watch always triages), its // digest topics and its own threshold. triageFirst?: boolean; topics?: string[]; threshold?: { strong: number; weak: number }; }; const ymdRe = /^\d{4}-\d{2}-\d{2}$/; /** The create body, judged without touching the disk. */ export function parseCreate(b: Record): CreateInput { const shape = b.shape; if (typeof shape !== "string" || !(OFFERED_SHAPES as readonly string[]).includes(shape)) fail(`"shape" is one of ${OFFERED_SHAPES.join(", ")}`); const text = (k: string) => { const v = b[k]; if (v === undefined || v === null || v === "") return undefined; if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); return (v as string).trim(); }; const topic = text("topic") ?? text("question"); if (!topic) fail('a recurring report needs its "topic" (or "question")'); const channels = b.channels === undefined ? [] : typeof b.channels === "string" ? b.channels.split(",") : b.channels; if (!Array.isArray(channels) || !channels.every((c) => typeof c === "string" && c.trim())) fail('"channels" is a list of channel slugs'); const chans = [...new Set((channels as string[]).map((c) => c.trim()))]; if (!chans.length) fail('a recurring report needs its scope: "channels" (a board\'s, or named)'); const from = text("from"); if (from !== undefined && !ymdRe.test(from)) fail('"from" is a YYYY-MM-DD date'); let cadence: Cadence; try { cadence = parseCadence(b.cadence ?? (b.at ? { kind: "daily", at: b.at } : undefined)); } catch (e) { return fail((e as Error).message); } const tz = text("tz") ?? localTimeZone(); if (!isTimeZone(tz)) fail(`"tz" is a time zone this editor knows (an IANA name such as Europe/London): not ${JSON.stringify(tz)}`); const id = text("id"); if (id !== undefined && !SCHEDULE_ID_RE.test(id)) fail('"id" is a lowercase slug, at most 48 characters'); const article = text("article"); if (article !== undefined) { if (shape !== "living") fail('"article" is a living report\'s: a series makes an article per edition'); if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) fail(`"article" is an article id (a lowercase slug): not ${JSON.stringify(article)}`); } if (b.autoMakeCurrent !== undefined && typeof b.autoMakeCurrent !== "boolean") fail('"autoMakeCurrent" is true or false'); if (b.autoMakeCurrent === true && shape !== "living") fail('"autoMakeCurrent" is a living report\'s (an edition is its own article)'); if (b.regex !== undefined && typeof b.regex !== "boolean") fail('"regex" is true or false'); let maxUsd: number | undefined; if (b.maxUsd !== undefined && b.maxUsd !== null) { if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars'); maxUsd = b.maxUsd as number; } if (b.triageFirst !== undefined && typeof b.triageFirst !== "boolean") fail('"triageFirst" is true or false'); if (b.triageFirst === true && shape === "watch") fail('a watch always triages first: "triageFirst" is a living report\'s or a series\''); const topics = parseTopics(b.topics); const threshold = parseThreshold(b.threshold); return { shape: shape as ScheduleShape, topic: topic!, ...(text("question") ? { question: text("question") } : {}), ...(id ? { id } : {}), ...(article ? { article } : {}), channels: chans, ...(text("case") ? { case: text("case") } : {}), ...(from ? { from } : {}), ...(text("terms") ? { terms: text("terms") } : {}), ...(b.regex === true ? { regex: true } : {}), cadence: cadence!, tz, ...(b.autoMakeCurrent === true ? { autoMakeCurrent: true } : {}), ...(text("model") ? { model: text("model") } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), ...(b.triageFirst === true ? { triageFirst: true } : {}), ...(topics?.length ? { topics } : {}), ...(threshold ? { threshold } : {}), }; } /** A triage's digest topics: a list (or a comma-separated text) of tags. */ function parseTopics(v: unknown): string[] | undefined { if (v === undefined || v === null || v === "") return undefined; const arr = typeof v === "string" ? v.split(",") : v; if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string")) fail('"topics" is a list of digest topic tags'); const out = [...new Set((arr as string[]).map((x) => x.trim()).filter(Boolean))]; if (out.some((x) => x.length > 80)) fail('a topic is at most 80 characters'); return out.slice(0, 20); } /** A schedule's own triage threshold: {strong, weak}, whole numbers 0–50. */ function parseThreshold(v: unknown): { strong: number; weak: number } | undefined { if (v === undefined || v === null) return undefined; const t = v as Record; const ok = (x: unknown) => typeof x === "number" && Number.isInteger(x) && x >= 0 && x <= 50; if (!t || typeof t !== "object" || Array.isArray(t) || !ok(t.strong) || !ok(t.weak)) fail('"threshold" is {"strong": n, "weak": n}: whole numbers 0–50 (0: that rule off)'); return { strong: t.strong as number, weak: t.weak as number }; } export type SchedulePlan = { id: string; shape: ScheduleShape; topic: string; question: string; article: string | null; channels: string[]; cadence: string; tz: string; firstTick: string; firstTickWords: string; // A series' first window (the cadence's length back from the first tick's date). firstWindow: { from: string; to: string } | null; firstTitle: string | null; model: string; provider: "api" | "local"; capUsd: number | null; dailyCapUsd: number; existingArticle: boolean; // Triage first (umtool R6): its model, threshold and the day's escalation cap; null: none. triage: { model: string; provider: "api" | "local"; threshold: { strong: number; weak: number }; thresholdWords: string; maxEscalationsPerDay: number; topics: string[]; terms: string | null } | null; warnings: string[]; }; async function articleExists(paths: SchedulePaths, id: string): Promise { const dir = path.join(paths.articlesDir, id); return (await exists(path.join(dir, "report.json"))) || (await exists(path.join(dir, ARTICLE_ITERATIONS_DIRNAME))); } /** What create would make, nothing written. */ export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promise<{ plan: SchedulePlan; schedule: Schedule }> { const paths = deps.paths; const now = nowOf(deps); const warnings: string[] = []; if (deps.knownChannels) { const known = new Set(await deps.knownChannels()); const unknown = input.channels.filter((c) => !known.has(c)); if (unknown.length) fail(`no such channel${unknown.length === 1 ? "" : "s"} in this editor: ${unknown.join(", ")}`); } let id: string; let article: string | null = null; let existingArticle = false; if (input.shape === "living") { if (input.article) { article = input.article; existingArticle = await articleExists(paths, article); if (await exists(livingFile(paths, article))) fail(`"${article}" is a living report already: update its schedule instead`); if (await exists(seriesFile(paths, article))) fail(`"${article}" is a series' id`); } else { const base = slugOf(input.id ?? input.topic, 60); if (RESERVED_ARTICLE_IDS.includes(base)) fail(`"${base}" is reserved: name the article`); article = await freeId(base, async (x) => (await articleExists(paths, x)) || (await idTaken(paths, x)) || RESERVED_ARTICLE_IDS.includes(x)); } id = article; } else if (input.id) { if (await idTaken(paths, input.id)) fail(`"${input.id}" is taken: a schedule has that id`); id = input.id; } else { // Room for an edition's "-YYYY-MM-DD(-n)" in a 64-character article id. id = await freeId(slugOf(input.topic, 48), (x) => idTaken(paths, x)); } const gen = deps.settings?.().generation; const m = gen ? tickModel(gen, { ...(input.model ? { model: input.model } : {}), ...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}) }) : null; if (m?.note) warnings.push(m.note); if (input.shape === "series" && !input.terms && !input.triageFirst) warnings.push("no terms: a window is quiet only when no recording in scope falls in it"); const triaged = input.shape === "watch" || input.triageFirst === true; if (triaged && !input.terms && !input.topics?.length) warnings.push(`no terms or topics: every new recording in scope is a candidate (up to ${gen?.triage.maxCandidates ?? 40} a tick)`); const first = nextTickAfter(input.cadence, now.getTime(), input.tz, null); const anchor = anchorFor(input.cadence, first, input.tz); const fw = editionWindow({ cadence: input.cadence, editions: [], scope: { channels: input.channels, ...(input.from ? { from: input.from } : {}) } }, localDate(first, input.tz)); const firstWindow = input.shape === "series" && "window" in fw ? fw.window : null; const threshold = input.threshold ?? (gen ? { strong: gen.triage.strong, weak: gen.triage.weak } : { strong: 1, weak: 3 }); const triageModel = gen ? triageModelOf(gen) : ""; const at = now.toISOString(); const schedule: Schedule = { format: SCHEDULE_FORMAT, version: SCHEDULE_VERSION, id, shape: input.shape, topic: input.topic, question: input.question ?? input.topic, ...(article ? { article } : {}), scope: { channels: input.channels, ...(input.case ? { case: input.case } : {}), ...(input.from ? { from: input.from } : {}), ...(input.terms ? { terms: input.terms } : {}), ...(input.regex ? { regex: true } : {}), ...(input.topics?.length ? { topics: input.topics } : {}), }, cadence: input.cadence, tz: input.tz, anchor, paused: false, ...(input.shape === "living" ? { autoMakeCurrent: input.autoMakeCurrent === true } : {}), ...(input.model ? { model: input.model } : {}), ...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}), ...(input.triageFirst ? { triageFirst: true } : {}), ...(input.threshold ? { triage: { threshold: input.threshold } } : {}), createdAt: at, updatedAt: at, lastTick: null, nextTick: new Date(first).toISOString(), running: null, ticks: [], ...(input.shape === "series" ? { editions: [] } : {}), }; const checked = parseSchedule(schedule); if (!checked.ok) fail(`the schedule does not validate: ${checked.problems.join("; ")}`); return { schedule, plan: { id, shape: input.shape, topic: input.topic, question: schedule.question, article, channels: input.channels, cadence: cadenceWords(input.cadence), tz: input.tz, firstTick: schedule.nextTick!, firstTickWords: tickWords(first, input.tz, now.getTime()), firstWindow, firstTitle: firstWindow ? editionTitle(input.topic, input.cadence, firstWindow) : null, model: m?.model ?? input.model ?? "", provider: m?.provider ?? (input.model && providerOf(input.model) === "local" ? "local" : "api"), capUsd: m?.capUsd ?? null, dailyCapUsd: gen?.caps.daily ?? 0, existingArticle, triage: triaged ? { model: triageModel, provider: triageModel && providerOf(triageModel) === "local" ? "local" : "api", threshold, thresholdWords: thresholdWords(threshold), maxEscalationsPerDay: gen?.triage.maxEscalationsPerDay ?? 0, topics: input.topics ?? [], terms: input.terms ?? null, } : null, warnings, }, }; } /** Make the schedule (the operator's act: nothing else creates one). */ export async function createSchedule(input: CreateInput, deps: ScheduleDeps): Promise<{ plan: SchedulePlan; schedule: Schedule }> { return withArticleStoreLock(async () => { const out = await planCreate(input, deps); const s = out.schedule; if (s.shape === "living") { // A new article is "in the making" from the start (store.ts). await mkdir(path.join(deps.paths.articlesDir, s.id, ARTICLE_ITERATIONS_DIRNAME), { recursive: true }); } else { await mkdir(seriesDir(deps.paths, s.id), { recursive: true }); } await writeJsonAtomic(scheduleFile(deps.paths, s.shape, s.id), s, { mkdir: true }); return out; }, deps.paths); } // ─── read-patch-write ─── export async function mutateSchedule(id: string, deps: ScheduleDeps, fn: (s: Schedule, now: Date) => Schedule | Promise): Promise { return withArticleStoreLock(async () => { const r = await readScheduleById(id, deps.paths); if (!r) fail(`no schedule "${id}"`); if (!r!.ok) fail(`the schedule "${id}" does not read (${r!.file}): ${(r as { problem: string }).problem}`); const now = nowOf(deps); const next = { ...(await fn((r as { schedule: Schedule }).schedule, now)), updatedAt: now.toISOString() }; const checked = parseSchedule(next); if (!checked.ok) fail(`the schedule "${id}" would not validate: ${checked.problems.join("; ")}`); await writeJsonAtomic(r!.file, next); return next; }, deps.paths); } export type UpdateInput = { topic?: string; question?: string; cadence?: Cadence; tz?: string; channels?: string[]; from?: string | null; terms?: string | null; regex?: boolean; autoMakeCurrent?: boolean; model?: string | null; maxUsd?: number | null; triageFirst?: boolean; topics?: string[] | null; threshold?: { strong: number; weak: number } | null; }; export function parseUpdate(b: Record): UpdateInput { const out: UpdateInput = {}; const text = (k: string) => { const v = b[k]; if (v === undefined) return undefined; if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); return (v as string).trim(); }; const orNull = (k: string) => (b[k] === null || b[k] === "" ? null : text(k)); if (b.topic !== undefined) out.topic = text("topic"); if (b.question !== undefined) out.question = text("question"); if (b.cadence !== undefined) { try { out.cadence = parseCadence(b.cadence); } catch (e) { fail((e as Error).message); } } if (b.tz !== undefined) { const tz = text("tz")!; if (!isTimeZone(tz)) fail(`"tz" is a time zone this editor knows: not ${JSON.stringify(tz)}`); out.tz = tz; } if (b.channels !== undefined) { const arr = typeof b.channels === "string" ? b.channels.split(",") : b.channels; if (!Array.isArray(arr) || !arr.length || !arr.every((c) => typeof c === "string" && c.trim())) fail('"channels" is a non-empty list of channel slugs'); out.channels = [...new Set((arr as string[]).map((c) => c.trim()))]; } if (b.from !== undefined) { const v = orNull("from"); if (v !== null && !ymdRe.test(v!)) fail('"from" is a YYYY-MM-DD date'); out.from = v ?? null; } if (b.terms !== undefined) out.terms = orNull("terms") ?? null; if (b.regex !== undefined) { if (typeof b.regex !== "boolean") fail('"regex" is true or false'); out.regex = b.regex as boolean; } if (b.autoMakeCurrent !== undefined) { if (typeof b.autoMakeCurrent !== "boolean") fail('"autoMakeCurrent" is true or false'); out.autoMakeCurrent = b.autoMakeCurrent as boolean; } if (b.model !== undefined) out.model = orNull("model") ?? null; if (b.maxUsd !== undefined) { if (b.maxUsd !== null && (typeof b.maxUsd !== "number" || !(b.maxUsd > 0))) fail('"maxUsd" is a positive number of dollars, or null'); out.maxUsd = b.maxUsd as number | null; } if (b.triageFirst !== undefined) { if (typeof b.triageFirst !== "boolean") fail('"triageFirst" is true or false'); out.triageFirst = b.triageFirst as boolean; } if (b.topics !== undefined) out.topics = b.topics === null || b.topics === "" ? null : (parseTopics(b.topics) ?? null); if (b.threshold !== undefined) out.threshold = b.threshold === null ? null : (parseThreshold(b.threshold) ?? null); if (!Object.keys(out).length) fail("nothing to change: send topic, question, cadence, tz, channels, from, terms, regex, autoMakeCurrent, model, maxUsd, triageFirst, topics or threshold"); return out; } /** Change a schedule. A new cadence or zone re-plans the next tick (and an every-N-days grid's anchor) from now. */ export async function updateSchedule(id: string, patch: UpdateInput, deps: ScheduleDeps): Promise { if (patch.channels && deps.knownChannels) { const known = new Set(await deps.knownChannels()); const unknown = patch.channels.filter((c) => !known.has(c)); if (unknown.length) fail(`no such channel${unknown.length === 1 ? "" : "s"} in this editor: ${unknown.join(", ")}`); } const gen = deps.settings?.().generation; if (gen && patch.maxUsd) capFor(gen.caps, "sweep", patch.maxUsd); return mutateSchedule(id, deps, (s, now) => { if (patch.autoMakeCurrent !== undefined && s.shape !== "living") fail('"autoMakeCurrent" is a living report\'s'); if (patch.triageFirst === true && s.shape === "watch") fail("a watch always triages first"); const cadence = patch.cadence ?? s.cadence; const tz = patch.tz ?? s.tz; const replan = patch.cadence !== undefined || patch.tz !== undefined; let nextTick = s.nextTick; let anchor = s.anchor ?? null; if (replan) { const t = nextTickAfter(cadence, now.getTime(), tz, null); anchor = anchorFor(cadence, t, tz); nextTick = new Date(t).toISOString(); } const scope = { ...s.scope }; if (patch.channels) scope.channels = patch.channels; if (patch.from !== undefined) { if (patch.from === null) delete scope.from; else scope.from = patch.from; } if (patch.terms !== undefined) { if (patch.terms === null) delete scope.terms; else scope.terms = patch.terms; } if (patch.regex !== undefined) scope.regex = patch.regex; if (patch.topics !== undefined) { if (patch.topics === null || !patch.topics.length) delete scope.topics; else scope.topics = patch.topics; } const next: Schedule = { ...s, cadence, tz, anchor, nextTick, scope }; if (patch.triageFirst !== undefined) { if (patch.triageFirst) next.triageFirst = true; else delete next.triageFirst; } if (patch.threshold !== undefined) { if (patch.threshold === null) delete next.triage; else next.triage = { ...(s.triage ?? {}), threshold: patch.threshold }; } if (patch.topic) next.topic = patch.topic; if (patch.question) next.question = patch.question; if (patch.autoMakeCurrent !== undefined) next.autoMakeCurrent = patch.autoMakeCurrent; if (patch.model !== undefined) { if (patch.model === null) delete next.model; else next.model = patch.model; } if (patch.maxUsd !== undefined) { if (patch.maxUsd === null) delete next.caps; else next.caps = { ...(s.caps ?? {}), maxUsd: patch.maxUsd }; } return next; }); } /** Pause or resume. A resume re-plans the next tick from now: the windows a pause skipped are not caught up. */ export async function setPaused(id: string, paused: boolean, deps: ScheduleDeps): Promise { return mutateSchedule(id, deps, (s, now) => { if (s.paused === paused) return s; if (paused) return { ...s, paused: true }; const t = nextTickAfter(s.cadence, now.getTime(), s.tz, s.anchor); return { ...s, paused: false, nextTick: new Date(t).toISOString() }; }); } // ─── delete ─── export type DeletePlan = { id: string; shape: ScheduleShape; file: string; // Words for the plan's head and its confirm. removes: string; keeps: string[]; refused: string | null; }; export async function planDelete(id: string, deps: ScheduleDeps): Promise { const r = await readScheduleById(id, deps.paths); if (!r) fail(`no schedule "${id}"`); if (!r!.ok) { // An unreadable file is still removable: say what it is. const shape: ScheduleShape = r!.file.endsWith("series.json") ? "series" : "living"; return { id, shape, file: r!.file, removes: `the unreadable schedule ${path.relative(deps.paths.articlesDir, r!.file)}`, keeps: [], refused: null }; } const s = (r as { schedule: Schedule }).schedule; const refused = s.running ? `a tick is ${s.running.trigger === "now" ? "queued or running" : "running"} (job ${s.running.jobId}) — cancel it or let it end first` : null; if (s.shape === "living") { return { id, shape: s.shape, file: r!.file, removes: `the schedule of ${s.article ?? s.id} (${cadenceWords(s.cadence)}, ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} recorded)`, keeps: [`the article ${s.article ?? s.id} and its iterations`], refused, }; } if (s.shape === "watch") { const found = [...new Set(s.ticks.filter((t) => t.article).map((t) => t.article!))]; return { id, shape: s.shape, file: r!.file, removes: `the watch ${s.id} (${cadenceWords(s.cadence)}): its schedule and ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} recorded`, keeps: [ ...(found.length ? [`${found.length} article${found.length === 1 ? "" : "s"} its escalations made, as articles: ${found.join(", ")}`] : []), `its triage runs (reports/.triage/${s.id}/) and the boards made from them`, ], refused, }; } const eds = (s.editions ?? []).filter((e) => e.article); const quiet = (s.editions ?? []).length - eds.length; return { id, shape: s.shape, file: r!.file, removes: `the series ${s.id} (${cadenceWords(s.cadence)}): its schedule, ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} and ${(s.editions ?? []).length} edition line${(s.editions ?? []).length === 1 ? "" : "s"}${quiet ? ` (${quiet} quiet)` : ""}`, keeps: eds.length ? [`${eds.length} edition article${eds.length === 1 ? "" : "s"}, as articles: ${eds.map((e) => e.article).join(", ")}`] : [], refused, }; } /** Delete a schedule. The plan is re-read under the lock; a refusal stands. */ export async function deleteSchedule(id: string, deps: ScheduleDeps): Promise { return withArticleStoreLock(async () => { const plan = await planDelete(id, deps); if (plan.refused) fail(plan.refused); if (plan.shape === "living") await rm(plan.file, { force: true }); else await rm(seriesDir(deps.paths, id), { recursive: true, force: true }); return plan; }, deps.paths); } // ─── reset a schedule's triage (R6.1: recovering a bad run) ─── export type ResetTriagePlan = { id: string; // The runs discarded (reports/.triage///), from run `from` on. dir: string; from: number | null; runs: number[]; // seen.json — what the next run counts as known — and whether it goes. seen: { k: number; ids: number } | null; seenRemoved: boolean; // A series' quiet editions those runs covered: dropped, so the next tick // covers their windows again. editions: { n: number; title: string; window: { from: string; to: string } }[]; // Words for the plan's head and its confirm. removes: string[]; keeps: string[]; refused: string | null; }; const planResetOf = async (s: Schedule, k: number | null, deps: ScheduleDeps): Promise => { const id = s.id; const all = await listTriageRuns(id, deps.paths); const from = k ?? all[0] ?? null; const runs = from === null ? [] : all.filter((n) => n >= from); const seenFile = await readTriageSeen(id, deps.paths); const seen = seenFile ? { k: seenFile.k, ids: seenFile.ids.length } : null; // seen.json is cumulative: a run from `from` on fed it, so it goes. const seenRemoved = !!seen && (from === null || seen.k >= from || k === null); const discarded = new Set(runs); const editionsOf = new Set(s.ticks.filter((t) => t.edition !== undefined && t.triage && discarded.has(t.triage.k)).map((t) => t.edition!)); const editions = (s.editions ?? []).filter((e) => e.status === "quiet" && editionsOf.has(e.n)).map((e) => ({ n: e.n, title: e.title, window: { from: e.window.from, to: e.window.to } })); const dir = path.relative(deps.paths.articlesDir, triageOwnerDir(deps.paths, id)); const removes = [ ...(runs.length ? [`${runs.length} triage run${runs.length === 1 ? "" : "s"} (${runs.map((n) => `#${n}`).join(", ")}) in ${dir}/`] : []), ...(seenRemoved && seen ? [`seen.json — the ${seen.ids} recording id${seen.ids === 1 ? "" : "s"} run #${seen.k} counted as known (the next run counts new from its since)`] : []), ...(editions.length ? [`${editions.length} quiet edition line${editions.length === 1 ? "" : "s"} those runs covered (${editions.map((e) => `${e.window.from} … ${e.window.to}`).join(", ")}): the next tick covers ${editions.length === 1 ? "that window" : "those windows"} again`] : []), ]; return { id, dir, from, runs, seen, seenRemoved, editions, removes, keeps: [ "the schedule, its cadence and its tick log (a discarded run's line stays, its link gone)", ...((s.editions ?? []).some((e) => e.article) ? ["every edition article"] : []), ...(from !== null && all.some((n) => n < from) ? [`the runs before #${from}`] : []), ], refused: s.running ? `a tick is ${s.running.trigger === "now" ? "queued or running" : "running"} (job ${s.running.jobId}) — cancel it or let it end first` : !runs.length && !seenRemoved ? `"${id}" has no triage state${k !== null ? ` from run #${k}` : ""} to discard` : null, }; }; /** What `reset-triage` would discard (nothing written). `k`: from that run on (default: every run). */ export async function planResetTriage(id: string, k: number | null, deps: ScheduleDeps): Promise { const r = await readScheduleById(id, deps.paths); if (!r) fail(`no schedule "${id}"`); if (!r!.ok) fail(`the schedule "${id}" does not read (${r!.file}): ${(r as { problem: string }).problem}`); return planResetOf((r as { schedule: Schedule }).schedule, k, deps); } /** * Discard a schedule's triage state (the plan, re-made under the lock; a * refusal stands): the runs from `k` on, seen.json when they fed it, and the * quiet edition lines they covered — so the next tick triages afresh. */ export async function resetTriage(id: string, k: number | null, deps: ScheduleDeps): Promise { let plan: ResetTriagePlan | null = null; await mutateSchedule(id, deps, async (s) => { plan = await planResetOf(s, k, deps); if (plan.refused) fail(plan.refused); for (const n of plan.runs) await rm(triageRunDir(deps.paths, id, n), { recursive: true, force: true }); if (plan.seenRemoved) await rm(triageSeenPath(deps.paths, id), { force: true }); const drop = new Set(plan.editions.map((e) => e.n)); return drop.size ? { ...s, editions: (s.editions ?? []).filter((e) => !drop.has(e.n)) } : s; }); return plan!; } // ─── the tick's bookkeeping (controller/reportTick.ts, the runner) ─── /** * Claim a tick for job `jobId`: refused (null) when one is already queued or * running. A scheduled claim moves `nextTick` on to the first window after * now — the missed ones are counted, never queued. */ export async function claimTick( id: string, o: { jobId: string; trigger: "schedule" | "now"; scheduledFor?: string; next?: string }, deps: ScheduleDeps, ): Promise { let refused = false; const out = await mutateSchedule(id, deps, (s, now) => { if (s.running) { refused = true; return s; } return { ...s, running: { jobId: o.jobId, at: now.toISOString(), trigger: o.trigger, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}) }, ...(o.next ? { nextTick: o.next } : {}), }; }); return refused ? null : out; } /** Give a claim back (its job never started). */ export async function releaseClaim(id: string, jobId: string, deps: ScheduleDeps): Promise { await mutateSchedule(id, deps, (s) => (s.running?.jobId === jobId ? { ...s, running: null } : s)).catch(() => {}); } /** Point a claim at the job that holds it (the job's id is known only once it is enqueued). */ export async function moveClaim(id: string, from: string, to: string, deps: ScheduleDeps): Promise { await mutateSchedule(id, deps, (s) => (s.running?.jobId === from ? { ...s, running: { ...s.running, jobId: to } } : s)); } /** Record a tick's end: its line in the history (the newest TICKS_KEPT), the claim released, `lastTick`. */ export async function recordTick(id: string, tick: Tick, deps: ScheduleDeps): Promise { return mutateSchedule(id, deps, (s) => ({ ...s, running: s.running && (!tick.jobId || s.running.jobId === tick.jobId || s.running.jobId.startsWith(PENDING_PREFIX)) ? null : s.running, lastTick: tick.at, ticks: [...s.ticks, tick].slice(-TICKS_KEPT), })); } /** Drop a series' edition line (a tick that made nothing). */ export async function dropEdition(id: string, n: number, deps: ScheduleDeps): Promise { await mutateSchedule(id, deps, (s) => ({ ...s, editions: (s.editions ?? []).filter((e) => e.n !== n) })); } /** Add or replace a series' edition (by its number). */ export async function putEdition(id: string, e: Edition, deps: ScheduleDeps): Promise { return mutateSchedule(id, deps, (s) => { if (s.shape !== "series") fail(`"${id}" is not a series`); const rest = (s.editions ?? []).filter((x) => x.n !== e.n); return { ...s, editions: [...rest, e].sort((a, b) => a.n - b.n) }; }); } export { CadenceError };