// A RECURRING REPORT'S TICK (umtool R5; plans/umtool-redesign.md "R5"): ONE // editor job, kind `report-tick` on its own queue (REPORT_TICK_QUEUE: one tick // at a time machine-wide), whose steps go through a SEAM, `TickSteps`: // // fetchAndBuild(scope) R4's stage 1: the editor's own paced fetches for the // scope's channels, then a LOCAL build of the site // that holds them (a sweep reads a composed build) // refresh(article) R4's `report-draft {"task":"refresh"}` — what // changed, then an update when anything did (its // own no-change/$0 and held-by-cap outcomes) // generateEdition(...) a sweep over a window as a new article (the // existing generate path with from/to), after a // window check: nothing in it is a QUIET edition // triage?(...) R6's cheap pass (`report-draft {"task":"triage"}`): // tier 0 (what is new by id, matching the terms or // topics) and tier 1 (the local window judge), and // whether its flags reach the threshold // // THE TICK, by shape: // living refresh (R4's task: its own stage 1 over the report's scope and // every channel its citations touch, then what changed, then the // update) → on `updated` with `autoMakeCurrent`, the new iteration // made current, else left ready (an iteration-ready Review card). // A living report with no report yet takes fetchAndBuild and its // first sweep instead. // series the window first (an empty one fetches nothing), then // fetchAndBuild over it → an EDITION: a new article // `-` (the tick's day) over whole days — the // day after the last edition's window end through the day before // the tick (the first: the cadence's length back), never a day // twice (lib/report/schedule/types.ts editionWindow) — titled // " · week of " / " · ". A quiet window // is recorded, no article, $0; an empty one (a Tick now right after // a tick) makes no edition and says so. // watch (R6) fetchAndBuild over the scope → triage → at or above the // threshold, an API sweep of the flagged recordings as a new // article `-` (" · "): the Inbox's // Worth researching card; below it, `no-change`, the triage log, $0 API // // TRIAGE FIRST (R6; a living report's or a series' `triageFirst`, always a // watch's): fetch → triage → (escalate) → the shape's step on the FLAGGED ids // only — a living report's refresh reads them (no second fetch), a series' // edition sweeps them (no date bound: a late transcript is in). Below the // threshold the tick ends with its triage log, $0 API (a series' edition is // quiet). An escalation past the day's cap (settings.generation.triage // .maxEscalationsPerDay, over every schedule) is held — the operator's call, // the flags kept. The tick line keeps the triage in brief (`triage`). // // Caps: the generation policy's per-job cap (the schedule's own, never above // caps.max) and the daily cap; a refusal ends the tick `held-by-cap` — the // operator's call, with the reason and the estimate. // // Every tick ends with a line in the schedule's history (controller/ // reportSchedule.ts recordTick) and the log's `@@report-tick {json}`. import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { Paths } from "../lib/paths"; import { REPORT_TICK_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import type { GenerationSettings } from "../lib/generationSettings"; import { currentIteration, iterationUsd, listIterations, makeCurrent, readIteration, readIterationFile, writeIterationFile, } from "../lib/report/iterations"; import { addDays, cadenceDays, localDate } from "../lib/report/schedule/cadence"; import { readSchedule } from "../lib/report/schedule/store"; import { editionTitle, editionWindow, nothingToCover, type Edition, type Schedule, type Tick, type TickStatus } from "../lib/report/schedule/types"; import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage"; import { listSchedules } from "../lib/report/schedule/store"; import { triagesFirst } from "../lib/report/schedule/types"; import { readTriageFile } from "../lib/report/draft/triage/store"; import { partialWords, tickTriageOf, type TickTriage, type TriageFile } from "../lib/report/draft/triage/types"; import { learnDue, learnedWords, namesForPass, termsKey } from "../lib/report/draft/triage/learned"; import { readLearned } from "../lib/report/draft/triage/learnedStore"; import { enqueueReportDraft, type ReportDraftDeps } from "./reportDraft"; import { fetchScope, readRefreshFile } from "./reportRefresh"; import { PENDING_PREFIX, claimTick, dropEdition, moveClaim, putEdition, recordTick, releaseClaim, tickModel, type ScheduleDeps, } from "./reportSchedule"; import { stat } from "node:fs/promises"; import path from "node:path"; export const REPORT_TICK_JOB_KIND = "report-tick"; export const REPORT_TICK_RESULT_MARKER = "@@report-tick "; // How often a tick re-reads the spend of the sweep it waits on. const SPEND_POLL_MS = 5_000; // ─── the seam ─── export type StepCtx = { log: (line: string) => void; signal: AbortSignal }; // `warnings`: what stage 1 skipped and said (a held or cooling platform, a // channel no build holds) -- recorded on the tick, never its failure. export type FetchOutcome = { ok: true; note?: string; warnings?: string[] } | { ok: false; status: "failed" | "held-by-cap"; reason: string; warnings?: string[] }; export type StepStatus = "done" | "no-change" | "quiet" | "partial" | "held-by-cap" | "failed" | "cancelled"; export type StepOutcome = { status: StepStatus; // The iteration made (a refresh's, an edition's sweep). iteration?: number; usd: number; reason?: string; jobId?: string; // What a held step would have cost at most (its cap). estimateUsd?: number; // Recordings the window check matched. matched?: number; // What a step skipped and said (a refresh's fetch on a held platform). warnings?: string[]; // The article the step wrote (a watch's escalation). article?: string; }; export type EditionInput = { schedule: Schedule; // The article the sweep writes (a new one; an edition's, or a living // report's first). article: string; // The report's title once done (an edition's); null keeps the model's. title: string | null; window: { from: string; to: string }; // A series' window check (a living report's first sweep has none). quietCheck: boolean; // R6: the sweep reads only these recordings (what a triage flagged) — no // date bound, the window is the edition's label — and names the triage it // escalates. ids?: string[]; triage?: { owner: string; k: number }; }; /** R6: the triage step's ask — the scope (no window: new is by id), and "new" with no last run. */ export type TriageStepInput = { schedule: Schedule; scope: { channels: string[]; from?: string; to?: string }; since: string | null }; export type TriageStepOutcome = { status: "done" | "failed" | "cancelled"; file: TriageFile | null; reason?: string; jobId?: string }; export type TickSteps = { // Stage 1 over a scope: a series' edition (its window), a living report's // first sweep. A living report's refresh runs its own stage 1 (over its // report's scope and every channel its citations touch). fetchAndBuild(scope: { channels: string[]; from?: string; to?: string }, ctx: StepCtx): Promise; // R6: `ids` — the update reads only these (a triage's flags); `fetch: false` — stage 1 ran already. refresh(article: string, o: { model?: string; maxUsd?: number; ids?: string[]; fetch?: boolean }, ctx: StepCtx): Promise; generateEdition(input: EditionInput, ctx: StepCtx): Promise; // R6: the cheap pass that flags what is worth a sweep (triage first, a watch). triage?(input: TriageStepInput, ctx: StepCtx): Promise; // R6.3: the proposal pass (learned spellings), run before tier 0 when one is // due — never proposed, the terms changed, a week since the last. learn?(input: LearnStepInput, ctx: StepCtx): Promise; }; export type LearnStepInput = { schedule: Schedule; trigger: "create" | "terms" | "weekly" }; export type LearnStepOutcome = { status: "done" | "failed" | "cancelled"; reason?: string; jobId?: string; added?: number; total?: number }; // Steps that refuse, saying so: what a deps without R4's wiring (r4Steps // below) gets — a test, or a process with no editor door. export const NOT_WIRED_FETCH = "not wired: no fetch-and-build step (R4's stage 1) in this process"; export const NOT_WIRED_REFRESH = "not wired: no refresh step (R4's report-draft refresh) in this process"; export const notWiredFetch: TickSteps["fetchAndBuild"] = async () => ({ ok: false, status: "failed", reason: NOT_WIRED_FETCH }); export const notWiredRefresh: TickSteps["refresh"] = async () => ({ status: "failed", usd: 0, reason: NOT_WIRED_REFRESH }); // ─── the real generateEdition ─── /** * A window's recordings for the quiet check: `{recordings}` or why it could not * say. `partial` (R6.1): the scan hit a cap, `unreached` what it did not read * — 0 from a partial scan is NOT quiet. */ export type CountWindow = (q: { channels: string[]; from: string; to: string; terms?: string; regex?: boolean }) => Promise<{ recordings: number; partial?: boolean; unreached?: string[] } | { error: string }>; export type EditionDeps = { draft: ReportDraftDeps; // The window check (the editor's enumerate over the corpus). Absent: no // quiet editions — every window is swept. countWindow?: CountWindow; }; const settingsOf = (d: { settings?: () => { generation: GenerationSettings } }) => (d.settings ?? getSettings)().generation; /** The cap refusal's words (the daily cap's own sentence): a refusal that says them is held, not failed. */ export const isCapRefusal = (reason: string) => /daily cap|caps\.daily|caps\.max|over the settings' max/.test(reason); /** The existing generate path (a `report-draft` sweep with from/to) as a tick step: window check, cap, the job, its end. */ export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition"] { return async (input, ctx) => { const { schedule: s, window } = input; const paths = deps.draft.paths; const gen = settingsOf(deps.draft); let matched: number | undefined; if (input.quietCheck && !input.ids?.length && deps.countWindow) { const c = await deps.countWindow({ channels: s.scope.channels, from: window.from, to: window.to, ...(s.scope.terms ? { terms: s.scope.terms } : {}), ...(s.scope.regex ? { regex: true } : {}), }); if ("error" in c) return { status: "failed", usd: 0, reason: `the window check failed: ${c.error}` }; matched = c.recordings; if (c.partial && c.recordings === 0) { // A capped scan that read nothing matching: not a quiet window. const where = c.unreached?.length ? `not reached: ${c.unreached.join(", ")}` : "a cap was hit"; return { status: "partial", usd: 0, matched: 0, reason: `partial — the window check of ${window.from} … ${window.to} was capped (${where}): nothing matched in what it read, so the window is not called quiet` }; } if (c.partial) ctx.log(`warning: the window check was capped${c.unreached?.length ? ` (not reached: ${c.unreached.join(", ")})` : ""}: at least ${c.recordings} match`); if (c.recordings === 0) { return { status: "quiet", usd: 0, matched: 0, reason: s.scope.terms ? `nothing in ${window.from} … ${window.to} matches ${s.scope.terms}` : `no recording in scope in ${window.from} … ${window.to}`, }; } ctx.log(`window ${window.from} … ${window.to}: ${c.recordings} recording${c.recordings === 1 ? "" : "s"} match`); } let m: ReturnType; try { m = tickModel(gen, s); } catch (e) { return { status: "held-by-cap", usd: 0, reason: (e as Error).message }; } if (m.note) ctx.log(m.note); if (m.provider === "api") { const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.draft.now?.())), gen.caps.daily); if (refusal) return { status: "held-by-cap", usd: 0, reason: refusal, ...(m.capUsd !== null ? { estimateUsd: m.capUsd } : {}), ...(matched !== undefined ? { matched } : {}) }; } const out = await enqueueReportDraft( { task: "sweep", article: input.article, question: s.question, channels: s.scope.channels, // A triage's flagged recordings: no date bound (a late transcript is in). ...(input.ids?.length ? { ids: input.ids } : { from: window.from, to: window.to }), ...(input.triage ? { triage: `${input.triage.owner}/${input.triage.k}` } : {}), model: m.model, ...(m.capUsd !== null ? { maxUsd: m.capUsd } : {}), }, deps.draft, ); if (!out.result.ok || !("iteration" in out)) { const reason = (out.result as { error: string }).error; return { status: isCapRefusal(reason) ? "held-by-cap" : "failed", usd: 0, reason, ...(m.capUsd !== null ? { estimateUsd: m.capUsd } : {}) }; } const result = out.result as Extract; void result.stream.cancel(); const n = out.iteration; ctx.log(`sweep ${input.article} i${n} on ${m.model}: job ${result.jobId}`); // A tick cancelled cancels its sweep. const stop = () => getRegistry().cancel(result.jobId); ctx.signal.addEventListener("abort", stop, { once: true }); // The sweep's spend so far, in the tick's own log (`~$x`: the Running // list's spend for the tick). let said = -1; const spent = setInterval(() => { void readIteration(input.article, n, paths).then( (it) => { const usd = it ? iterationUsd(it) : 0; if (usd !== said && usd > 0) { said = usd; ctx.log(`sweep ${input.article} i${n}: ~$${usd.toFixed(2)} so far`); } }, () => {}, ); }, SPEND_POLL_MS); spent.unref?.(); try { await result.done; } finally { clearInterval(spent); ctx.signal.removeEventListener("abort", stop); } const it = await readIteration(input.article, n, paths); const usd = it ? iterationUsd(it) : 0; ctx.log(`sweep ${input.article} i${n} ended ${it?.status ?? "unread"}: ~$${usd.toFixed(2)}`); const status: StepStatus = it?.status === "done" ? "done" : it?.status === "cancelled" ? "cancelled" : "failed"; if (status === "done" && input.title) { // An edition's title is the series' (" · week of "), not the model's. const text = await readIterationFile(input.article, n, "report.json", paths).catch(() => null); if (text) { try { const doc = JSON.parse(text) as Record; await writeIterationFile(input.article, n, "report.json", { ...doc, title: input.title }, paths); } catch (e) { ctx.log(`the report kept its own title: ${(e as Error).message}`); } } } return { status, iteration: n, usd, jobId: result.jobId, ...(it?.error && status !== "done" ? { reason: it.error } : {}), ...(matched !== undefined ? { matched } : {}), }; }; } // ─── R4's steps (the seam, wired) ─── /** What the R4 wiring calls (injectable: the unit tests stub them). */ export type R4Calls = { fetchScope: typeof fetchScope; enqueueReportDraft: typeof enqueueReportDraft; readRefreshFile: typeof readRefreshFile; }; const stepWords = (x: { channel?: string; action?: string; site?: string | null; reason?: string }) => { const what = [x.channel, x.action, x.site ? `build ${x.site}` : ""].filter(Boolean).join(" "); return what ? `${what}: ${x.reason ?? "skipped"}` : (x.reason ?? "skipped"); }; /** * fetchAndBuild and refresh over R4 (controller/reportRefresh.ts): * fetchAndBuild `fetchScope` — each channel's paced fetches, then the * local build of the site that holds them (never a deploy). * A step refused or skipped (a held or cooling platform, a * channel no build holds) is a WARNING on the tick; only a * build that ran and failed fails it. * refresh `report-draft {"task": "refresh"}` — its own stage 1, what * changed, the update — awaited; its refresh.json's status * is the outcome: updated → done (the new iteration), * no-change, held-by-cap (with the cap's refusal and the * estimate). * Both need `deps.refreshEditor` (the editor's in-process door). */ export function r4Steps(draft: ReportDraftDeps, calls: Partial = {}): Pick { const c: R4Calls = { fetchScope, enqueueReportDraft, readRefreshFile, ...calls }; return { fetchAndBuild: async (scope, ctx) => { let r: Awaited>; try { r = await c.fetchScope(scope, draft, { signal: ctx.signal, log: ctx.log }); } catch (e) { if (ctx.signal.aborted) throw e; return { ok: false, status: "failed", reason: `the fetch could not run: ${(e as Error).message}` }; } const warnings = [ ...r.warnings, // A refused or skipped step (not a routine one) — failed, cancelled and // still-going steps are in r.warnings already. ...r.fetch.filter((f) => (f.status === "refused" || f.status === "skipped") && !f.routine).map(stepWords), ...(r.build && r.build.status !== "done" && r.build.status !== "failed" && r.build.reason ? [stepWords({ ...r.build, site: r.build.site })] : []), ]; if (r.build?.status === "failed") { return { ok: false, status: "failed", reason: `the local build${r.build.site ? ` of ${r.build.site}` : ""} failed${r.build.reason ? `: ${r.build.reason}` : ""}`, warnings }; } const fetched = r.fetch.filter((f) => f.status === "done").length; return { ok: true, note: `stage 1: ${fetched} fetch${fetched === 1 ? "" : "es"} done${r.build?.site ? `, ${r.build.site} built (${r.build.status})` : ""}`, warnings }; }, refresh: async (article, o, ctx) => { const out = await c.enqueueReportDraft( { task: "refresh", article, ...(o.model ? { model: o.model } : {}), ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), ...(o.ids?.length ? { ids: o.ids } : {}), ...(o.fetch === false ? { fetch: false } : {}) }, draft, ); if (!out.result.ok || !("iteration" in out)) { const reason = (out.result as { error: string }).error; return { status: isCapRefusal(reason) ? "held-by-cap" : "failed", usd: 0, reason }; } const result = out.result as Extract; void result.stream.cancel(); const n = out.iteration; ctx.log(`refresh ${article} i${n}: job ${result.jobId}`); const stop = () => getRegistry().cancel(result.jobId); ctx.signal.addEventListener("abort", stop, { once: true }); try { await result.done; } finally { ctx.signal.removeEventListener("abort", stop); } const it = await readIteration(article, n, draft.paths).catch(() => null); const usd = it ? iterationUsd(it) : 0; const f = await c.readRefreshFile(article, n, draft.paths).catch(() => null); const warnings = [...(out.warnings ?? []), ...(f?.warnings ?? []), ...(f?.fetch ?? []).filter((x) => (x.status === "refused" || x.status === "skipped") && !x.routine).map(stepWords)]; const base = { iteration: n, usd, jobId: result.jobId, ...(warnings.length ? { warnings } : {}) }; ctx.log(`refresh ${article} i${n} ended ${f?.status ?? it?.status ?? "unread"}: ~$${usd.toFixed(2)}${f?.summary ? ` — ${f.summary}` : ""}`); switch (f?.status) { case "updated": return { status: "done", ...base, ...(f.summary ? { reason: f.summary } : {}) }; case "no-change": return { status: "no-change", ...base, reason: f.summary }; case "partial": return { status: "partial", ...base, reason: f.summary }; case "held-by-cap": return { status: "held-by-cap", ...base, reason: f.update?.refusal ?? f.summary, ...(f.update?.estimateUsd !== undefined ? { estimateUsd: f.update.estimateUsd } : {}), }; case "cancelled": return { status: "cancelled", ...base, reason: "cancelled" }; default: return { status: ctx.signal.aborted ? "cancelled" : "failed", ...base, reason: f?.summary || it?.error || `the refresh ended ${it?.status ?? "unread"}` }; } }, }; } // ─── the tick ─── export type TickDeps = ScheduleDeps & { paths: Paths; steps: TickSteps; // Default: lib/report/iterations makeCurrent. makeCurrent?: (article: string, n: number) => Promise; }; /** Whether a living report has a report to refresh: a current one, or a done iteration carrying one. */ export async function hasReportToRefresh(article: string, paths: Pick): Promise { const cur = await currentIteration(article, paths).catch(() => null); if (cur?.report != null) return true; for (const it of await listIterations(article, paths).catch(() => [])) { if (it.status === "done" && (await readIterationFile(article, it.n, "report.json", paths).catch(() => null)) !== null) return true; } return false; } const exists = (p: string) => stat(p).then(() => true, () => false); /** The edition's article id: `-`, then -2, -3 … when the store has it. */ async function editionArticle(s: Schedule, day: string, paths: Pick): Promise { const base = `${s.id}-${day}`; const used = new Set((s.editions ?? []).map((e) => e.article).filter(Boolean)); for (let k = 1; k < 100; k++) { const id = k === 1 ? base : `${base}-${k}`; if (!used.has(id) && !(await exists(path.join(paths.articlesDir, id)))) return id; } throw new Error(`no free edition id after ${base}`); } // ─── R6: the triage step (the seam, wired) ─── /** What the triage wiring calls (injectable: the unit tests stub it). */ export type TriageCalls = { enqueueReportDraft: typeof enqueueReportDraft; readTriageFile: typeof readTriageFile }; /** * The triage step over the editor: `report-draft {"task":"triage"}` for the * schedule (its id the run's owner: reports/.triage//), awaited (a * cancelled tick cancels it), its triage.json the outcome. */ export function triageStep(draft: ReportDraftDeps, calls: Partial = {}): NonNullable { const c: TriageCalls = { enqueueReportDraft, readTriageFile, ...calls }; return async (input, ctx) => { const s = input.schedule; const out = await c.enqueueReportDraft( { task: "triage", article: s.id, question: s.question, channels: input.scope.channels, ...(input.scope.from ? { from: input.scope.from } : {}), ...(input.scope.to ? { to: input.scope.to } : {}), ...(s.scope.terms ? { terms: s.scope.terms, ...(s.scope.regex ? { regex: true } : {}) } : {}), ...(s.scope.topics?.length ? { topics: s.scope.topics } : {}), ...(s.triage?.threshold ? { threshold: s.triage.threshold } : {}), ...(input.since ? { since: input.since } : {}), }, draft, ); if (!out.result.ok || !("iteration" in out)) return { status: "failed", file: null, reason: `the triage could not start: ${(out.result as { error: string }).error}` }; const result = out.result as Extract; void result.stream.cancel(); const k = out.iteration; ctx.log(`triage ${s.id}/${k}: job ${result.jobId}`); const stop = () => getRegistry().cancel(result.jobId); ctx.signal.addEventListener("abort", stop, { once: true }); try { await result.done; } finally { ctx.signal.removeEventListener("abort", stop); } const f = await c.readTriageFile(s.id, k, draft.paths).catch(() => null); if (!f) return { status: ctx.signal.aborted ? "cancelled" : "failed", file: null, jobId: result.jobId, reason: `triage ${s.id}/${k} left no triage.json` }; ctx.log(`triage ${s.id}/${k} ended ${f.status}: ${f.summary}`); return { status: f.status === "done" ? "done" : f.status === "cancelled" || ctx.signal.aborted ? "cancelled" : "failed", file: f, jobId: result.jobId, ...(f.status !== "done" ? { reason: f.error ?? f.summary } : {}), }; }; } /** Escalations the ticks of every schedule ran on the UTC day of `now` (the day's escalation cap counts them). */ export async function escalationsToday(paths: Pick, now: Date): Promise { const day = utcDay(now); let n = 0; for (const s of await listSchedules(paths).catch(() => [])) for (const t of s.ticks) if (t.triage?.escalated && t.at.slice(0, 10) === day) n++; return n; } /** The day's escalation cap's refusal, or null. */ export async function escalationCapRefusal(paths: Pick, now: Date, cap: number): Promise { if (!(cap > 0)) return null; const n = await escalationsToday(paths, now); return n >= cap ? `the day's escalation cap is reached: ${n} escalation${n === 1 ? "" : "s"} today (${utcDay(now)}, UTC), the cap ${cap} (settings.generation.triage.maxEscalationsPerDay) — the flags are kept; it resets at midnight UTC` : null; } export type TickRun = { trigger: "schedule" | "now"; scheduledFor?: string; missed?: number; jobId: string }; /** Run one tick of schedule `id` and record it. Answers the history line it wrote. */ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: StepCtx): Promise { const now = deps.now?.() ?? new Date(); const t0 = Date.now(); const s = await readSchedule(id, deps.paths); if (!s) throw new Error(`no schedule "${id}"`); const base = { at: now.toISOString(), trigger: run.trigger, jobId: run.jobId, ...(run.scheduledFor ? { scheduledFor: run.scheduledFor } : {}), ...(run.missed ? { missed: run.missed } : {}), }; const finish = async (o: Partial & { status: TickStatus; usd: number }): Promise => { const tick: Tick = { ...base, ...(learnLine ? { learn: learnLine } : {}), ...o, minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 }; await recordTick(id, tick, deps); ctx.log(`${REPORT_TICK_RESULT_MARKER}${JSON.stringify({ schedule: id, ...tick })}`); return tick; }; const today = localDate(now.getTime(), s.tz); let edition: Edition | null = null; // The triage this tick ran (R6), for its line. const tri: { file: TriageFile | null } = { file: null }; const triageLine = (o: { tier2Usd?: number; capped?: string } = {}): { triage?: TickTriage } => (tri.file ? { triage: tickTriageOf(tri.file, o) } : {}); const tier1Usd = () => tri.file?.cost.tier1 ?? 0; // R6.3: the proposal pass this tick ran, for its line. let learnLine: Tick["learn"] | undefined; const learned = (): { learn?: Tick["learn"] } => (learnLine ? { learn: learnLine } : {}); try { ctx.log(`${s.shape} ${id}: ${run.trigger === "now" ? "ticked now" : `the ${run.scheduledFor} window`}${run.missed ? ` (stands in for ${run.missed} missed)` : ""}`); // Stage 1 over a scope; what it skipped is the tick's warnings. const warnings: string[] = []; const stage1 = async (scope: { channels: string[]; from?: string; to?: string }): Promise => { const f = await deps.steps.fetchAndBuild(scope, ctx); for (const w of f.warnings ?? []) { warnings.push(w); ctx.log(`warning: ${w}`); } if (!f.ok) return finish({ status: f.status, usd: 0, reason: f.reason, ...(warnings.length ? { warnings } : {}) }); if (f.note) ctx.log(f.note); if (ctx.signal.aborted) return finish({ status: "cancelled", usd: 0, reason: "cancelled", ...(warnings.length ? { warnings } : {}) }); return null; }; const warned = () => (warnings.length ? { warnings: [...new Set(warnings)] } : {}); // R6: the triage, after stage 1. Answers the flagged ids to escalate on, // or the tick's end (below the threshold, the cap, a failure). const triage = async (o: { onBelow: (why: string) => Promise }): Promise<{ ids: string[]; ref: { owner: string; k: number } } | { done: Tick }> => { if (!deps.steps.triage) return { done: await finish({ status: "failed", usd: 0, reason: "not wired: no triage step (R6) in this process", ...warned() }) }; // R6.3: before tier 0, a proposal pass when one is due. Its failure is a // warning, never the tick's: the triage runs on what is learned. if (deps.steps.learn && namesForPass(s).names.length) { const lf = await readLearned(deps.paths, s).catch(() => null); const due = learnDue(lf, termsKey(s.scope.terms, s.scope.regex === true), now); if (due) { ctx.log(`learn: a proposal pass is due (${due === "create" ? "never proposed" : due === "terms" ? "the terms changed" : "a week since the last"})`); const l = await deps.steps.learn({ schedule: s, trigger: due }, ctx); learnLine = { trigger: due, status: l.status, ...(l.added !== undefined ? { added: l.added } : {}), ...(l.total !== undefined ? { total: l.total } : {}), ...(l.jobId ? { jobId: l.jobId } : {}) }; if (l.status === "cancelled" || ctx.signal.aborted) return { done: await finish({ status: "cancelled", usd: 0, reason: "cancelled", ...learned(), ...warned() }) }; if (l.status !== "done") { warnings.push(`the proposal pass failed: ${l.reason ?? "no reason"} — the triage runs on what is learned`); ctx.log(`warning: the proposal pass failed: ${l.reason ?? "no reason"}`); } else ctx.log(`learn: ${l.added ?? 0} learned (${l.total ?? 0} in all)`); } } const back = addDays(today, -cadenceDays(s.cadence)); const since = s.scope.from && s.scope.from > back ? s.scope.from : back; const t = await deps.steps.triage({ schedule: s, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, since }, ctx); tri.file = t.file; if (t.file?.learned?.n) ctx.log(`triage ${t.file.owner}/${t.file.k}: ${learnedWords(t.file.learned.n)}`); if (t.status !== "done" || !t.file) { return { done: await finish({ status: t.status === "cancelled" ? "cancelled" : "failed", usd: tier1Usd(), reason: `the triage ${t.status === "cancelled" ? "was cancelled" : "failed"}${t.reason ? `: ${t.reason}` : ""}`, ...triageLine(), ...warned() }) }; } const esc = t.file.escalation; // R6.1: a partial tier 0 never ends a tick quiet — what it did not reach // is not "nothing new". Below the threshold it is the operator's call. const part = partialWords(t.file.tier0); if (!esc?.escalate && part) { const reason = `partial — ${part}; nothing flagged in what was read (${esc?.why ?? t.file.summary})`; ctx.log(`triage ${reason}`); return { done: await finish({ status: "partial", usd: tier1Usd(), reason, ...triageLine(), ...warned() }) }; } if (!esc?.escalate) return { done: await o.onBelow(`triage: ${esc?.why ?? t.file.summary} — below the threshold, nothing escalated`) }; if (part) { warnings.push(`the triage was partial (${part}): the escalation reads what it reached`); ctx.log(`warning: the triage was partial (${part})`); } const gen = (deps.settings ?? getSettings)().generation; const capped = await escalationCapRefusal(deps.paths, now, gen.triage.maxEscalationsPerDay); if (capped) { ctx.log(`escalation held: ${capped}`); return { done: await finish({ status: "held-by-cap", usd: tier1Usd(), reason: capped, ...triageLine({ capped }), ...warned() }) }; } const ids = [...new Set((t.file.tier1?.flags ?? []).map((f) => f.id))]; ctx.log(`escalate: ${esc.why} — tier 2 reads ${ids.length} recording(s): ${ids.slice(0, 10).join(", ")}`); return { ids, ref: { owner: t.file.owner, k: t.file.k } }; }; if (s.shape === "living") { const article = s.article ?? s.id; let out: StepOutcome; if (!(await hasReportToRefresh(article, deps.paths))) { ctx.log(`${article} has no report yet: its first sweep${triagesFirst(s) ? " (triage applies from the next tick)" : ""}`); const back = addDays(today, -cadenceDays(s.cadence)); const window = { from: s.scope.from ?? back, to: today }; const stopped = await stage1({ channels: s.scope.channels, ...window }); if (stopped) return stopped; out = await deps.steps.generateEdition({ schedule: s, article, title: null, window, quietCheck: false }, ctx); } else if (triagesFirst(s)) { const stopped = await stage1({ channels: s.scope.channels }); if (stopped) return stopped; const t = await triage({ onBelow: (why) => finish({ status: "no-change", usd: tier1Usd(), article, reason: why, ...triageLine(), ...warned() }) }); if ("done" in t) return t.done; out = await deps.steps.refresh(article, { ...(s.model ? { model: s.model } : {}), ...(s.caps?.maxUsd ? { maxUsd: s.caps.maxUsd } : {}), ids: t.ids, fetch: false }, ctx); } else { out = await deps.steps.refresh(article, { ...(s.model ? { model: s.model } : {}), ...(s.caps?.maxUsd ? { maxUsd: s.caps.maxUsd } : {}) }, ctx); } warnings.push(...(out.warnings ?? [])); let reason = out.reason; if (out.status === "done" && out.iteration && s.autoMakeCurrent) { try { await (deps.makeCurrent ?? ((a: string, n: number) => makeCurrent(a, n, deps.paths)))(article, out.iteration); ctx.log(`${article} i${out.iteration} made current (autoMakeCurrent)`); } catch (e) { reason = `made, not current: ${(e as Error).message}`; } } return await finish({ status: out.status, usd: Math.round((out.usd + tier1Usd()) * 10_000) / 10_000, article, ...(out.iteration ? { iteration: out.iteration } : {}), ...(reason ? { reason } : {}), ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}), ...triageLine({ tier2Usd: out.usd }), ...warned(), }); } if (s.shape === "watch") { // No article until something is found (R6). const stopped = await stage1({ channels: s.scope.channels }); if (stopped) return stopped; const t = await triage({ onBelow: (why) => finish({ status: "no-change", usd: tier1Usd(), reason: why, ...triageLine(), ...warned() }) }); if ("done" in t) return t.done; const article = await editionArticle(s, today, deps.paths); const title = `${s.topic} · ${today}`; const since = tri.file?.since ?? addDays(today, -cadenceDays(s.cadence)); const out = await deps.steps.generateEdition({ schedule: s, article, title, window: { from: since < today ? since : today, to: today }, quietCheck: false, ids: t.ids, triage: t.ref }, ctx); const made = out.iteration !== undefined; return await finish({ status: out.status === "quiet" ? "no-change" : out.status, usd: Math.round((out.usd + tier1Usd()) * 10_000) / 10_000, ...(made ? { article, iteration: out.iteration } : {}), ...(out.reason ? { reason: out.reason } : {}), ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}), ...triageLine({ tier2Usd: out.usd }), ...warned(), }); } if (s.shape !== "series") return await finish({ status: "failed", usd: 0, reason: `a ${s.shape} schedule has no tick` }); const w = editionWindow(s, today); if ("empty" in w) { // Nothing between the last edition and today: no edition, $0, no card. return await finish({ status: "no-change", usd: 0, reason: nothingToCover(w.nextFrom) }); } const window = w.window; const stopped = await stage1({ channels: s.scope.channels, ...window }); if (stopped) return stopped; const n = Math.max(0, ...(s.editions ?? []).map((e) => e.n)) + 1; // Named for the tick's day (the window ends the day before it). const article = await editionArticle(s, today, deps.paths); const title = editionTitle(s.topic, s.cadence, window); let flagged: { ids: string[]; ref: { owner: string; k: number } } | null = null; if (triagesFirst(s)) { // Below the threshold: a quiet edition (its window covered by the triage), $0 API. const t = await triage({ onBelow: async (why) => { const e: Edition = { n, at: now.toISOString(), window, title, status: "quiet", usd: tier1Usd(), reason: why, jobId: run.jobId }; await putEdition(id, e, deps); return finish({ status: "quiet", usd: tier1Usd(), edition: n, reason: why, ...triageLine(), ...warned() }); }, }); if ("done" in t) return t.done; flagged = t; } edition = { n, at: now.toISOString(), window, title, status: "running", article, usd: 0, jobId: run.jobId }; await putEdition(id, edition, deps); const out = await deps.steps.generateEdition({ schedule: s, article, title, window, quietCheck: !flagged, ...(flagged ? { ids: flagged.ids, triage: flagged.ref } : {}) }, ctx); const made = out.iteration !== undefined; const usd = Math.round((out.usd + tier1Usd()) * 10_000) / 10_000; if (out.status === "quiet" || made) { edition = { n, at: edition.at, window, title, // A made edition whose step said partial still made its article. status: out.status === "no-change" || out.status === "partial" ? "done" : out.status, ...(out.status !== "quiet" ? { article, iteration: out.iteration } : {}), usd, ...(out.jobId ? { jobId: out.jobId } : {}), ...(out.reason ? { reason: out.reason } : {}), ...(out.matched !== undefined ? { matched: out.matched } : {}), }; await putEdition(id, edition, deps); } else { // Nothing was made (held, refused): no edition — the next tick covers this window. await dropEdition(id, n, deps); } return await finish({ status: out.status, usd, ...(out.status === "quiet" || made ? { edition: n } : {}), ...(made ? { article, iteration: out.iteration } : {}), ...(out.reason ? { reason: out.reason } : {}), ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}), ...triageLine({ tier2Usd: out.usd }), ...warned(), }); } catch (e) { const cancelled = ctx.signal.aborted; if (edition?.status === "running") await dropEdition(id, edition.n, deps).catch(() => {}); return finish({ status: cancelled ? "cancelled" : "failed", usd: tier1Usd(), reason: cancelled ? "cancelled" : (e as Error).message, ...triageLine() }); } } // ─── the job ─── export type EnqueueTickResult = { ok: true; jobId: string } | { ok: false; error: string; running?: string }; /** * Enqueue ONE `report-tick` job for schedule `id`: the claim first (refused * when a tick of it is queued or running), then the job; a scheduled tick's * claim moves `nextTick` on to `next`. */ export async function enqueueTick( id: string, o: { trigger: "schedule" | "now"; scheduledFor?: string; next?: string; missed?: number }, deps: TickDeps, ): Promise { const pending = `${PENDING_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; const claimed = await claimTick(id, { jobId: pending, trigger: o.trigger, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), ...(o.next ? { next: o.next } : {}) }, deps); if (!claimed) { const s = await readSchedule(id, deps.paths); return { ok: false, error: `a tick of "${id}" is already queued or running (job ${s?.running?.jobId ?? "?"})`, ...(s?.running ? { running: s.running.jobId } : {}) }; } const result = await runManagedFunction({ kind: REPORT_TICK_JOB_KIND, queueKey: REPORT_TICK_QUEUE, paths: deps.paths, fn: async (onLog, signal, _setProgress, ctx) => { // The claim names its job before anything runs. await moveClaim(id, pending, ctx.jobId, deps).catch(() => {}); const tick = await runTick(id, { trigger: o.trigger, jobId: ctx.jobId, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), ...(o.missed ? { missed: o.missed } : {}) }, deps, { log: onLog, signal }); if (tick.status === "cancelled") throw new Error("cancelled"); if (tick.status === "failed" || tick.status === "interrupted") throw new Error(tick.reason ?? "the tick failed"); }, }); if (!result.ok) { await releaseClaim(id, pending, deps); return { ok: false, error: result.error }; } void result.stream.cancel(); await moveClaim(id, pending, result.jobId, deps).catch(() => {}); // A job cancelled before it ran never ran runTick: record it and give the claim back. void result.done.then(async (d) => { const s = await readSchedule(id, deps.paths).catch(() => null); if (s?.running?.jobId === result.jobId || s?.running?.jobId === pending) { await recordTick( id, { at: (deps.now?.() ?? new Date()).toISOString(), trigger: o.trigger, jobId: result.jobId, status: d.status === "cancelled" ? "cancelled" : "interrupted", usd: 0, reason: `the job ended ${d.status} before the tick ran`, ...(o.scheduledFor ? { scheduledFor: o.scheduledFor } : {}), }, deps, ).catch(() => {}); } }); return { ok: true, jobId: result.jobId }; }