// `pnpm ops report-schedule` — a recurring report's schedule, as one ops action // (umtool R5). The editor's route is an adapter over `reportScheduleAction`; // umtool's Create, series page and chip post here. The writes are // controller/reportSchedule.ts's; a tick is controller/reportTick.ts's. // // {"action": "list", "id"?} every schedule (or one), with its // chip, its call and its spend // {"action": "create", …, "dryRun"?} the plan (first tick, model, cap) // with dryRun, else the schedule; // shape living | series | watch // (R6: no article until a triage // finds something); triageFirst, // topics, threshold {strong, weak} // {"action": "update", "id", …} topic, question, cadence, tz, // channels, from, terms, regex, // autoMakeCurrent, model, maxUsd, // triageFirst, topics, threshold // {"action": "pause" | "resume", "id"} a resume re-plans from now // {"action": "delete", "id", "confirm"?} the plan, unless confirm: true // {"action": "tick-now", "id"} one tick now (refused while one // is queued or running) // {"action": "reset-triage", "id", "k"?, (R6.1) discard the schedule's // "confirm"?} triage state — its runs (from // run k on), seen.json, the quiet // editions they covered — the plan // unless confirm: true // {"action": "learn", "id", "dryRun"?} (R6.3) the proposal pass now: the // plan (the names it asks about, // the model) and its job; dryRun: // the plan only. A create (of a // schedule that triages) and a // change of terms start one too // {"action": "unlearn", "id", "spelling"} (R6.3) remove a learned spelling; // it is never learned again // {"action": "add-spelling", "id", (release 32 R2) a spelling added by // "spelling", "means"} hand: counted in scope, its proving // line found by code, kept as "hand" // {"action": "promote-alias", "id", (R6.3) a learned spelling as a // "spelling", "site"?, "confirm"?} search alias (global, or a // site's) through the alias // writer: the plan unless confirm import { getSettings } from "../lib/settings"; import { ArticleRegistryError } from "../lib/report/registry"; import { CadenceError } from "../lib/report/schedule/cadence"; import { isGateHeld } from "../lib/pauseGates"; import { listScheduleReads, readScheduleById } from "../lib/report/schedule/store"; import { callOf, scheduleChip, spentOf, type Schedule, type Tick } from "../lib/report/schedule/types"; import { ScheduleInputError, createSchedule, deleteSchedule, parseCreate, parseUpdate, planCreate, planDelete, planResetTriage, resetTriage, setPaused, updateSchedule, } from "./reportSchedule"; import { enqueueTick, type TickDeps } from "./reportTick"; import { isReportScheduleArmed } from "./reportScheduleRunner"; import { LearnedInputError, addSpellingByHand, planPromoteAlias, promoteAlias, unlearnSpelling, type HandProver } from "./learnedSpellings"; import { planLearn, type LearnPlan, type LearnTrigger } from "./reportLearn"; import { triagesFirst } from "../lib/report/schedule/types"; import { namesForPass } from "../lib/report/draft/triage/learned"; export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage", "learn", "unlearn", "promote-alias", "add-spelling"] as const; export type ReportScheduleActionName = (typeof REPORT_SCHEDULE_ACTIONS)[number]; export const REPORT_SCHEDULE_BODY_KEYS = [ "action", "id", "shape", "topic", "question", "article", "channels", "case", "from", "terms", "regex", "cadence", "at", "tz", "autoMakeCurrent", "model", "maxUsd", "confirm", "dryRun", "triageFirst", "topics", "threshold", "k", "spelling", "means", "site", ] as const; export type ScheduleView = Schedule & { chip: string; // The newest tick when it is the operator's call (failed, held by a cap, interrupted). call: Tick | null; spentUsd: number; }; export const viewOf = (s: Schedule, now?: number): ScheduleView => ({ ...s, chip: scheduleChip(s, now), call: callOf(s), spentUsd: spentOf(s) }); export type LaneView = { held: boolean; armed: boolean }; export function laneView(settings: () => Parameters[0] = getSettings): LaneView { let held = false; try { held = isGateHeld(settings(), "report-schedule"); } catch { /* settings unreadable: not held */ } return { held, armed: isReportScheduleArmed() }; } type Ok = { ok: true } & Record; type Refused = { ok: false; error: string; status?: number }; const idOf = (b: Record): string => { if (typeof b.id !== "string" || !b.id.trim()) throw new ScheduleInputError('"id" names the schedule (a series\' id, or a living report\'s article)'); return b.id.trim(); }; /** R6.3: the proposal pass's door — the editor's enqueueLearn, bound to its deps. Absent: a learn is refused as not wired. */ export type EnqueueLearnFn = (id: string, trigger: LearnTrigger) => Promise<{ ok: true; jobId: string; plan: LearnPlan } | { ok: false; error: string; plan?: LearnPlan }>; // After a create or a change of terms: a pass when the schedule triages and its terms name someone. async function learnAfter(id: string, trigger: LearnTrigger, s: { shape: string; triageFirst?: boolean; scope: { terms?: string; regex?: boolean } }, enqueue: EnqueueLearnFn | undefined) { if (!enqueue || !triagesFirst(s as Parameters[0]) || !namesForPass(s).names.length) return {}; const out = await enqueue(id, trigger).catch((e: Error) => ({ ok: false as const, error: e.message })); return { learn: out.ok ? { jobId: out.jobId, names: out.plan.names } : { refused: out.error } }; } /** One `report-schedule` ask. Input errors answer `{ok: false, error}` (a 400); nothing throws for them. */ export async function reportScheduleAction( body: Record, deps: TickDeps & { lane?: () => LaneView; enqueueLearn?: EnqueueLearnFn; proveSpelling?: HandProver }, ): Promise { const action = body.action; if (typeof action !== "string" || !(REPORT_SCHEDULE_ACTIONS as readonly string[]).includes(action)) { return { ok: false, error: `"action" is one of ${REPORT_SCHEDULE_ACTIONS.join(", ")}` }; } const now = (deps.now?.() ?? new Date()).getTime(); try { switch (action as ReportScheduleActionName) { case "list": { const lane = (deps.lane ?? (() => laneView()))(); if (body.id !== undefined) { const r = await readScheduleById(idOf(body), deps.paths); if (!r) return { ok: false, error: `no schedule "${String(body.id)}"`, status: 404 }; if (!r.ok) return { ok: false, error: `the schedule "${r.id}" does not read (${r.file}): ${r.problem}` }; return { ok: true, schedule: viewOf(r.schedule, now), lane }; } const reads = await listScheduleReads(deps.paths); return { ok: true, schedules: reads.flatMap((r) => (r.ok ? [viewOf(r.schedule, now)] : [])), problems: reads.flatMap((r) => (r.ok ? [] : [{ id: r.id, file: r.file, problem: r.problem }])), lane, }; } case "create": { const input = parseCreate(body); if (body.dryRun === true) { const { plan } = await planCreate(input, deps); return { ok: true, plan }; } const { plan, schedule } = await createSchedule(input, deps); return { ok: true, plan, schedule: viewOf(schedule, now), ...(await learnAfter(schedule.id, "create", schedule, deps.enqueueLearn)) }; } case "update": { const id = idOf(body); const before = await readScheduleById(id, deps.paths).catch(() => null); const s = await updateSchedule(id, parseUpdate(body), deps); const termsChanged = before?.ok && (before.schedule.scope.terms !== s.scope.terms || (before.schedule.scope.regex === true) !== (s.scope.regex === true)); return { ok: true, schedule: viewOf(s, now), ...(termsChanged ? await learnAfter(id, "terms", s, deps.enqueueLearn) : {}) }; } case "learn": { const id = idOf(body); if (body.dryRun === true || !deps.enqueueLearn) { const plan = await planLearn(id, deps); if (body.dryRun === true) return { ok: true, plan }; return { ok: false, error: plan.refused ?? "not wired: no proposal pass (R6.3) in this process" }; } const out = await deps.enqueueLearn(id, "ops"); if (!out.ok) return { ok: false, error: out.error }; return { ok: true, plan: out.plan, jobId: out.jobId }; } case "unlearn": { const id = idOf(body); const out = await unlearnSpelling(id, String(body.spelling ?? ""), deps); return { ok: true, removed: out.removed, blocked: out.blocked }; } case "add-spelling": { const id = idOf(body); if (!deps.proveSpelling) return { ok: false, error: "not wired: no corpus to count a spelling in (release 32) in this process" }; const out = await addSpellingByHand(id, { spelling: body.spelling, means: body.means }, { paths: deps.paths, prove: deps.proveSpelling, ...(deps.now ? { now: deps.now } : {}) }); return { ok: true, added: out.added, unblocked: out.unblocked }; } case "promote-alias": { const id = idOf(body); const site = body.site === undefined || body.site === null || body.site === "" || body.site === "global" ? null : typeof body.site === "string" ? body.site.trim() : ""; if (site === "") throw new ScheduleInputError('"site" is a site\'s id (or absent: the global aliases)'); if (body.confirm !== true) { const plan = await planPromoteAlias(id, String(body.spelling ?? ""), site, deps); return { ok: true, confirmed: false, plan }; } const plan = await promoteAlias(id, String(body.spelling ?? ""), site, deps); return { ok: true, confirmed: true, promoted: plan }; } case "pause": case "resume": { const s = await setPaused(idOf(body), action === "pause", deps); return { ok: true, schedule: viewOf(s, now) }; } case "delete": { const id = idOf(body); if (body.confirm !== true) { const plan = await planDelete(id, deps); return { ok: true, confirmed: false, plan }; } const plan = await deleteSchedule(id, deps); return { ok: true, confirmed: true, deleted: plan }; } case "reset-triage": { const id = idOf(body); let k: number | null = null; if (body.k !== undefined) { if (typeof body.k !== "number" || !Number.isInteger(body.k) || body.k < 1) throw new ScheduleInputError('"k" is a triage run\'s number (1, 2, …): discard from that run on'); k = body.k; } if (body.confirm !== true) { const plan = await planResetTriage(id, k, deps); return { ok: true, confirmed: false, plan }; } const plan = await resetTriage(id, k, deps); return { ok: true, confirmed: true, reset: plan }; } case "tick-now": { const id = idOf(body); const r = await readScheduleById(id, deps.paths); if (!r) return { ok: false, error: `no schedule "${id}"`, status: 404 }; if (!r.ok) return { ok: false, error: `the schedule "${id}" does not read: ${r.problem}` }; const out = await enqueueTick(id, { trigger: "now" }, deps); if (!out.ok) return { ok: false, error: out.error, ...(out.running ? { status: 409 } : {}) }; return { ok: true, jobId: out.jobId }; } } } catch (e) { if (e instanceof ScheduleInputError || e instanceof CadenceError || e instanceof LearnedInputError) return { ok: false, error: (e as Error).message }; // A schedule the learn plan cannot read is input-shaped too. if (/^no schedule "|does not read/.test((e as Error).message)) return { ok: false, error: (e as Error).message, ...(/^no schedule "/.test((e as Error).message) ? { status: 404 } : {}) }; // The registry's own refusals (the store busy, a bad id) are input-shaped too. if (e instanceof ArticleRegistryError) return { ok: false, error: (e as Error).message }; if (/maxUsd/.test((e as Error).message)) return { ok: false, error: (e as Error).message }; throw e; } return { ok: false, error: "unreachable" }; }