// THE `report-schedule` LANE (umtool R5): the editor keeps the schedules. // // Armed by the editor's instrumentation BELOW the idle gate, beside the // research auto-continue it is shaped after (controller/ // researchAutoContinue.ts): ARCHILYZER_IDLE_BOOT arms nothing, and // `armReportSchedule` refuses an idle boot itself too. Once armed, a SCAN // runs now and then every CHECK_MS on an unref'd timer (the process's // lifetime, like the sync heartbeat), and: // // - the lane's PAUSE GATE (lib/pauseGates.ts, lane `report-schedule`, // `settings.reportSchedule.held`) is read first: held, the scan // enqueues nothing. A hold is never a stop — a tick already queued or // running finishes. Tick now is the operator's word and is not held; // - a claim whose job is gone (the editor stopped mid-tick) is recorded // `interrupted` and released, so the schedule ticks again; // - each schedule not paused, not ticking and due (cadence.ts dueTick) // gets ONE `report-tick` job (controller/reportTick.ts enqueueTick), // its claim taken first, its next window the first after now — a // window missed while the editor was down is one catch-up tick, never N. // The ticks themselves run one at a time (REPORT_TICK_QUEUE). // // Not a long-lived registry job (the auto-queue runners are): a tick is the // job, and the Running list shows the ticks rather than a runner that only // waits. import { isIdleBoot } from "../lib/idleBoot"; import { getRegistry } from "../jobs/registry"; import { getSettings, type SiteSettings } from "../lib/settings"; import { isGateHeld } from "../lib/pauseGates"; import { dueTick } from "../lib/report/schedule/cadence"; import { listSchedules } from "../lib/report/schedule/store"; import type { Schedule } from "../lib/report/schedule/types"; import { PENDING_PREFIX, recordTick } from "./reportSchedule"; import { enqueueTick, type EnqueueTickResult, type TickDeps } from "./reportTick"; export const CHECK_MS = 60_000; // A claim taken and never handed to a job (the editor died between the two). export const PENDING_STALE_MS = 2 * 60_000; export type ScanDeps = { deps: TickDeps; // The lane's gate (default: settings.reportSchedule.held). held?: () => boolean; // Is this job queued or running in this process? (default: the registry) isLive?: (jobId: string) => boolean; enqueue?: (id: string, o: { trigger: "schedule"; scheduledFor: string; next: string; missed: number }) => Promise; log?: (line: string) => void; }; export type ScanResult = { held: boolean; schedules: number; enqueued: { id: string; jobId: string; scheduledFor: string; missed: number }[]; refused: { id: string; error: string }[]; interrupted: string[]; }; const liveInRegistry = (jobId: string) => { const j = getRegistry().get(jobId); return !!j && (j.status === "queued" || j.status === "running"); }; function gateHeld(settings: () => SiteSettings = getSettings): boolean { try { return isGateHeld(settings(), "report-schedule"); } catch { return false; } } /** Is this schedule's claim dead (its job gone)? */ function deadClaim(s: Schedule, now: number, isLive: (id: string) => boolean): boolean { if (!s.running) return false; if (s.running.jobId.startsWith(PENDING_PREFIX)) return now - Date.parse(s.running.at) > PENDING_STALE_MS; return !isLive(s.running.jobId); } /** One pass over the schedules (see the head of this file). */ export async function scanSchedules(o: ScanDeps): Promise { const { deps } = o; const now = (deps.now?.() ?? new Date()).getTime(); const isLive = o.isLive ?? liveInRegistry; const out: ScanResult = { held: false, schedules: 0, enqueued: [], refused: [], interrupted: [] }; const schedules = await listSchedules(deps.paths); out.schedules = schedules.length; for (const s of schedules) { if (!deadClaim(s, now, isLive)) continue; await recordTick( s.id, { at: new Date(now).toISOString(), trigger: s.running!.trigger, jobId: s.running!.jobId, status: "interrupted", usd: 0, reason: "the editor stopped during the tick (its job is gone)", ...(s.running!.scheduledFor ? { scheduledFor: s.running!.scheduledFor } : {}), }, deps, ).catch(() => {}); s.running = null; out.interrupted.push(s.id); o.log?.(`report-schedule: ${s.id}: a tick was interrupted (job gone); released`); } if ((o.held ?? (() => gateHeld()))()) { out.held = true; return out; } const enqueue = o.enqueue ?? ((id, x) => enqueueTick(id, x, deps)); for (const s of schedules) { if (s.running) continue; const d = dueTick(s, now); if (!d.due) continue; const scheduledFor = new Date(d.scheduledFor).toISOString(); const r = await enqueue(s.id, { trigger: "schedule", scheduledFor, next: new Date(d.next).toISOString(), missed: d.missed }); if (r.ok) { out.enqueued.push({ id: s.id, jobId: r.jobId, scheduledFor, missed: d.missed }); o.log?.(`report-schedule: ${s.id}: tick for ${scheduledFor}${d.missed ? ` (stands in for ${d.missed} missed)` : ""} → job ${r.jobId}`); } else { out.refused.push({ id: s.id, error: r.error }); o.log?.(`report-schedule: ${s.id}: not ticked: ${r.error}`); } } return out; } // ─── arming (the editor's instrumentation, below the idle gate) ─── type Armed = { o: ScanDeps; timer: ReturnType | null; scanning: Promise | null }; declare global { // eslint-disable-next-line no-var var __yttReportSchedule__: Armed | undefined; } /** One scan at a time: a second caller shares the one going. Null when unarmed. */ export function reportScheduleTick(): Promise | null { const a = globalThis.__yttReportSchedule__; if (!a) return null; if (!a.scanning) { a.scanning = scanSchedules(a.o).finally(() => { a.scanning = null; }); } return a.scanning; } /** * Arm the lane: a scan now and every `everyMs` (default CHECK_MS). Refused * (false) on an idle boot. Idempotent: a second call only replaces the deps. */ export function armReportSchedule(o: ScanDeps, opts: { env?: Record; everyMs?: number; bootScan?: boolean } = {}): boolean { if (isIdleBoot(opts.env)) return false; const armed = globalThis.__yttReportSchedule__; if (armed) { armed.o = o; return true; } const state: Armed = { o, timer: null, scanning: null }; globalThis.__yttReportSchedule__ = state; const every = opts.everyMs ?? CHECK_MS; if (every > 0) { state.timer = setInterval(() => { void reportScheduleTick()?.catch((e) => state.o.log?.(`report-schedule: the scan failed: ${(e as Error).message}`)); }, every); state.timer.unref?.(); } if (opts.bootScan !== false) void reportScheduleTick()?.catch(() => {}); return true; } export function disarmReportSchedule(): void { const a = globalThis.__yttReportSchedule__; if (a?.timer) clearInterval(a.timer); globalThis.__yttReportSchedule__ = undefined; } export function isReportScheduleArmed(): boolean { return globalThis.__yttReportSchedule__ !== undefined; }