// A RECURRING REPORT'S SCHEDULE — its shape (umtool R5; plans/umtool-redesign.md // "R5 — Recurring reports"). Pure: the types, the schema, the words, and what // a reader (umtool's chip, the series page, the Inbox) derives from a // schedule. The store is ./store.ts (reads) and controller/reportSchedule.ts // (the ONE writer); the editor's runner (controller/reportScheduleRunner.ts) // ticks it. // // living one article kept current: each tick re-fetches what the scope // holds and runs R4's Refresh over the article (its first tick, // with no report yet, is the article's first sweep); the new // iteration is left ready for review, or made current when // `autoMakeCurrent` says so // series a new dated EDITION each tick — a new article over the window // since the last edition's window end — titled // " · week of " (weekly) or " · "; a // window nothing in scope matches is a QUIET edition: recorded, // no article, $0 // watch no article until something is found (umtool R6): each tick // fetches, then TRIAGES what is new in scope (the cheap pass, // lib/report/draft/triage); only a triage at or above its threshold // escalates to an API sweep of the flagged recordings, as a new // article `-` — an Inbox "Worth researching" card, // and a board umtool makes of the flags. Below it, the tick ends // with its triage log, $0 API // // A living report or a series may ask for TRIAGE FIRST (`triageFirst`): its // tick triages before its own step, and runs that step on the flagged // recordings only — or, below the threshold, ends $0 (a series' edition is // quiet). Stored with the series (a dot-directory) and its runs in // reports/.triage//. // // Safe for a client component: zod and ./cadence only. import { z } from "zod"; import { addDays, cadenceDays, chipWords, localDate, parseCadence, type Cadence } from "./cadence"; import { TRIAGE_STATUSES } from "../draft/triage/types"; export const SCHEDULE_FORMAT = "archilyzer-schedule"; export const SCHEDULE_VERSION = 1; export const SCHEDULE_SHAPES = ["living", "series", "watch"] as const; export type ScheduleShape = (typeof SCHEDULE_SHAPES)[number]; // The shapes create offers. export const OFFERED_SHAPES: readonly ScheduleShape[] = ["living", "series", "watch"]; // `partial` (R6.1): a scan the tick decided on hit a cap or did not reach a // channel, and found nothing in what it read — never `quiet`/`no-change`, // which would be a silent zero. The reason names what was not reached. export const TICK_STATUSES = ["done", "no-change", "quiet", "partial", "held-by-cap", "failed", "cancelled", "interrupted"] as const; export type TickStatus = (typeof TICK_STATUSES)[number]; // The outcomes that are the operator's call (a Your call card). export const CALL_STATUSES: readonly TickStatus[] = ["failed", "held-by-cap", "interrupted", "partial"]; export const EDITION_STATUSES = ["running", "done", "quiet", "failed", "cancelled", "held-by-cap"] as const; export type EditionStatus = (typeof EDITION_STATUSES)[number]; // The history a schedule keeps: the newest ticks, the oldest dropped. export const TICKS_KEPT = 100; const isoTime = z.string().refine((s) => Number.isFinite(Date.parse(s)), "is not an ISO 8601 time"); const ymd = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "is not a YYYY-MM-DD date"); // A series' id: room left for an edition's "-YYYY-MM-DD-n" in a 64-character // article id. A living report's id is its article's (any article id). export const SCHEDULE_ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/; const ANY_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; const channelSlug = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "is not a channel slug"); const cadenceSchema = z.unknown().transform((v, ctx): Cadence => { try { return parseCadence(v); } catch (e) { ctx.addIssue({ code: "custom", message: (e as Error).message }); return z.NEVER; } }); export const scheduleScopeSchema = z.looseObject({ channels: z.array(channelSlug).min(1), // The research board (R2 case) the scope came from, when it did. case: z.string().min(1).optional(), // The first window starts no earlier than this. from: ymd.optional(), // A series' window check: what an edition's window must match to be worth a // sweep (enumerate_matches' query). Absent: any recording in the window. terms: z.string().min(1).optional(), regex: z.boolean().optional(), // A triage's digest topic tags (umtool R6): a new recording whose digest // carries one is a candidate, whatever its words. topics: z.array(z.string().min(1)).optional(), }); export type ScheduleScope = z.infer; // What a tick keeps of its triage (umtool R6; draft/triage/types.ts TickTriage). export const tickTriageSchema = z.looseObject({ owner: z.string().min(1), k: z.number().int().positive(), status: z.enum(TRIAGE_STATUSES), candidates: z.number().int().nonnegative(), flagged: z.number().int().nonnegative(), dismissed: z.number().int().nonnegative(), escalated: z.boolean(), why: z.string(), ids: z.array(z.string()), top: z.array(z.looseObject({ f: z.string(), id: z.string(), line: z.string(), score: z.number(), reason: z.string() })), usd: z.looseObject({ tier1: z.number().nonnegative(), tier2: z.number().nonnegative() }), capped: z.string().optional(), partial: z.string().optional(), // R6.3: the learned spellings its query carried (terms + N learned). learned: z.number().int().nonnegative().optional(), }); export const tickSchema = z.looseObject({ at: isoTime, // The window it ticked for (absent: Tick now). scheduledFor: isoTime.optional(), trigger: z.enum(["schedule", "now"]), status: z.enum(TICK_STATUSES), jobId: z.string().optional(), // Living: the iteration the tick made (or refreshed into). iteration: z.number().int().positive().optional(), // Series: the edition's number. edition: z.number().int().positive().optional(), article: z.string().optional(), usd: z.number().nonnegative(), // Why it ended so (one line), and what a held tick would have cost. reason: z.string().optional(), estimateUsd: z.number().nonnegative().optional(), // Windows passed while the editor was away, that this one tick stood in for. missed: z.number().int().nonnegative().optional(), minutes: z.number().nonnegative().optional(), // What its fetch skipped and said (a held or cooling platform): never its failure. warnings: z.array(z.string()).optional(), // Its triage, when it ran one (umtool R6): the tiers in brief, and whether it escalated. triage: tickTriageSchema.optional(), // R6.3: the proposal pass it ran before tier 0 (a pass was due): what it learned. learn: z.looseObject({ trigger: z.string(), status: z.string(), added: z.number().int().nonnegative().optional(), total: z.number().int().nonnegative().optional(), jobId: z.string().optional() }).optional(), }); export type Tick = z.infer; export const editionSchema = z.looseObject({ n: z.number().int().positive(), at: isoTime, window: z.looseObject({ from: ymd, to: ymd }), title: z.string().min(1), status: z.enum(EDITION_STATUSES), // The edition's article in the store (absent: a quiet one). article: z.string().optional(), iteration: z.number().int().positive().optional(), usd: z.number().nonnegative(), jobId: z.string().optional(), reason: z.string().optional(), // How many recordings the window held for the terms (the quiet check). matched: z.number().int().nonnegative().optional(), }); export type Edition = z.infer; export const scheduleSchema = z.looseObject({ format: z.literal(SCHEDULE_FORMAT), version: z.literal(SCHEDULE_VERSION), id: z.string().regex(ANY_ID_RE), shape: z.enum(SCHEDULE_SHAPES), // The topic: a series' edition titles start with it; a living report's name. topic: z.string().min(1), // What a sweep asks. question: z.string().min(1), // Living: the article kept current. article: z.string().optional(), scope: scheduleScopeSchema, cadence: cadenceSchema, // The local clock the cadence is on (the editor's zone when it was made). tz: z.string().min(1), // An every-N-days schedule's grid: its first tick's local date. anchor: ymd.nullable().optional(), paused: z.boolean(), // Living: make each refreshed iteration current with no review (default off). autoMakeCurrent: z.boolean().optional(), // The model a tick's generation runs on (default: the policy's route). model: z.string().min(1).optional(), // A tick's per-job cap (USD; never above the policy's max). Default: the // policy's sweep cap. caps: z.looseObject({ maxUsd: z.number().positive().optional() }).optional(), // Living and series: triage first (umtool R6; a watch always triages). triageFirst: z.boolean().optional(), // The schedule's own triage threshold (default: settings.generation.triage's). triage: z.looseObject({ threshold: z.looseObject({ strong: z.number().int().min(0).max(50), weak: z.number().int().min(0).max(50) }).optional() }).optional(), createdAt: isoTime, updatedAt: isoTime, lastTick: isoTime.nullable(), nextTick: isoTime.nullable(), // A tick queued or running (its job): never two of one schedule at once. running: z.looseObject({ jobId: z.string().min(1), at: isoTime, trigger: z.enum(["schedule", "now"]), scheduledFor: isoTime.optional() }).nullable(), ticks: z.array(tickSchema), // Series: every edition, oldest first. editions: z.array(editionSchema).optional(), }); export type Schedule = z.infer; export function parseSchedule(raw: unknown): { ok: true; value: Schedule } | { ok: false; problems: string[] } { const r = scheduleSchema.safeParse(raw); if (r.success) return { ok: true, value: r.data }; return { ok: false, problems: r.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`) }; } // ─── what a reader derives ─── /** Does this schedule's tick triage first? A watch always does. */ export const triagesFirst = (s: Pick): boolean => s.shape === "watch" || s.triageFirst === true; /** The cadence chip: "weekly · next Mon 06:00", "daily · paused". */ export const scheduleChip = (s: Pick, now?: number) => chipWords(s, now); /** The newest tick, or null. */ export const lastTickOf = (s: Pick): Tick | null => s.ticks[s.ticks.length - 1] ?? null; /** The tick that is the operator's call now: the newest, when it failed or was held, and nothing has ticked since. */ export function callOf(s: Pick): Tick | null { if (s.running) return null; const t = lastTickOf(s); return t && CALL_STATUSES.includes(t.status) ? t : null; } /** Editions newest first. */ export const editionsNewestFirst = (s: Pick): Edition[] => [...(s.editions ?? [])].sort((a, b) => b.n - a.n); /** What the schedule's ticks spent, in USD. */ export const spentOf = (s: Pick): number => Math.round(s.ticks.reduce((n, t) => n + t.usd, 0) * 10_000) / 10_000; /** "Co-host updates · week of 2026-10-13" (weekly) or "Co-host updates · 2026-10-14". */ export function editionTitle(topic: string, cadence: Cadence, window: { from: string; to: string }): string { return cadence.kind === "weekly" ? `${topic} · week of ${window.from}` : `${topic} · ${window.to}`; } // ─── an edition's window (operator ruling, R5 review) ─── // // WHOLE DAYS, AND NO DAY READ TWICE. An edition covers [start, end], local // dates in the schedule's zone: // end the day BEFORE the tick (the tick's own day is not over) // start the previous edition's end + 1 day; the first edition's, the // cadence's length back from the tick's day (floored at the // scope's `from`) // So weekly on Mon 06:00 covers the previous Mon … Sun, 7 days, and "week of // " names it. A window that would be empty (start > end — a Tick now // right after a tick) makes no edition at all: `{ empty, nextFrom }`. // // The previous edition is the last one that covered its window: done, quiet // or still running. A failed edition (or a held tick, which makes none) // leaves its window to the next tick. // // By PUBLISH date: a recording of an earlier window that only gets its // transcript later is missed by a series (R6's tier 0 takes candidates by id, // new since the last tick, which closes that gap). export type EditionWindow = { from: string; to: string }; export function editionWindow( s: Pick, tickDay: string, ): { window: EditionWindow } | { empty: true; nextFrom: string } { const covered = [...(s.editions ?? [])].reverse().find((e) => e.status === "done" || e.status === "quiet" || e.status === "running"); const to = addDays(tickDay, -1); let from = covered ? addDays(covered.window.to, 1) : addDays(tickDay, -cadenceDays(s.cadence)); if (!covered && s.scope.from && s.scope.from > from) from = s.scope.from; if (from > to) return { empty: true, nextFrom: from }; return { window: { from, to } }; } /** The window of an edition ticked at instant `t` (ms), on the schedule's own clock. */ export const editionWindowAt = (s: Pick, t: number) => editionWindow(s, localDate(t, s.tz)); /** "Nothing to cover yet — the next edition starts 2026-10-19". */ export const nothingToCover = (nextFrom: string) => `Nothing to cover yet — the next edition starts ${nextFrom}`;