Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Schedules: an occurrence ledger, catch-up with a rule, a watchdog for lost turns, and the health report's schedule section (#6042)
Milind Soni4cde6d5a0c5c
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex bf9de124b8..0b16236b22 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1719,7 +1719,10 @@ wait for the next read, `truncated: true`):"botId": "<uuid>", "threadId": "<uuid>", "seq": 12 }],"turns": { "started15m": 6, "failed15m": 3, "started24h": 40, "failed24h": 5 },"routines": [{ "routineId": "<uuid>", "status": "failed", "at": 1790000200000, "consecutiveFailures": 2 }],- "schedule": { "unreadable": false, "slowStops": 0 },+ "schedule": { "v": 1, "seq": 4182, "unreadable": false, "nextDueAt": 1790086400000, "oldestUnconfirmed": null,+ "lastConfirmed": { "dueAt": 1790000000000, "startedAt": 1790000001250, "state": "ran" },+ "due": { "boot": { "ran": 1, "failed": 0, "missed": 0, "late": 0, "retried": 0 },+ "day": { "ran": 1, "failed": 0, "missed": 0, "late": 0, "retried": 0 } }, "slowStops": 0 },"engines": [{ "kind": "codex", "used": true, "available": true, "authenticated": false, "version": "0.130.0" }],"connectors": { "checkedAt": 1790000000000, "failed": false, "items": [{ "slug": "gmail", "connected": false }] },"browser": { "available": true, "installing": false, "interrupted": 0 },@@ -1798,13 +1801,39 @@ counts once too. `turns` counts turns started and failed rows per minute;`routines` gives, for each routine that is on and each outside trigger, its lastoutcome and its failures in a row, counted from the saved run rows at every read,so a restart does not start the count again. A row that only counts occurrences-skipped while the routine was at work is not a result and is left out. `schedule.unreadable` is true while-the home cannot read its saved routines (none runs until it can), and-`schedule.slowStops` counts, since boot, the times stopping a turn took the-scheduler longer than 10 seconds and it went on without waiting. This `schedule`-section carries no `v`: a reader that requires a versioned section (`v: 1` with-every field of that version) takes it as "no section", which is intended. The-versioned section, with its required fields, comes with the run ledger.+skipped while the routine was at work is not a result and is left out.++**`schedule`** says what is due on this home, what has not started and what+last did (`server/routine-schedule-report.ts`), worked out from the occurrence+ledger (docs/routine-schedules.md) each time the report is read, on every page+of a truncated one too. It is about scheduled occurrences only: one firing of a+routine that is on and runs by the clock. Runs a person, a start-up, a webhook+or a connected-app event started are not in it, and neither are routines with+checks, which make no run when nothing is new. Times are this home's clock in+epoch milliseconds; counters run from 0 to 1e9.++| Field | Meaning |+| --- | --- |+| `v` | `1` |+| `seq` | Goes up by at least 1 with every change to this section other than the day's window moving: a row made, started, finished or closed, a routine added, changed, turned on or off or deleted, `unreadable` changing. It is saved with the ledger, so a restart never lowers it; a lower value means the schedule was restored from a backup. Renewing a run's lease does not raise it |+| `unreadable` | The saved routines cannot be read, so nothing runs; or the ledger cannot be written, so runs start without it and this section cannot say what is due. The next three fields are then `null` |+| `nextDueAt` | The earliest scheduled-for time among occurrences that have no run row yet, over routines whose bot takes runs now; `null` when nothing is scheduled. It may be past |+| `oldestUnconfirmed` | The due occurrence with the earliest scheduled-for time of which no attempt has started: `{ dueAt, state, since }`, with `state` `due` (no run row yet; `since` is `dueAt`) or `queued` (a row waits to start; `since` is when it was made). `null` when every due occurrence is decided. A routine whose bot is paused counts here too |+| `lastConfirmed` | The decided occurrence with the latest scheduled-for time: `{ dueAt, startedAt, state }`. `state` is `running` (started and not finished: waiting on a person, or for its retry, included), `ran`, `failed`, `missed` or `skipped`; `startedAt` is when its first attempt started, `null` for `missed` and `skipped`. A record that counts several occurrences stands at the last of them |+| `due.boot`, `due.day` | `{ ran, failed, missed, late, retried }` since this process started, and over the last 24 hours from the saved ledger: occurrences that finished well; that finished failed (a run someone stopped after it started counts here); that were closed without starting (`missed` and `skipped` together, each occurrence a record counts); whose first attempt started more than 5 minutes after its time; and starts after the first. Occurrences passed over only because the scheduler was held up starting another run are not counted as missed |+| `slowStops` | Since boot, the times stopping a turn took the scheduler longer than 10 seconds and it went on without waiting |++What a reader may rely on: an occurrence that is due and has not started+shows in `oldestUnconfirmed` at or before its time; a past `nextDueAt` always+comes with it; the report right after an occurrence's first start names it in+`lastConfirmed` (the start is written to the ledger before the turn begins, unless the ledger cannot be written),+unless one due later is already decided; and after a boot an overdue+occurrence shows as `due` or `queued` until the scheduler starts it or closes+it as missed, never moved past in silence. Two gaps are known: a routine that+also runs at start-up and is found more than 12 hours late runs its start-up+run in place of the missed occurrence, which gets no record; and occurrences+that fall while a routine is held (its owner left) are not recorded, because a+held routine is off.**What it never carries:** a failure's words, a bot's name, a thread's title,a prompt, a URL, an email address, a token, or an engine's accountdiff --git a/docs/routine-schedules.md b/docs/routine-schedules.mdindex bec19d8f29..19bec3b70a 100644--- a/docs/routine-schedules.md+++ b/docs/routine-schedules.md@@ -84,12 +84,99 @@ use an appropriate event/webhook workflow instead of a fake weekly schedule.routine and while one runs (Automations → *Keep this computer awake forroutines*, on by default; a closed lid still sleeps). For true 24/7, runOpenMausBot on a VPS — see [deploy-vps.md](deploy-vps.md).-- Existing catch-up policy remains: up to 12 hours late, one missed occurrence- can be dispatched; older work receives a missed-run receipt. The next date- advances without replaying every missed minute. Queued/running/waiting work- for the same cron routine does not accumulate overlapping copies (a run is- waiting while teammates still owe it results on the job runtime,- docs/runtime-contract.md §9).+- Catching up after downtime (the app closed, the computer asleep, a Cloud+ home off or restarting): for each routine, the newest occurrence that came+ due meanwhile runs late, if it is no more than 12 hours past its time, and+ the ones before it close on one **Missed** row that counts them and says why+ ("Missed 3 scheduled runs because this computer was asleep or OpenMausBot+ was not running"; on a Cloud, "because this Cloud was asleep or+ restarting"). That row is shown as already seen: the newest one is running,+ so it asks nothing of you. When even the newest is more than 12 hours old,+ nothing runs: all of them close on one Missed row that you are told about.+ The next date advances without replaying every missed minute. Routines found+ late in the same pass start 15 seconds apart (at most 40 steps, then again+ from the first), so a long downtime does not start them all in one second.+ A "when my limit resets" routine runs however late it is found. When the+ scheduler itself got to a routine late because it was waiting on another+ run's start (a pass ended after the run came due), the row says that+ instead ("…because the scheduler was held up starting another run") and the+ occurrences passed over are not counted as missed in the health report.+ Queued/running/waiting work for the same cron routine does not accumulate+ overlapping copies (a run is waiting while teammates still owe it results on+ the job runtime, docs/runtime-contract.md §9).+- **The occurrence ledger.** Beside `routines.json` the scheduler keeps+ `routines.ledger.jsonl`: one record per scheduled occurrence of each routine,+ keyed by the routine's id and the scheduled-for time. A record says how the+ occurrence ended (`ran`, `failed`, `missed` or `skipped`, or that it is+ `queued` or `running`), a fixed word for why, how often it started, when its+ first start was, and which run rows it produced. It holds ids, times, counts+ and fixed words only: never a name, a prompt or an output. The run rows stay+ in `routines.json`, and a row and its routine's next time are still saved in+ one write; the ledger is worked out from the rows at every save.+ - **Each occurrence starts once.** Before the scheduler makes a row for an+ occurrence it asks the ledger whether that occurrence already has a+ record; one that has is not made again, whatever brought it back (a+ `routines.json` put back from a copy, a clock set back, an edit made while+ the clock was wrong, a second process on the same files). A start is+ appended to the ledger and flushed to disk before its turn begins. A retry+ is a further start of the same record, counted on it.+ - **A ledger that cannot be written never stops a schedule.** A write that+ fails is logged once and made again with the next save; it fails neither+ the save nor any other run. A scheduled start waits at most three+ scheduler passes for the ledger; after that it starts without a record,+ and so does every later one until the ledger can be written again, with+ `routines.json` alone keeping a run from starting twice, as before there+ was a ledger. Meanwhile the health report says `unreadable: true`. A run+ someone started by hand never waits for the ledger.+ - **A clock that was ahead.** A row closed without starting says nothing+ about a time that has not come: a record reaching past now is cut back to+ now when that is seen, and cut again to just before an occurrence that+ comes due inside it, so every occurrence after the clock is put right is+ made and run. A record of a run that did start keeps its time.+ - **Leases.** A started occurrence's record carries a lease naming the+ machine and process that run it, renewed every minute for three, and given+ up at a clean shutdown. A process that starts on the same machine takes a+ cut run over at once (only one server holds a data folder). One that+ starts on another machine, a copy of the disk, waits until the lease has+ lapsed before it starts that run again.+ - **A restore from a backup.** A small file, `routines.ledger.mark`, keeps+ the ledger's sequence number and the time of its last change. A ledger+ with a lower number than the mark was brought back from a backup: every+ occurrence up to the mark's time already had its turn, so runs the backup+ held unfinished are let go ("Not run again: this schedule was restored+ from a backup…") and the occurrences up to then close on one counted row+ per routine; what came due after that is caught up as after any downtime.+ When a whole disk is restored, mark included, there is nothing to tell it+ by, and the catch-up rule above applies.+ - **Size.** The file is appended to and rewritten whole, through a temporary+ file and a rename, once it holds 500 more lines than records. Records that+ have ended are all kept for 48 hours; after that each routine keeps its+ 200 newest for 90 days, and the file never holds more than 10,000. A+ record that has not ended is never dropped. A torn last line (a crash in+ the middle of an append) is dropped at the next start and the rest kept;+ a ledger that is lost, or left empty, is made again from the run rows,+ and its sequence number carries on from the mark; neither is taken for a+ restore.+ - **Earlier versions.** A version from before the ledger reads and writes+ `routines.json` as it always did and ignores the two new files, so going+ back loses no routine and no run row. Coming forward again, the ledger+ takes in the rows that version made. At the first start with the ledger,+ it is made from the run rows already saved; none is moved or dropped.+ - `GET /api/routines?history=<routine id>` adds `occurrences`: that+ routine's records, newest first, for a routine the asker may see.+- The run rows in `routines.json` are still capped at 2,000. When the cap is+ reached, the row dropped is the oldest ended one of the routine that holds+ the most ended rows, so a routine that runs every five minutes uses up its+ own history and not the others'.+- **A run whose turn is gone.** A run that shows as running while its+ conversation has had no turn of its own for five minutes of scheduler+ passes, and has sent no event in that time, is treated like a run that+ failed: it starts once more ("Starting again shortly after a failure: its+ turn ended without reporting back"), and a second loss fails it. A run that+ waits on you or on work it handed on is never taken for lost, nor is a room+ goal's run, nor one whose turn is parked waiting for a computer another+ conversation holds: that turn resumes by itself when the computer is free. The five minutes are added up a pass at a time, so the hours a+ computer slept are not in them.- Every occurrence that does not run leaves a **Missed** row with its reason inthe routine's log. Occurrences skipped behind the same earlier run share onerow, which counts them ("Skipped 12 scheduled runs because the previous rundiff --git a/server/automation-reports.e2e.test.ts b/server/automation-reports.e2e.test.tsindex fb42715eec..1b48b89ff9 100644--- a/server/automation-reports.e2e.test.ts+++ b/server/automation-reports.e2e.test.ts@@ -407,11 +407,12 @@ it("tells the main chat about a run missed while the computer was off, which hasconst main = bot.activeTaskId as string;const { routine } = await api("POST", "/api/routines", {name: "Inbox watch", prompt: "Do the Inbox watch check.", botId: bot.id,- schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 },+ schedule: { type: "interval", everyMinutes: 1_440, anchorAt: Date.now() + 3_600_000 },});await restartable.stop();const file = join(restartable.dataDir, "routines.json");const saved = JSON.parse(readFileSync(file, "utf8"));+ // Its one occurrence is more than 12 hours old, so nothing runs late in its place.saved.routines.find((each: any) => each.id === routine.id).nextRunAt = Date.now() - 13 * 3_600_000;writeFileSync(file, JSON.stringify(saved));await restartable.start();diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.tsindex acb215b6b9..bc3641ecc9 100644--- a/server/cloud-health.test.ts+++ b/server/cloud-health.test.ts@@ -3,7 +3,7 @@ import { mkdirSync, rmSync } from "node:fs";import type { IncomingMessage, ServerResponse } from "node:http";import { join } from "node:path";import { PassThrough } from "node:stream";-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { failedTurnTool } from "../shared/failed-turn.ts";import type { PlaceRow } from "../shared/place-view.ts";import { TRIAL_CREDIT_REFUSED } from "../shared/trial-credit.ts";@@ -212,15 +212,21 @@ describe("the ledger", () => {it("reports each routine's last outcome and failures in a row as the saved run rows give them, so a restart hides none", () => {const rows = [{ routineId: "routine-1", status: "missed" as const, at: START, consecutiveFailures: 2 }, { routineId: "not an id!", status: "failed" as const, at: START, consecutiveFailures: 9 }];- const caps: number[] = [];- const deps = { routines: (cap: number) => { caps.push(cap); return rows; }, schedule: () => ({ unreadable: true, slowStops: 2 }) };+ const caps: number[] = [], none = { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 };+ const schedule = { v: 1 as const, seq: 7, unreadable: true, nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null, due: { boot: none, day: none }, slowStops: 2 };+ const deps = { routines: (cap: number) => { caps.push(cap); return rows; }, schedule: () => schedule };for (const w of [world(deps), world(deps)]) {const report = w.health.report(null);expect(report.routines).toEqual([rows[0]]);- expect(report.schedule).toEqual({ unreadable: true, slowStops: 2 });+ expect(report.schedule).toEqual(schedule);}expect(caps).toEqual([100, 100]);expect(world().health.report(null)).toMatchObject({ routines: [], schedule: null });+ vi.spyOn(console, "error").mockImplementation(() => {});+ const broken = world({ routines: () => { throw new Error("Quarterly-Secret-Plan"); }, schedule: () => { throw new Error("Quarterly-Secret-Plan"); } }).health.report(null);+ expect(broken).toMatchObject({ v: 1, routines: [], schedule: null, turns: { started15m: 0 } });+ expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain("Quarterly");+ vi.restoreAllMocks();});});diff --git a/server/cloud-health.ts b/server/cloud-health.tsindex b96c2508de..d3a03dbd04 100644--- a/server/cloud-health.ts+++ b/server/cloud-health.ts@@ -15,6 +15,7 @@ import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";import { classifyError } from "./drivers/retry.ts";import type { PerfHealth } from "./perf/perf-report.ts";import type { RoutineHealth } from "./routine-health.ts";+import type { ScheduleSection } from "./routine-schedule-report.ts";import type { Message, StoreChange } from "./store.ts";/** The report's largest JSON body; incidents past it wait for the next poll. */@@ -245,8 +246,8 @@ export interface CloudHealthDeps {room?: () => RoomReport;/** Each routine's newest ended run and its failures in a row, from the saved run rows (routine-health.ts), at most `cap`. */routines?: (cap: number) => RoutineHealth[];- /** Whether routines.json cannot be read, and how often stopping a turn outlasted the scheduler's wait since boot. */- schedule?: () => { unreadable: boolean; slowStops: number };+ /** What is due, what has not started and what last did (routine-schedule-report.ts), read from the scheduler each time; null while there is none. */+ schedule?: () => ScheduleSection | null;/** CPU steal and pressure, boot and wake times, and how long messages wait for their engine. */speed?: CloudSpeed;/** Turn phase timings, usage-limit holds, process buckets and event-loop lag: at most PERF_HEALTH_MAX_BYTES. A throw@@ -264,6 +265,11 @@ export function boxSummary(report: BoxReport | undefined): { box: BoxReport["boxreturn { box: report.box, reason: report.reason, checks: report.checks ? `${report.checks.passed}/${report.checks.total}` : null, failed, boxed: report.boxed, refused: report.refused, broker, hardening: report.hardening };}+/** What the scheduler says of itself, or `fallback` when asking it throws: the rest of the report is still answered. The log names no cause, which could quote a routine. */+function guarded<T>(read: () => T, fallback: T): T {+ try { return read(); } catch { console.error("cloud health: the scheduler's part of the report could not be read"); return fallback; }+}+/** The report's body, at most CLOUD_HEALTH_MAX_BYTES of JSON. */export function createCloudHealth(deps: CloudHealthDeps) {const now = deps.now ?? Date.now;@@ -304,7 +310,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {const memory = memoryBytes(), browser = deps.browser(), first = deps.firstHour?.();const base = {v: 1 as const, version, image, bootedAt: ledger.bootedAt, at: now(),- turns: read.turns, routines: (deps.routines?.(ROUTINE_CAP) ?? []).filter((routine) => match(ID, routine.routineId)), schedule: deps.schedule?.() ?? null,+ turns: read.turns, routines: guarded(() => deps.routines?.(ROUTINE_CAP) ?? [], []).filter((routine) => match(ID, routine.routineId)), schedule: guarded(() => deps.schedule?.() ?? null, null),engines: engines(), connectors: connectorState(),browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },box: boxSummary(deps.box?.()),diff --git a/server/index.ts b/server/index.tsindex 4f50331c10..0c8de4c8f9 100644--- a/server/index.ts+++ b/server/index.ts@@ -437,7 +437,7 @@ import { claudeUserSkillsEnabled } from "./turn-settings.ts";import { addHeldSecretScrubber, redactSecretsInText, scrubHeldSecrets } from "./redact.ts";import * as vps from "./vps-computer.ts";import { vpsConfigForBot, vpsSshAliasForBot } from "./vps-hosts.ts";-import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineRunsFor } from "./routine-run-window.ts"; import { batchSaves } from "./save-batch.ts";+import { ROUTINE_RESTARTED, RoutineManager, type Routine, type RoutineRun, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts"; import { routineModelRefusal, routineThreadModel, type RoutineModelChecks } from "./routine-input.ts"; import { routineHistoryFor, routineRunsFor } from "./routine-run-window.ts"; import { runTurnLive } from "./routine-turn-live.ts"; import { batchSaves } from "./save-batch.ts";import { CalendarCallManager, type CalendarCall } from "./calendar-calls.ts";import { BROWSER_UPLOAD_TOOL, browserRuntimeEnv } from "./browser-runtime.ts";import { BrowserUploadRefusal, uploadableFiles } from "./browser-upload.ts";@@ -2849,7 +2849,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.schedulerState() ?? { unreadable: false, slowStops: 0 },+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -8794,7 +8794,7 @@ routines = new RoutineManager({? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,- routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user",+ routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId),goalState: (groupId, coordinatorBotId) => {if (!groupId) return unattendedDispatchState(coordinatorBotId);@@ -14518,7 +14518,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (path === "/api/routines" && method === "GET") {return json(res, 200, {routines: routines!.listRoutines().filter((routine) => routineVisible(routine, visible)).map((routine) => routineForViewer(routine, visible)),- runs: routineRunsFor((from, to) => routines!.listRuns(from, to), url.searchParams).filter((run) => routineRunVisible(run, visible)),+ runs: routineRunsFor((from, to) => routines!.listRuns(from, to), url.searchParams).filter((run) => routineRunVisible(run, visible)), ...routineHistoryFor(routines!, url.searchParams, (routine) => routineVisible(routine, visible)),});}const routineBodyRefusal = (body: unknown, existing?: Routine): { status: number; error: string } | null => {diff --git a/server/routine-catch-up.test.ts b/server/routine-catch-up.test.tsnew file mode 100644index 0000000000..ef3d3c648f--- /dev/null+++ b/server/routine-catch-up.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vitest";++import { CATCH_UP_MS, CATCH_UP_STAGGER_MS, CATCH_UP_STAGGER_STEPS, passedOccurrences, planOccurrence, staggered } from "./routine-catch-up.ts";+import { nextOccurrence, type RoutineSchedule } from "./routine-schedules.ts";++const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR;+const START = Date.parse("2026-11-16T08:00:00Z");+const cron = (expression: string): RoutineSchedule => ({ type: "cron", expression, timeZone: "UTC" });+const interval = (everyMinutes: number, more: Record<string, unknown> = {}): RoutineSchedule => ({ type: "interval", everyMinutes, anchorAt: START, ...more });++describe("the occurrences passed while nothing could start them", () => {+ it("counts an interval's slots by arithmetic and a cron's by walking them", () => {+ expect(passedOccurrences(interval(5), START + 5 * MINUTE, START + 5 * MINUTE)).toEqual({ latest: START + 5 * MINUTE, count: 1 });+ expect(passedOccurrences(interval(5), START + 5 * MINUTE, START + 22 * MINUTE)).toEqual({ latest: START + 20 * MINUTE, count: 4 });+ expect(passedOccurrences(interval(5), START + 5 * MINUTE, START + 400 * DAY)).toEqual({ latest: START + 400 * DAY, count: 400 * 288 });+ expect(passedOccurrences(cron("0 * * * *"), START + HOUR, START + 3 * HOUR + 59 * MINUTE)).toEqual({ latest: START + 3 * HOUR, count: 3 });+ expect(passedOccurrences(cron("0 9 * * 1-5"), Date.parse("2026-11-16T09:00:00Z"), Date.parse("2026-11-23T08:00:00Z"))).toEqual({ latest: Date.parse("2026-11-20T09:00:00Z"), count: 5 });+ });++ it("finds the newest slot of an every-minute rule a month later without walking the month", () => {+ const first = START + MINUTE, now = START + 30 * DAY + 30_000;+ const passed = passedOccurrences(cron("* * * * *"), first, now);+ expect(passed.latest).toBe(START + 30 * DAY);+ expect(passed.count).toBe(30 * 1_440);+ });++ it("counts only the slots an interval kept to some hours allows, and stops at its end", () => {+ const first = new Date(2026, 10, 16, 9, 0).getTime();+ const hours = interval(30, { anchorAt: first, window: { start: "09:00", end: "10:30" } });+ expect(passedOccurrences(hours, first, new Date(2026, 10, 17, 9, 40).getTime())).toEqual({ latest: new Date(2026, 10, 17, 9, 30).getTime(), count: 5 });+ const ended = interval(60, { endsAt: START + 3 * HOUR });+ expect(passedOccurrences(ended, START + HOUR, START + 9 * HOUR)).toEqual({ latest: START + 3 * HOUR, count: 3 });+ });++ it("takes a one-time run and a limit reset for the single occurrence they are", () => {+ expect(passedOccurrences({ type: "once", at: START }, START, START + DAY)).toEqual({ latest: START, count: 1 });+ expect(passedOccurrences({ type: "limit_reset", engine: "claude", repeat: "every_reset", at: START } as RoutineSchedule, START, START + DAY)).toEqual({ latest: START, count: 1 });+ });+});++describe("what a due routine does", () => {+ const plan = (schedule: RoutineSchedule, first: number, now: number, cloud = false) => planOccurrence({ schedule, nextRunAt: first }, now, cloud);++ it("runs on time with nothing else to say", () => {+ expect(plan(interval(60), START + HOUR, START + HOUR + 90_000)).toEqual({ scheduledFor: START + HOUR, first: START + HOUR, through: START + HOUR, count: 1, fields: {}, late: false });+ });++ it("runs the newest occurrence late, with the older ones closed on a row the owner need not look at", () => {+ const late = plan(interval(60), START + HOUR, START + 4 * HOUR + 10 * MINUTE);+ expect(late).toMatchObject({ scheduledFor: START + 4 * HOUR, first: START + HOUR, through: START + 4 * HOUR, count: 4, fields: {}, late: true });+ expect(late.older).toMatchObject({ scheduledFor: START + HOUR, count: 3, fields: { status: "missed", seenAt: START + 4 * HOUR + 10 * MINUTE,+ error: "Missed 3 scheduled runs because this computer was asleep or OpenMausBot was not running", skipped: { count: 3, firstAt: START + HOUR, lastAt: START + 3 * HOUR } } });+ expect(late.older!.fields.skipped).not.toHaveProperty("told");+ expect(plan(interval(60), START + HOUR, START + HOUR + 10 * MINUTE)).toEqual({ scheduledFor: START + HOUR, first: START + HOUR, through: START + HOUR, count: 1, fields: {}, late: true });+ expect(plan(cron("0 9 * * *"), Date.parse("2026-11-16T09:00:00Z"), Date.parse("2026-11-18T10:00:00Z")).older?.fields.skipped)+ .toMatchObject({ count: 2, firstAt: Date.parse("2026-11-16T09:00:00Z"), lastAt: Date.parse("2026-11-17T09:00:00Z") });+ });++ it("closes them all, and tells the owner, when the newest is too old to run", () => {+ const daily = cron("0 9 * * *"), first = Date.parse("2026-11-16T09:00:00Z");+ const one = plan(daily, first, first + CATCH_UP_MS + 1);+ expect(one).toMatchObject({ scheduledFor: first, through: first, count: 1, late: false, fields: { status: "missed", errorCode: "routines.server.missedTooLate", errorParams: { hours: 12 } } });+ expect(one.fields).not.toHaveProperty("skipped");+ expect(one.fields).not.toHaveProperty("seenAt");+ expect(plan(daily, first, first + CATCH_UP_MS).fields).toEqual({});+ const three = plan(daily, first, first + 2 * DAY + 13 * HOUR, true);+ expect(three).toMatchObject({ scheduledFor: first, through: first + 2 * DAY, count: 3,+ fields: { status: "missed", error: "Missed 3 scheduled runs because this Cloud was asleep or restarting", skipped: { count: 3, firstAt: first, lastAt: first + 2 * DAY, told: true } } });+ expect(three.older).toBeUndefined();+ expect(nextOccurrence(daily, Math.max(first + 2 * DAY + 13 * HOUR, three.through))).toBe(first + 3 * DAY);+ });++ it("runs a limit reset however late, and misses a one-time run found more than twelve hours late", () => {+ const reset = { type: "limit_reset", engine: "claude", repeat: "every_reset", at: START } as RoutineSchedule;+ expect(plan(reset, START, START + 3 * DAY)).toMatchObject({ scheduledFor: START, count: 1, fields: {} });+ expect(plan({ type: "once", at: START }, START, START + 11 * HOUR)).toMatchObject({ scheduledFor: START, fields: {}, late: true });+ expect(plan({ type: "once", at: START }, START, START + 13 * HOUR).fields).toMatchObject({ status: "missed" });+ });++ it("says the scheduler was held up, not that the computer was asleep, when a pass ended after the run came due", () => {+ const held = planOccurrence({ schedule: interval(60), nextRunAt: START + HOUR }, START + 3 * HOUR + 10 * MINUTE, true, true);+ expect(held).toMatchObject({ scheduledFor: START + 3 * HOUR, late: true });+ expect(held.older!.fields).toMatchObject({ error: "Missed 2 scheduled runs because the scheduler was held up starting another run", errorParams: { why: "routines.server.part.heldUp" } });+ expect(held.older!.fields.skipped!.behind).toMatch(/^late:/);+ });++ it("spreads late starts over steps and wraps, so the last one is never far off", () => {+ expect(staggered(START, 0)).toEqual({});+ expect(staggered(START, 3)).toEqual({ retryAt: START + 3 * CATCH_UP_STAGGER_MS });+ expect(staggered(START, CATCH_UP_STAGGER_STEPS)).toEqual({});+ expect(staggered(START, 2 * CATCH_UP_STAGGER_STEPS - 1)).toEqual({ retryAt: START + (CATCH_UP_STAGGER_STEPS - 1) * CATCH_UP_STAGGER_MS });+ });+});diff --git a/server/routine-catch-up.ts b/server/routine-catch-up.tsnew file mode 100644index 0000000000..0f058d9e1c--- /dev/null+++ b/server/routine-catch-up.ts@@ -0,0 +1,148 @@+// What a routine does about the occurrences that came due while nothing could start them (the app closed, the computer+// asleep, a Cloud home off or restarting): the newest one runs late when it is still within CATCH_UP_MS of its time, and+// the ones before it close as missed on one row that counts them and says why. Late starts found in one scheduler pass+// are spread out, so a long downtime does not start every routine in the same second.+import { randomUUID } from "node:crypto";++import { runsOnce } from "../shared/limit-reset.ts";+import { intervalHasRestrictions } from "./routine-intervals.ts";+import { codedLine, type RoutineLineKey } from "./routine-lines.ts";+import { isOccurrenceRun } from "./routine-occurrences.ts";+import { routineRunDefinition } from "./routine-run-definition.ts";+import { nextOccurrence, type RoutineSchedule } from "./routine-schedules.ts";+import type { Routine, RoutineRun } from "./routines.ts";++/** An occurrence found later than this still runs only if it is the newest; older than this it is missed. */+export const CATCH_UP_MS = 12 * 60 * 60_000;+/** A row made later than this after its time is a late start, for the spreading below. */+export const CATCH_UP_LATE_MS = 2 * 60_000;+/** Late starts made in one pass begin this far apart, over at most this many steps. */+export const CATCH_UP_STAGGER_MS = 15_000;+export const CATCH_UP_STAGGER_STEPS = 40;+/** Occurrences walked one by one before the rest are estimated from their spacing. */+const WALK_LIMIT = 2_000;++type DownWhy = Extract<RoutineLineKey, "routines.server.part.computerOff" | "routines.server.part.cloudDown" | "routines.server.part.heldUp">;+const WHY_WORD: Record<DownWhy, string> = { "routines.server.part.computerOff": "down:computer", "routines.server.part.cloudDown": "down:cloud", "routines.server.part.heldUp": "late" };++/** From the occurrence at `first`, the newest one at or before `now`, and how many there are up to it. Past WALK_LIMIT+ * the count is an estimate. */+export function passedOccurrences(schedule: RoutineSchedule, first: number, now: number): { latest: number; count: number } {+ if (runsOnce(schedule) || schedule.type === "limit_reset" || now <= first) return { latest: first, count: 1 };+ if (schedule.type === "interval" && !intervalHasRestrictions(schedule)) {+ const every = schedule.everyMinutes * 60_000, steps = Math.floor((now - first) / every);+ return { latest: first + steps * every, count: steps + 1 };+ }+ let latest = first, count = 1;+ for (; count < WALK_LIMIT; count += 1) {+ const next = nextOccurrence(schedule, latest);+ if (next === null || next > now) return { latest, count };+ latest = next;+ }+ const spacing = Math.max(60_000, (latest - first) / (count - 1));+ for (let back = 4 * spacing; back <= 4_000 * spacing; back *= 10) {+ let at = nextOccurrence(schedule, Math.max(latest, now - back));+ if (at === null || at > now) continue;+ for (let walked = 0; walked < WALK_LIMIT; walked += 1) {+ const next = nextOccurrence(schedule, at);+ if (next === null || next > now) break;+ at = next;+ }+ return { latest: at, count: count + Math.max(1, Math.round((at - latest) / spacing)) };+ }+ return { latest, count };+}++export interface OccurrencePlan {+ /** The scheduled-for time of the row to make. */+ scheduledFor: number;+ /** The oldest occurrence dealt with: the routine's next run as it was. */+ first: number;+ /** The newest occurrence dealt with: the routine's next run is the first after it. */+ through: number;+ /** How many occurrences this deals with. */+ count: number;+ /** What the row is besides a queued run: nothing, or the fields of a missed row. */+ fields: Partial<RoutineRun>;+ /** The row starts late, so its start is spread out with the pass's other late starts. */+ late: boolean;+ /** The occurrences before the one that runs: one more row, already closed, that counts them. */+ older?: { scheduledFor: number; count: number; fields: Partial<RoutineRun> };+}++function missedFields(count: number, firstAt: number, lastAt: number, why: DownWhy, now: number, told: boolean): Partial<RoutineRun> {+ const line = !told || count > 1 ? codedLine("error", count > 1 ? "routines.server.missedMany" : "routines.server.missedOne", count > 1 ? { count, why } : { why })+ : codedLine("error", "routines.server.missedTooLate", { why, hours: CATCH_UP_MS / 3_600_000 });+ const counts = count > 1 || !told;+ return {+ status: "missed", finishedAt: now, error: line.text, ...line.codes, ...(told ? {} : { seenAt: now }),+ ...(counts ? { skipped: { count, firstAt, lastAt, behind: `${WHY_WORD[why]}:${now}`, ...(told ? { told: true as const } : {}) } } : {}),+ };+}++/** `heldUp`: a scheduler pass ended after the run came due, so the scheduler was at work and only got to it late (it was+ * waiting on another run's start): what it passed over is then said to be that, not a computer asleep or a Cloud down.+ * What to do with the routine's next run, which is due: run it; or, found late, run the newest occurrence passed and+ * close the older ones; or, with the newest too old as well, close them all on one row the owner is told about. A+ * limit reset is a state, not a moment: it still holds however late the computer wakes. */+export function planOccurrence(routine: Pick<Routine, "schedule" | "nextRunAt">, now: number, cloud: boolean, heldUp = false): OccurrencePlan {+ const first = routine.nextRunAt!, why: DownWhy = heldUp ? "routines.server.part.heldUp" : cloud ? "routines.server.part.cloudDown" : "routines.server.part.computerOff";+ const late = now - first > CATCH_UP_LATE_MS;+ const { latest, count } = late ? passedOccurrences(routine.schedule, first, now) : { latest: first, count: 1 };+ if (now - latest > CATCH_UP_MS && routine.schedule.type !== "limit_reset") {+ return { scheduledFor: first, first, through: latest, count, late: false, fields: missedFields(count, first, latest, why, now, true) };+ }+ const before = count > 1 ? lastBefore(routine.schedule, first, latest) : first;+ return {+ scheduledFor: latest, first, through: latest, count, late, fields: {},+ ...(count > 1 ? { older: { scheduledFor: first, count: count - 1, fields: missedFields(count - 1, first, before, why, now, false) } } : {}),+ };+}++/** The occurrence just before `latest`, for the last time an older row stands for; `first` when it cannot be found cheaply. */+function lastBefore(schedule: RoutineSchedule, first: number, latest: number): number {+ if (schedule.type === "interval" && !intervalHasRestrictions(schedule)) return latest - schedule.everyMinutes * 60_000;+ let at = first;+ for (let walked = 0; walked < WALK_LIMIT; walked += 1) {+ const next = nextOccurrence(schedule, at);+ if (next === null || next >= latest) return at;+ at = next;+ }+ return at;+}++/** The start of the `index`th late run made in one pass: the first at once, each next one a step later. */+export function staggered(now: number, index: number): Partial<RoutineRun> {+ const step = index % CATCH_UP_STAGGER_STEPS;+ return step === 0 ? {} : { retryAt: now + step * CATCH_UP_STAGGER_MS };+}++const ACTIVE = new Set<RoutineRun["status"]>(["queued", "running", "waiting"]);++/** After a restore from a backup, with `through` the time until which the schedule it replaced had been alive: every+ * occurrence up to then had its turn before the restore, so none of them runs again. Runs the backup held unfinished+ * are let go, and each routine's occurrences up to then close on one counted row; what came due after `through` is+ * caught up as after any downtime. Returns the rows changed or added. */+export function settleRestored(routines: Routine[], runs: RoutineRun[], through: number | null, now: number, advance: (routine: Routine, past: number) => void): RoutineRun[] {+ if (through === null) return [];+ const changed: RoutineRun[] = [], line = codedLine("error", "routines.server.restored");+ for (const run of runs) {+ if (!ACTIVE.has(run.status) || !isOccurrenceRun(run) || run.scheduledFor > through) continue;+ Object.assign(run, line.codes, { status: "cancelled", attention: undefined, error: line.text, finishedAt: now } satisfies Partial<RoutineRun>);+ if (run.target === "room-goal") run.goalStatus = "stopped";+ changed.push(run);+ }+ for (const routine of routines) {+ if (!routine.enabled || routine.checks || routine.nextRunAt == null || routine.nextRunAt > through || routine.schedule.type === "limit_reset") continue;+ const first = routine.nextRunAt, { latest, count } = passedOccurrences(routine.schedule, first, through);+ const counted = codedLine("error", "routines.server.restoredMany", { count });+ const row: RoutineRun = {+ id: randomUUID(), routineId: routine.id, ...routineRunDefinition(routine), scheduledFor: first, status: "missed", manual: false, triggerSource: "schedule",+ createdAt: now, finishedAt: now, seenAt: now, error: counted.text, ...counted.codes, skipped: { count, firstAt: first, lastAt: latest, behind: `restored:${through}` },+ };+ runs.push(row);+ advance(routine, latest);+ changed.push(row);+ }+ return changed;+}diff --git a/server/routine-ledger-faults.test.ts b/server/routine-ledger-faults.test.tsnew file mode 100644index 0000000000..feccb1be91--- /dev/null+++ b/server/routine-ledger-faults.test.ts@@ -0,0 +1,796 @@+// What the occurrence ledger promises under faults: every scheduled occurrence ends as ran, failed or missed with a+// reason, starts once, and shows in the health report's `schedule` section as the contract with the control plane says.+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { CATCH_UP_STAGGER_MS } from "./routine-catch-up.ts";+import { ledgerPaths, type Occurrence } from "./routine-ledger.ts";+import { LEASE_MS, UNRECORDED_START_PASSES } from "./routine-occurrences.ts";+import { TURN_GONE_MS } from "./routine-run-watch.ts";+import type { ScheduleSection } from "./routine-schedule-report.ts";+import { RoutineManager, type RoutineManagerOptions, type RoutineRun } from "./routines.ts";++const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR;+const START = Date.parse("2026-11-16T08:00:00Z");+const dirs: string[] = [];++function folder(): string {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-ledger-"));+ dirs.push(dir);+ return join(dir, "routines.json");+}++function harness(start = START, file = folder(), more: Partial<RoutineManagerOptions> = {}) {+ let now = start, bot: "ready" | "busy" | "missing" = "ready", task = 0, live: boolean | null = true;+ const started: string[] = [], prompts: string[] = [], failed: RoutineRun[] = [];+ const options: RoutineManagerOptions = {+ file, now: () => now, botState: () => bot, createTask: () => ({ threadId: `thread-${++task}` }),+ startTurn: async (_botId, threadId, prompt) => { started.push(threadId); prompts.push(prompt); },+ interruptTurn: async () => {}, onRunFailed: (run) => failed.push(run), turnLive: () => live, ...more,+ };+ const h = {+ file, options, started, prompts, failed, manager: new RoutineManager(options),+ at: (value: number) => { now = value; }, now: () => now, bot: (value: typeof bot) => { bot = value; }, live: (value: boolean | null) => { live = value; },+ tickAt: async (value: number) => { now = value; await h.manager.tick(); },+ passTo: async (to: number, step = MINUTE) => { while (now + step <= to) { now += step; await h.manager.tick(); } if (now < to) { now = to; await h.manager.tick(); } },+ /** The process is killed and another starts on the same files: nothing of the first is flushed or given up. */+ kill: () => (h.manager = new RoutineManager(options)),+ /** A clean shutdown, then a start. */+ restart: () => { h.manager.close(); return (h.manager = new RoutineManager(options)); },+ event: (threadId: string, type: string, extra: Record<string, unknown> = {}) =>+ h.manager.handleRuntimeEvent({ eventId: `${type}-${threadId}-${now}`, provider: "fake", threadId, createdAt: new Date(now).toISOString(), type, ...extra } as Parameters<RoutineManager["handleRuntimeEvent"]>[0]),+ done: (threadId: string) => h.event(threadId, "turn.completed", { ok: true }),+ runs: () => h.manager.listRuns().sort((a, b) => a.createdAt - b.createdAt || a.scheduledFor - b.scheduledFor),+ routine: () => h.manager.listRoutines()[0]!,+ report: () => invariants(h.manager.scheduleReport(), now),+ records: (routineId = h.manager.listRoutines()[0]!.id) => h.manager.occurrences(routineId),+ };+ return h;+}++/** What the home must keep true in every report (the contract's rules that one report can show). */+function invariants(section: ScheduleSection, now: number): ScheduleSection {+ expect(section.v).toBe(1);+ expect(Number.isSafeInteger(section.seq) && section.seq >= 0).toBe(true);+ if (section.nextDueAt !== null && section.nextDueAt <= now) {+ expect(section.oldestUnconfirmed, "a past nextDueAt comes with the occurrence that has not started").not.toBeNull();+ expect(section.oldestUnconfirmed!.dueAt).toBeLessThanOrEqual(section.nextDueAt);+ }+ if (section.oldestUnconfirmed) expect(section.oldestUnconfirmed.dueAt).toBeLessThanOrEqual(now);+ if (section.lastConfirmed) expect(section.lastConfirmed.startedAt === null).toBe(section.lastConfirmed.state === "missed" || section.lastConfirmed.state === "skipped");+ if (section.unreadable) expect([section.nextDueAt, section.oldestUnconfirmed, section.lastConfirmed]).toEqual([null, null, null]);+ return section;+}++const every = (minutes: number, extra: Record<string, unknown> = {}) => ({ name: "Fix new bugs", prompt: "Look for new bug reports and fix them", botId: "maus-1",+ schedule: { type: "interval" as const, everyMinutes: minutes, anchorAt: START }, ...extra });+const NONE = { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 };++afterEach(() => {+ vi.restoreAllMocks();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("an occurrence's record", () => {+ it("follows the run from due to queued to running to ran, and the report says each step", async () => {+ const h = harness();+ h.manager.create(every(60));+ expect(h.report()).toMatchObject({ unreadable: false, nextDueAt: START + HOUR, oldestUnconfirmed: null, lastConfirmed: null, due: { boot: NONE, day: NONE } });++ h.at(START + HOUR + 1_000);+ expect(h.report()).toMatchObject({ nextDueAt: START + HOUR, oldestUnconfirmed: { dueAt: START + HOUR, state: "due", since: START + HOUR }, lastConfirmed: null });++ h.bot("busy");+ await h.manager.tick();+ expect(h.records()).toMatchObject([{ dueAt: START + HOUR, state: "queued", attempts: 0 }]);+ expect(h.report()).toMatchObject({ nextDueAt: START + 2 * HOUR, oldestUnconfirmed: { dueAt: START + HOUR, state: "queued", since: START + HOUR + 1_000 }, lastConfirmed: null });++ h.bot("ready");+ await h.tickAt(START + HOUR + 7 * MINUTE);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.records()).toMatchObject([{ state: "running", attempts: 1, startedAt: START + HOUR + 7 * MINUTE, runIds: [h.runs()[0]!.id] }]);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + HOUR, startedAt: START + HOUR + 7 * MINUTE, state: "running" }, due: { boot: { ...NONE, late: 1 } } });++ h.done("thread-1");+ expect(h.records()).toMatchObject([{ state: "ran", attempts: 1, endedAt: START + HOUR + 7 * MINUTE }]);+ expect(h.records()[0]).not.toHaveProperty("lease");+ expect(h.report()).toMatchObject({ lastConfirmed: { dueAt: START + HOUR, state: "ran" }, due: { boot: { ...NONE, ran: 1, late: 1 }, day: { ...NONE, ran: 1, late: 1 } } });+ });++ it("is written before the turn starts, so the very next report names the run that started", async () => {+ const file = folder();+ let seen: ScheduleSection | undefined, onDisk = "";+ const h = harness(START, file, { startTurn: async () => { seen = h.manager.scheduleReport(); onDisk = readFileSync(ledgerPaths(file).ledger, "utf8"); } });+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ expect(seen).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + HOUR, startedAt: START + HOUR, state: "running" } });+ expect(onDisk.trim().split("\n").map((line) => JSON.parse(line) as { o?: Occurrence }).findLast((line) => line.o)?.o).toMatchObject({ state: "running", attempts: 1 });+ });++ it("never holds a routine's name, prompt or output, in the file or in the report", async () => {+ const h = harness();+ const routine = h.manager.create(every(60, { name: "Quarterly-Secret-Plan", prompt: "Email payroll-figures to the board" }));+ await h.tickAt(START + HOUR);+ h.event("thread-1", "item.completed", { itemType: "assistant_text", text: "Sent payroll-figures to [email protected]" });+ h.done("thread-1");+ await h.tickAt(START + 2 * HOUR);+ h.manager.failThread("thread-2", "Provider said: payroll-figures rejected", { cause: "refused" });+ h.manager.close();+ const written = [readFileSync(ledgerPaths(h.file).ledger, "utf8"), readFileSync(ledgerPaths(h.file).mark, "utf8"), JSON.stringify(h.report())];+ for (const text of written) for (const secret of ["Quarterly", "payroll", "[email protected]", "Email", "Provider said", "maus-1", "thread-1"]) expect(text).not.toContain(secret);+ expect(written[2]).not.toContain(routine.id);+ for (const run of h.runs()) expect(written[2]).not.toContain(run.id);+ expect(JSON.stringify(h.report()).length).toBeLessThan(1_000);+ });+});++describe("a server killed in the middle of a run", () => {+ it("starts the occurrence again once, in the same conversation, and counts both starts on one record", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ const seq = h.report().seq;++ h.kill();+ expect(h.report().seq).toBeGreaterThanOrEqual(seq);+ expect(h.runs()).toMatchObject([{ status: "queued", retried: "restarted" }]);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + HOUR, startedAt: START + HOUR, state: "running" } });+ await h.tickAt(START + HOUR + MINUTE);+ expect(h.started).toEqual(["thread-1", "thread-1"]);+ expect(h.prompts[1]).toContain("was cut off when OpenMausBot restarted");+ expect(h.records()).toMatchObject([{ dueAt: START + HOUR, state: "running", attempts: 2, startedAt: START + HOUR }]);+ expect(h.report().due.boot).toEqual({ ...NONE, retried: 1 });++ h.done("thread-1");+ await h.tickAt(START + HOUR + 2 * MINUTE);+ expect(h.started).toHaveLength(2);+ expect(h.records()).toMatchObject([{ state: "ran", attempts: 2 }]);+ expect(h.report().due.day).toEqual({ ...NONE, ran: 1, retried: 1 });+ });++ it("fails the occurrence once, with its reason, when the second start is cut too, and never starts it a third time", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.kill();+ await h.tickAt(START + HOUR + MINUTE);+ h.kill();+ expect(h.runs()).toMatchObject([{ status: "failed", error: "OpenMausBot restarted while this routine was running" }]);+ expect(h.records()).toMatchObject([{ state: "failed", attempts: 2, reason: "failed" }]);+ for (let minute = 2; minute < 60; minute += 5) await h.tickAt(START + HOUR + minute * MINUTE);+ expect(h.started).toEqual(["thread-1", "thread-1"]);+ expect(h.failed).toHaveLength(1);+ expect(h.report()).toMatchObject({ lastConfirmed: { dueAt: START + HOUR, state: "failed" }, due: { day: { ...NONE, failed: 1, retried: 1 } } });++ await h.tickAt(START + 2 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-1", "thread-2"]);+ expect(h.routine().enabled).toBe(true);+ });++ it("waits for another machine's lease to lapse before it starts a run that machine was running", async () => {+ const file = folder();+ const first = harness(START, file, { home: { machine: "machine-a" } });+ first.manager.create(every(60));+ await first.tickAt(START + HOUR);+ expect(first.records()[0]!.lease).toEqual({ machine: "machine-a", boot: expect.any(String), until: START + HOUR + LEASE_MS });++ const copy = harness(START + HOUR + 30_000, file, { home: { machine: "machine-b" } });+ expect(copy.runs()).toMatchObject([{ status: "queued", retried: "restarted", retryAt: START + HOUR + LEASE_MS + 1_000 }]);+ await copy.tickAt(START + HOUR + LEASE_MS);+ expect(copy.started).toEqual([]);+ await copy.tickAt(START + HOUR + LEASE_MS + 1_000);+ expect(copy.started).toEqual(["thread-1"]);++ const same = harness(START, folder(), { home: { machine: "machine-a" } });+ same.manager.create(every(60));+ await same.tickAt(START + HOUR);+ same.at(START + HOUR + 30_000);+ same.kill();+ expect(same.runs()).toMatchObject([{ status: "queued", retryAt: START + HOUR + 30_000 + 15_000 }]);+ });++ it("renews the lease while the run lives, and gives it up at a clean shutdown", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ const seq = h.report().seq;+ await h.passTo(START + HOUR + 10 * MINUTE);+ expect(h.records()[0]!.lease!.until).toBe(START + HOUR + 10 * MINUTE + LEASE_MS);+ expect(h.report().seq, "a renewed lease is no change to the report").toBe(seq);+ h.manager.close();+ expect(new RoutineManager(h.options).occurrences(h.routine().id)[0]).not.toHaveProperty("lease");+ });+});++describe("a computer asleep, or a server down, across due times", () => {+ it("runs the newest occurrence late and closes the ones before it on one row that counts them", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + 3 * HOUR + 20 * MINUTE);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs().map((run) => [run.scheduledFor, run.status])).toEqual([[START + HOUR, "missed"], [START + 3 * HOUR, "running"]]);+ expect(h.runs()[0]).toMatchObject({ error: "Missed 2 scheduled runs because this computer was asleep or OpenMausBot was not running", errorCode: "routines.server.missedMany",+ errorParams: { count: 2, why: "routines.server.part.computerOff" }, skipped: { count: 2, firstAt: START + HOUR, lastAt: START + 2 * HOUR }, seenAt: START + 3 * HOUR + 20 * MINUTE });+ expect(h.failed).toEqual([]);+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + 4 * HOUR });+ expect(h.records()).toMatchObject([+ { dueAt: START + 3 * HOUR, state: "running", attempts: 1 },+ { dueAt: START + HOUR, lastAt: START + 2 * HOUR, count: 2, state: "missed", reason: "computer-off", attempts: 0 },+ ]);+ expect(h.report()).toMatchObject({ nextDueAt: START + 4 * HOUR, oldestUnconfirmed: null, lastConfirmed: { dueAt: START + 3 * HOUR, state: "running" }, due: { boot: { ...NONE, missed: 2, late: 1 } } });+ });++ it("shows the overdue occurrence as due after a boot until the scheduler starts it, and never moves past it in silence", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ h.manager.close();++ h.at(START + 2 * HOUR + 40 * MINUTE);+ h.kill();+ expect(h.report()).toMatchObject({ nextDueAt: START + 2 * HOUR, oldestUnconfirmed: { dueAt: START + 2 * HOUR, state: "due", since: START + 2 * HOUR }, lastConfirmed: { dueAt: START + HOUR, state: "ran" } });+ await h.manager.tick();+ expect(h.report()).toMatchObject({ nextDueAt: START + 3 * HOUR, oldestUnconfirmed: null, lastConfirmed: { dueAt: START + 2 * HOUR, startedAt: START + 2 * HOUR + 40 * MINUTE, state: "running" } });+ });++ it("closes every occurrence on one row the owner is told about when even the newest is more than 12 hours old", async () => {+ const h = harness();+ const daily = { name: "Morning report", prompt: "Write the morning report", botId: "maus-1", schedule: { type: "interval" as const, everyMinutes: 1_440, anchorAt: START } };+ h.manager.create(daily);+ await h.tickAt(START + 3 * DAY + 13 * HOUR);+ expect(h.started).toEqual([]);+ expect(h.runs()).toMatchObject([{ status: "missed", scheduledFor: START + DAY, error: "Missed 3 scheduled runs because this computer was asleep or OpenMausBot was not running",+ skipped: { count: 3, firstAt: START + DAY, lastAt: START + 3 * DAY, told: true } }]);+ expect(h.runs()[0]).not.toHaveProperty("seenAt");+ expect(h.failed).toHaveLength(1);+ expect(h.report()).toMatchObject({ nextDueAt: START + 4 * DAY, oldestUnconfirmed: null, lastConfirmed: { dueAt: START + 3 * DAY, startedAt: null, state: "missed" }, due: { boot: { ...NONE, missed: 3 } } });++ const once = harness();+ once.manager.create({ ...daily, schedule: { type: "once" as const, at: START + HOUR } });+ await once.tickAt(START + 14 * HOUR);+ expect(once.runs()).toMatchObject([{ status: "missed", error: "Missed because this computer was asleep or OpenMausBot was not running until more than 12 hours after its time" }]);+ expect(once.runs()[0]).not.toHaveProperty("skipped");+ expect(once.records()).toMatchObject([{ state: "missed", reason: "computer-off" }]);+ });++ it("says a Cloud home was asleep or restarting", async () => {+ const h = harness(START, folder(), { home: { cloud: true } });+ h.manager.create(every(60));+ await h.tickAt(START + 2 * HOUR + 20 * MINUTE);+ expect(h.runs()[0]).toMatchObject({ status: "missed", error: "Missed because this Cloud was asleep or restarting", skipped: { count: 1 } });+ expect(h.records().at(-1)).toMatchObject({ state: "missed", reason: "cloud-down" });+ });++ it("spreads the late starts of many routines out instead of starting them all in one second", async () => {+ const h = harness();+ for (const index of [0, 1, 2, 3]) h.manager.create(every(60, { name: `Routine ${index}`, botId: `maus-${index}` }));+ await h.tickAt(START + HOUR + 30 * MINUTE);+ expect(h.started).toHaveLength(1);+ expect(h.runs().map((run) => run.retryAt).sort()).toEqual([START + HOUR + 30 * MINUTE + CATCH_UP_STAGGER_MS, START + HOUR + 30 * MINUTE + 2 * CATCH_UP_STAGGER_MS, START + HOUR + 30 * MINUTE + 3 * CATCH_UP_STAGGER_MS, undefined]);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: { dueAt: START + HOUR, state: "queued" } });+ await h.passTo(START + HOUR + 31 * MINUTE, CATCH_UP_STAGGER_MS);+ expect(h.started).toHaveLength(4);+ expect(h.report().oldestUnconfirmed).toBeNull();++ const onTime = harness();+ for (const index of [0, 1]) onTime.manager.create(every(60, { botId: `maus-${index}` }));+ await onTime.tickAt(START + HOUR);+ expect(onTime.started).toHaveLength(2);+ });++ it("counts occurrences that came due behind a run still at work on that run's row, the ones passed while asleep too", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ await h.tickAt(START + 4 * HOUR + 10 * MINUTE);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs()[1]).toMatchObject({ status: "missed", skipped: { count: 3, firstAt: START + 2 * HOUR, lastAt: START + 4 * HOUR }, error: "Skipped 3 scheduled runs because the previous run of this routine is still running" });+ expect(h.routine().skippedRuns).toBe(3);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + 4 * HOUR, startedAt: null, state: "skipped" } });+ });+});++describe("a clock that is set back or forward", () => {+ it("never starts an occurrence that already ran when the clock goes back before it", async () => {+ const h = harness();+ const routine = h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");++ h.at(START + 30 * MINUTE);+ await h.manager.tick();+ expect(h.routine().nextRunAt).toBe(START + 2 * HOUR);+ // An edit made while the clock is back works the next run out again from the earlier time.+ h.manager.update(routine.id, { schedule: { type: "interval", everyMinutes: 60, anchorAt: START + HOUR } });+ expect(h.routine().nextRunAt).toBe(START + HOUR);+ await h.tickAt(START + HOUR);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.routine().nextRunAt).toBe(START + 2 * HOUR);+ expect(h.records()).toMatchObject([{ dueAt: START + HOUR, state: "ran", attempts: 1 }]);+ expect(h.runs()).toHaveLength(1);+ await h.tickAt(START + 2 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });++ it("runs what a clock set forward brings due, and nothing twice when it is set back", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + DAY + HOUR + MINUTE);+ expect(h.runs().map((run) => [run.scheduledFor, run.status])).toEqual([[START + HOUR, "missed"], [START + DAY + HOUR, "running"]]);+ expect(h.runs()[0]!.skipped).toMatchObject({ count: 24, firstAt: START + HOUR, lastAt: START + DAY });+ h.done("thread-1");+ const seq = h.report().seq;++ h.at(START + 2 * HOUR);+ for (let hour = 2; hour <= 25; hour += 1) await h.tickAt(START + hour * HOUR);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.report().seq).toBeGreaterThanOrEqual(seq);+ await h.tickAt(START + DAY + 2 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });+});++describe("a clock that was days ahead", () => {+ it("does not let the span it closed swallow the occurrences that come after the clock is put right", async () => {+ const h = harness();+ const routine = h.manager.create(every(60));+ await h.tickAt(START + 3 * DAY + 5 * MINUTE);+ h.done("thread-1");+ expect(h.runs()[0]!.skipped).toMatchObject({ firstAt: START + HOUR, lastAt: START + 3 * DAY - HOUR });++ h.at(START + 2 * HOUR + 10 * MINUTE);+ h.manager.update(routine.id, { name: "Fix the newest bugs" });+ h.manager.update(routine.id, { schedule: { type: "interval", everyMinutes: 60, anchorAt: START + 30 * MINUTE } });+ expect(h.routine().nextRunAt).toBe(START + 2 * HOUR + 30 * MINUTE);+ const span = h.records().find((record) => record.state === "missed")!;+ expect(span).toMatchObject({ dueAt: START + HOUR, cut: START + 2 * HOUR + 10 * MINUTE, endedAt: START + 2 * HOUR + 10 * MINUTE });+ expect(span.lastAt ?? span.dueAt).toBeLessThanOrEqual(START + 2 * HOUR + 10 * MINUTE);+ for (const half of [5, 7, 9]) await h.tickAt(START + half * 30 * MINUTE).then(() => h.done(`thread-${(half - 1) / 2}`));+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3", "thread-4"]);++ // Asked about only when the occurrence is already due, with nothing saved since the clock went back.+ const late = harness();+ late.manager.create(every(60));+ await late.tickAt(START + 3 * DAY + 5 * MINUTE);+ late.done("thread-1");+ late.manager.close();+ const saved = JSON.parse(readFileSync(late.file, "utf8")) as { routines: Array<Record<string, unknown>> };+ saved.routines[0]!.nextRunAt = START + 5 * HOUR;+ writeFileSync(late.file, JSON.stringify(saved));+ late.at(START + 5 * HOUR + MINUTE);+ late.kill();+ await late.manager.tick();+ expect(late.started).toEqual(["thread-1", "thread-2"]);+ late.done("thread-2");+ await late.tickAt(START + 6 * HOUR);+ expect(late.started).toEqual(["thread-1", "thread-2", "thread-3"]);+ expect(late.report().due.day.missed).toBeLessThanOrEqual(5);+ });+});++describe("a scheduler pass held up by another run's start", () => {+ it("says so for what it passed over, and does not count it as missed", async () => {+ const file = folder();+ let release = () => {};+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const h = harness(START, file, { startTurn: async (_botId, threadId) => { h.started.push(threadId); if (threadId === "thread-1") await gate; } });+ h.manager.create(every(24 * 60, { anchorAt: undefined, schedule: { type: "interval" as const, everyMinutes: 1_440, anchorAt: START + HOUR } }));+ h.manager.create(every(60, { name: "Half past", botId: "maus-2", schedule: { type: "interval" as const, everyMinutes: 60, anchorAt: START + 90 * MINUTE } }));+ h.at(START + HOUR);+ const held = h.manager.tick();+ h.at(START + 3 * HOUR + 40 * MINUTE);+ release();+ await held;+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ const passed = h.runs().find((run) => run.skipped)!;+ expect(passed).toMatchObject({ status: "missed", seenAt: START + 3 * HOUR + 40 * MINUTE, error: "Missed 2 scheduled runs because the scheduler was held up starting another run",+ skipped: { count: 2, firstAt: START + 90 * MINUTE, lastAt: START + 150 * MINUTE } });+ expect(h.records(passed.routineId).at(-1)).toMatchObject({ state: "skipped", reason: "scheduler-late" });+ expect(h.report().due).toMatchObject({ boot: { missed: 0, late: 1 }, day: { missed: 0 } });+ });+});++describe("a restore from a backup", () => {+ async function ranThreeTimes() {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ return h;+ }+ const backup = (file: string) => { for (const path of [file, ledgerPaths(file).ledger]) copyFileSync(path, `${path}.backup`); };+ const restore = (file: string, ledger = true) => { for (const path of ledger ? [file, ledgerPaths(file).ledger] : [file]) copyFileSync(`${path}.backup`, path); };++ it("does not run again what ran after the backup was made, and reports a lower sequence number", async () => {+ const h = await ranThreeTimes();+ backup(h.file);+ await h.tickAt(START + 2 * HOUR);+ h.done("thread-2");+ await h.tickAt(START + 3 * HOUR);+ h.done("thread-3");+ const seq = h.report().seq;+ h.manager.close();++ restore(h.file);+ h.at(START + 3 * HOUR + 10 * MINUTE);+ h.kill();+ expect(h.report().seq).toBeLessThan(seq);+ expect(h.routine().nextRunAt).toBe(START + 4 * HOUR);+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3"]);+ expect(h.runs().at(-1)).toMatchObject({ status: "missed", seenAt: START + 3 * HOUR + 10 * MINUTE, skipped: { count: 2, firstAt: START + 2 * HOUR, lastAt: START + 3 * HOUR },+ error: "Not run again: 2 scheduled runs from before this schedule was restored from a backup" });+ expect(h.records()[0]).toMatchObject({ dueAt: START + 2 * HOUR, lastAt: START + 3 * HOUR, state: "skipped", reason: "restored" });+ expect(h.failed).toEqual([]);++ h.kill();+ await h.tickAt(START + 4 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3", "thread-4"]);+ expect(h.runs().filter((run) => run.skipped)).toHaveLength(1);+ });++ it("lets a run go that the backup held unfinished, and catches up what came due after the old schedule stopped", async () => {+ const h = await ranThreeTimes();+ await h.tickAt(START + 2 * HOUR);+ backup(h.file);+ h.done("thread-2");+ h.manager.close();++ restore(h.file);+ h.at(START + 5 * HOUR + 10 * MINUTE);+ h.kill();+ expect(h.runs().find((run) => run.scheduledFor === START + 2 * HOUR)).toMatchObject({ status: "cancelled", errorCode: "routines.server.restored" });+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3"]);+ expect(h.runs().filter((run) => run.status === "missed").map((run) => run.skipped)).toMatchObject([{ count: 2, firstAt: START + 3 * HOUR, lastAt: START + 4 * HOUR }]);+ expect(h.runs().at(-1)).toMatchObject({ scheduledFor: START + 5 * HOUR, status: "running" });+ });++ it("with only routines.json put back, the ledger still knows what ran", async () => {+ const h = await ranThreeTimes();+ backup(h.file);+ await h.tickAt(START + 2 * HOUR);+ h.done("thread-2");+ const seq = h.report().seq;+ h.manager.close();++ restore(h.file, false);+ h.at(START + 2 * HOUR + MINUTE);+ h.kill();+ expect(h.routine().nextRunAt).toBe(START + 2 * HOUR);+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ expect(h.routine().nextRunAt).toBe(START + 3 * HOUR);+ expect(h.report().seq).toBeGreaterThanOrEqual(seq);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + 2 * HOUR, state: "ran" } });+ });+});++describe("two scheduler passes at once", () => {+ it("start an occurrence once when they overlap in one process", async () => {+ const file = folder();+ let release = () => {};+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const h = harness(START, file, { startTurn: async (_botId, threadId) => { h.started.push(threadId); await gate; } });+ h.manager.create(every(60));+ h.at(START + HOUR);+ const passes = [h.manager.tick(), h.manager.tick(), h.manager.tick()];+ release();+ await Promise.all(passes);+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs()).toHaveLength(1);+ });++ it("start an occurrence once when two processes hold the same files", async () => {+ const file = folder();+ const first = harness(START, file);+ first.manager.create(every(60));+ const second = harness(START, file);+ await first.tickAt(START + HOUR);+ await second.tickAt(START + HOUR);+ expect([first.started, second.started]).toEqual([["thread-1"], []]);+ expect(second.routine().nextRunAt).toBe(START + 2 * HOUR);+ expect(second.runs()).toEqual([]);++ // The second gets there first, while the first is still held up behind a busy bot.+ first.done("thread-1");+ first.bot("busy");+ await first.tickAt(START + 2 * HOUR);+ await second.tickAt(START + 2 * HOUR);+ first.bot("ready");+ await first.tickAt(START + 2 * HOUR + MINUTE);+ expect([first.started, second.started]).toEqual([["thread-1"], ["thread-1"]]);+ expect(first.runs().at(-1)).toMatchObject({ status: "cancelled", error: "Not started: this scheduled run had already started once" });+ });+});++describe("a run whose turn is gone", () => {+ it("is started again once the host has said so for five minutes of passes, then failed with its reason", async () => {+ const h = harness();+ h.manager.create(every(24 * 60));+ await h.tickAt(START + DAY);+ h.live(false);+ await h.passTo(START + DAY + 4 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ h.event("thread-1", "item.completed", { itemType: "assistant_text", text: "Still working" });+ await h.passTo(START + DAY + 8 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ await h.passTo(START + DAY + 4 * MINUTE + TURN_GONE_MS + MINUTE);+ expect(h.runs()).toMatchObject([{ status: "queued", retried: "failed", attention: "Starting again shortly after a failure: its turn ended without reporting back" }]);++ await h.passTo(START + DAY + 12 * MINUTE);+ expect(h.started).toEqual(["thread-1", "thread-1"]);+ await h.passTo(START + DAY + 20 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Failed after one automatic retry: its turn ended without reporting back" }]);+ expect(h.records()).toMatchObject([{ state: "failed", attempts: 2, reason: "turn-gone" }]);+ expect(h.failed).toHaveLength(1);+ await h.passTo(START + DAY + HOUR);+ expect(h.started).toHaveLength(2);+ expect(h.routine().enabled).toBe(true);+ });++ it("is left alone while it waits on the person, while the host cannot tell, and across a sleep", async () => {+ const h = harness();+ h.manager.create(every(24 * 60));+ await h.tickAt(START + DAY);+ h.event("thread-1", "request.opened", { requestId: "ask-1", requestType: "question", tool: "ask", summary: "Which branch?" });+ h.live(false);+ await h.passTo(START + DAY + 30 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "waiting" }]);+ h.event("thread-1", "request.resolved", { requestId: "ask-1", source: "user" });++ h.live(null);+ await h.passTo(START + DAY + HOUR);+ expect(h.runs()).toMatchObject([{ status: "running" }]);++ h.live(false);+ await h.manager.tick();+ await h.tickAt(START + DAY + 9 * HOUR);+ await h.tickAt(START + DAY + 9 * HOUR + MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ });+});++describe("a run that waits on the person for more than a day", () => {+ it("keeps showing as started, hides no occurrence that has not, and gives way to the next occurrence", async () => {+ const h = harness();+ h.manager.create(every(24 * 60));+ await h.tickAt(START + DAY);+ h.event("thread-1", "request.opened", { requestId: "ask-1", requestType: "question", tool: "ask", summary: "Which branch?" });+ await h.passTo(START + DAY + 23 * HOUR, HOUR);+ expect(h.report()).toMatchObject({ nextDueAt: START + 2 * DAY, oldestUnconfirmed: null, lastConfirmed: { dueAt: START + DAY, startedAt: START + DAY, state: "running" } });++ await h.tickAt(START + 2 * DAY + MINUTE);+ expect(h.runs().map((run) => run.status)).toEqual(["cancelled", "running"]);+ expect(h.runs()[0]!.error).toBe("Stopped waiting: the next scheduled run of this routine started instead");+ expect(h.records()).toMatchObject([{ dueAt: START + 2 * DAY, state: "running" }, { dueAt: START + DAY, state: "failed", reason: "superseded", attempts: 1 }]);+ expect(h.report()).toMatchObject({ lastConfirmed: { dueAt: START + 2 * DAY, state: "running" }, due: { boot: { ...NONE, failed: 1 } } });+ });+});++describe("retries that run out", () => {+ it("fail the occurrence once after its one automatic retry, keep the routine on, and run the next occurrence", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.manager.failThread("thread-1", "The engine process exited");+ expect(h.runs()).toMatchObject([{ status: "queued", retried: "failed" }]);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + HOUR, state: "running" } });+ await h.tickAt(START + HOUR + MINUTE);+ h.manager.failThread("thread-1", "The engine process exited");+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Failed after one automatic retry: The engine process exited" }]);+ expect(h.records()).toMatchObject([{ state: "failed", attempts: 2, reason: "failed", startedAt: START + HOUR }]);+ expect(h.report()).toMatchObject({ lastConfirmed: { dueAt: START + HOUR, startedAt: START + HOUR, state: "failed" }, due: { boot: { ...NONE, failed: 1, retried: 1 }, day: { ...NONE, failed: 1, retried: 1 } } });+ await h.tickAt(START + 2 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-1", "thread-2"]);+ expect(h.routine().enabled).toBe(true);+ });++ it("does not count a start the bot refused as busy, and gives the occurrence up as missed after an hour of that", async () => {+ const file = folder();+ const h = harness(START, file, { startTurn: async () => { throw Object.assign(new Error("This conversation is busy"), { code: "thread_busy" }); } });+ h.manager.create(every(24 * 60));+ await h.tickAt(START + DAY);+ await h.passTo(START + DAY + 59 * MINUTE);+ expect(h.records()).toMatchObject([{ state: "queued", attempts: 0 }]);+ expect(h.records()[0]).not.toHaveProperty("startedAt");+ expect(h.report()).toMatchObject({ oldestUnconfirmed: { dueAt: START + DAY, state: "queued" }, due: { boot: NONE } });+ await h.passTo(START + DAY + 62 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "failed" }]);+ expect(h.records()).toMatchObject([{ state: "missed", attempts: 0, reason: "bot-busy" }]);+ expect(h.report()).toMatchObject({ oldestUnconfirmed: null, lastConfirmed: { dueAt: START + DAY, startedAt: null, state: "missed" } });+ });+});++describe("the files", () => {+ const rows = (count: number, routineId: string): RoutineRun[] => Array.from({ length: count }, (_, index) => ({+ id: `run-${index}`, routineId, routineName: "Fix new bugs", target: "bot" as const, botId: "maus-1", runOn: "maus" as const, scheduledFor: START - (count - index) * 5 * MINUTE,+ status: index % 50 === 7 ? "failed" as const : index % 50 === 9 ? "missed" as const : "completed" as const, manual: index % 100 === 3, triggerSource: index % 100 === 3 ? "manual" as const : "schedule" as const,+ createdAt: START - (count - index) * 5 * MINUTE, ...(index % 50 === 9 ? {} : { startedAt: START - (count - index) * 5 * MINUTE + 1_000 }),+ finishedAt: START - (count - index) * 5 * MINUTE + 60_000, ...(index % 50 === 7 ? { error: "Provider crashed", retried: "failed" as const } : {}),+ }));++ it("makes the ledger from a routines.json of 2,000 run rows written before there was one, losing none of them", async () => {+ const file = folder();+ const seed = harness(START - DAY, file);+ const routine = seed.manager.create(every(5));+ seed.manager.close();+ for (const path of Object.values(ledgerPaths(file))) rmSync(path, { force: true });+ const saved = JSON.parse(readFileSync(file, "utf8")) as { routines: Array<Record<string, unknown>>; runs: RoutineRun[] };+ saved.runs = rows(2_000, routine.id);+ saved.routines[0]!.nextRunAt = START;+ writeFileSync(file, JSON.stringify(saved));++ const h = harness(START - 1_000, file);+ expect(h.runs()).toHaveLength(2_000);+ const scheduled = saved.runs.filter((run) => !run.manual);+ expect(h.records()).toHaveLength(scheduled.length);+ expect(h.records().filter((record) => record.state === "failed")).toHaveLength(40);+ expect(h.records().find((record) => record.state === "failed")).toMatchObject({ attempts: 2, reason: "failed" });+ expect(h.records().filter((record) => record.state === "missed")).toHaveLength(40);+ expect(h.records().find((record) => record.state === "missed")).toMatchObject({ attempts: 0, reason: "not-started" });+ expect(h.report()).toMatchObject({ nextDueAt: START, oldestUnconfirmed: null, lastConfirmed: { dueAt: START - 5 * MINUTE, startedAt: START - 5 * MINUTE + 1_000, state: "ran" } });+ const lastDay = scheduled.filter((run) => run.finishedAt! > START - 1_000 - DAY), ended = (status: RoutineRun["status"]) => lastDay.filter((run) => run.status === status).length;+ expect(lastDay.length).toBeGreaterThan(280);+ expect(h.report().due.day).toEqual({ ran: ended("completed"), failed: ended("failed"), missed: ended("missed"), late: 0, retried: ended("failed") });+ expect(h.report().due.boot).toEqual(NONE);++ await h.tickAt(START);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs()).toHaveLength(2_000);+ const seq = h.report().seq;+ expect(new RoutineManager(h.options).scheduleReport().seq).toBeGreaterThanOrEqual(seq);+ });++ it("leaves routines.json as an earlier version reads it, and works again after that version ran without the ledger", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ h.manager.close();+ const saved = JSON.parse(readFileSync(h.file, "utf8")) as Record<string, unknown> & { routines: Array<Record<string, unknown>>; runs: RoutineRun[] };+ expect(Object.keys(saved).sort()).toEqual(["frozenResultsCleared", "routineRequestReceipts", "routines", "runs", "version", "webhookRunReceipts"]);+ expect(saved).toMatchObject({ version: 1, routines: [{ enabled: true, nextRunAt: START + 2 * HOUR }], runs: [{ status: "completed", scheduledFor: START + HOUR }] });++ // The earlier version runs the next occurrence and saves routines.json, knowing nothing of the ledger.+ saved.runs.push({ ...saved.runs[0]!, id: "made-by-the-earlier-version", scheduledFor: START + 2 * HOUR, createdAt: START + 2 * HOUR, startedAt: START + 2 * HOUR, finishedAt: START + 2 * HOUR + MINUTE });+ saved.routines[0]!.nextRunAt = START + 3 * HOUR;+ writeFileSync(h.file, JSON.stringify(saved));++ h.at(START + 2 * HOUR + 30 * MINUTE);+ h.kill();+ expect(h.manager.listRoutines()).toHaveLength(1);+ expect(h.records()).toMatchObject([{ dueAt: START + 2 * HOUR, state: "ran", attempts: 1 }, { dueAt: START + HOUR, state: "ran" }]);+ await h.tickAt(START + 3 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });++ it("writes nothing when a start finds nothing changed", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ h.manager.close();+ const { ledger, mark } = ledgerPaths(h.file), before = [readFileSync(h.file, "utf8"), readFileSync(ledger, "utf8"), readFileSync(mark, "utf8")];+ h.at(START + HOUR + 10 * MINUTE);+ h.kill();+ h.report();+ h.manager.close();+ expect([readFileSync(h.file, "utf8"), readFileSync(ledger, "utf8"), readFileSync(mark, "utf8")]).toEqual(before);+ });++ it("keeps what can be read of a ledger with a torn or damaged line, and never lowers the sequence number when the ledger is lost", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ const seq = h.report().seq, { ledger, mark } = ledgerPaths(h.file);+ h.manager.close();++ writeFileSync(ledger, `${readFileSync(ledger, "utf8")}{"s":${seq + 1},"o":{"routineId":"torn`);+ h.kill();+ expect(h.records()).toMatchObject([{ dueAt: START + HOUR, state: "ran" }]);+ expect(h.report().seq).toBeGreaterThanOrEqual(seq);+ await h.tickAt(START + 2 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ h.done("thread-2");+ const after = h.report().seq;+ h.manager.close();+ expect(new RoutineManager(h.options).occurrences(h.routine().id)).toMatchObject([{ dueAt: START + 2 * HOUR, state: "ran" }, { dueAt: START + HOUR, state: "ran" }]);++ rmSync(ledger);+ h.kill();+ expect(existsSync(mark)).toBe(true);+ expect(h.report().seq).toBeGreaterThan(after);+ expect(h.records()).toMatchObject([{ dueAt: START + 2 * HOUR, state: "ran" }, { dueAt: START + HOUR, state: "ran" }]);+ await h.tickAt(START + 3 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3"]);+ });++ it("says so in the report while routines.json cannot be read, with a sequence number that moved", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ const seq = h.report().seq;+ h.manager.close();+ vi.spyOn(console, "error").mockImplementation(() => {});+ writeFileSync(h.file, "{ not json");+ h.kill();+ const unreadable = h.report();+ expect(unreadable).toMatchObject({ unreadable: true, nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null });+ expect(unreadable.seq).toBeGreaterThan(seq);+ expect(h.report().seq).toBe(unreadable.seq);+ });++ it("holds a start back a few passes for a ledger that cannot be written, then runs without it, and never stops another run or a save", async () => {+ const h = harness();+ const hourly = h.manager.create(every(60));+ const other = h.manager.create(every(24 * 60, { name: "Weekly digest", botId: "maus-2" }));+ vi.spyOn(console, "error").mockImplementation(() => {});+ const { ledger } = ledgerPaths(h.file);+ // A folder where the file should be: every append fails, on Windows as on any other system.+ rmSync(ledger);+ mkdirSync(ledger);++ await h.tickAt(START + HOUR);+ expect(h.started).toEqual([]);+ h.manager.runNow(other.id);+ for (let pass = 1; pass <= UNRECORDED_START_PASSES - 1; pass += 1) await h.tickAt(START + HOUR + pass * 10_000);+ expect(h.started, "the run someone started by hand does not wait behind it").toEqual(["thread-1"]);+ expect(h.report().unreadable).toBe(false);+ await h.tickAt(START + HOUR + UNRECORDED_START_PASSES * 10_000);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ expect(h.report()).toMatchObject({ unreadable: true, nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null });++ h.done("thread-1");+ h.done("thread-2");+ const saved = () => (JSON.parse(readFileSync(h.file, "utf8")) as { runs: RoutineRun[] }).runs.map((run) => run.status).sort();+ expect(saved()).toEqual(["completed", "completed"]);+ for (let hour = 2; hour <= 6; hour += 1) {+ await h.tickAt(START + hour * HOUR);+ h.done(`thread-${hour + 1}`);+ }+ expect(h.started).toHaveLength(7);+ expect(saved().filter((status) => status === "completed")).toHaveLength(7);+ expect(h.failed).toEqual([]);++ // A process that starts while the ledger is still unwritable loads, picks a cut run up and saves its end.+ await h.tickAt(START + 7 * HOUR);+ h.kill();+ expect(h.runs().at(-1)).toMatchObject({ status: "queued", retried: "restarted" });+ for (let pass = 1; pass <= UNRECORDED_START_PASSES + 1; pass += 1) await h.tickAt(START + 7 * HOUR + pass * 20_000);+ expect(h.started.at(-1)).toBe("thread-8");+ h.event("thread-8", "turn.started");+ h.done("thread-8");+ expect(saved().filter((status) => status === "completed")).toHaveLength(8);++ rmSync(ledger, { recursive: true });+ await h.tickAt(START + 8 * HOUR);+ expect(h.report()).toMatchObject({ unreadable: false, lastConfirmed: { dueAt: START + 8 * HOUR, state: "running" } });+ expect(h.records(hourly.id).filter((record) => record.state === "ran")).toHaveLength(7);+ });++ it("makes an empty ledger again from the rows, and takes it for no restore", async () => {+ const h = harness();+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.done("thread-1");+ h.bot("busy");+ await h.tickAt(START + 2 * HOUR);+ h.manager.close();+ writeFileSync(ledgerPaths(h.file).ledger, "");+ h.at(START + 2 * HOUR + MINUTE);+ h.kill();+ expect(h.runs().map((run) => run.status)).toEqual(["completed", "queued"]);+ expect(h.records()).toMatchObject([{ dueAt: START + 2 * HOUR, state: "queued" }, { dueAt: START + HOUR, state: "ran" }]);+ h.bot("ready");+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });+});diff --git a/server/routine-ledger.test.ts b/server/routine-ledger.test.tsnew file mode 100644index 0000000000..348db13bfb--- /dev/null+++ b/server/routine-ledger.test.ts@@ -0,0 +1,194 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { LEDGER_KEEP_ALL_MS, LEDGER_KEEP_PER_ROUTINE, ledgerPaths, loadOccurrence, RoutineLedger, type Occurrence } from "./routine-ledger.ts";++const START = Date.parse("2026-11-16T08:00:00Z"), HOUR = 3_600_000;+const dirs: string[] = [];++function world(start = START) {+ const dir = mkdtempSync(join(tmpdir(), "omb-ledger-"));+ dirs.push(dir);+ const routines = join(dir, "routines.json"), clock = { now: start };+ const open = () => { const ledger = new RoutineLedger(routines, () => clock.now, 40); return { ledger, opened: ledger.open() }; };+ return { ...ledgerPaths(routines), clock, open };+}++const ran = (dueAt: number, more: Partial<Occurrence> = {}): Occurrence =>+ ({ routineId: "routine-1", dueAt, state: "ran", attempts: 1, startedAt: dueAt, madeAt: dueAt, endedAt: dueAt + 60_000, runIds: [`run-${dueAt}`], ...more });++afterEach(() => {+ vi.restoreAllMocks();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("the ledger file", () => {+ it("reads back what was appended, the last line for a key winning, and keeps its sequence number", () => {+ const w = world(), { ledger, opened } = w.open();+ expect(opened).toEqual({ state: "missing", restoredThrough: null });+ ledger.write([{ ...ran(START), state: "queued", attempts: 0, startedAt: undefined, endedAt: undefined }]);+ ledger.write([ran(START)]);+ ledger.write([ran(START + HOUR, { state: "missed", attempts: 0, count: 3, lastAt: START + 3 * HOUR })]);+ expect(ledger.seq).toBe(3);++ const again = w.open();+ expect(again.opened).toEqual({ state: "ok", restoredThrough: null });+ expect(again.ledger.seq).toBe(3);+ expect(again.ledger.get("routine-1", START)).toMatchObject({ state: "ran", attempts: 1 });+ expect(again.ledger.ofRun(`run-${START}`)?.dueAt).toBe(START);+ expect(again.ledger.covering("routine-1", START + 2 * HOUR)?.dueAt).toBe(START + HOUR);+ expect(again.ledger.covering("routine-1", START + 4 * HOUR)).toBeUndefined();+ expect(again.ledger.covering("routine-2", START)).toBeUndefined();+ expect(again.ledger.size).toBe(2);+ });++ it("drops a record whose removal was written, and a lease is renewed without raising the sequence number", () => {+ const w = world(), { ledger } = w.open();+ const queued: Occurrence = { ...ran(START), state: "queued", attempts: 0, startedAt: undefined, endedAt: undefined };+ ledger.write([queued, ran(START + HOUR, { state: "running", endedAt: undefined, lease: { machine: "m", boot: "b", until: START + 1 }})]);+ ledger.write([], [queued]);+ const seq = ledger.seq;+ ledger.write([ran(START + HOUR, { state: "running", endedAt: undefined, lease: { machine: "m", boot: "b", until: START + 2 } })], [], false);+ expect(ledger.seq).toBe(seq);+ const again = w.open().ledger;+ expect(again.seq).toBe(seq);+ expect([...again.all()]).toMatchObject([{ dueAt: START + HOUR, lease: { until: START + 2 } }]);+ expect(again.ofRun(`run-${START}`)).toBeUndefined();+ });++ it("keeps every whole line of a file whose last line was torn, and its next append starts a new line", () => {+ const w = world(), { ledger } = w.open();+ ledger.write([ran(START)]);+ writeFileSync(w.ledger, `${readFileSync(w.ledger, "utf8")}{"s":2,"o":{"routineId":"rout`);+ const torn = w.open();+ expect(torn.opened.state).toBe("damaged");+ expect([...torn.ledger.all()]).toHaveLength(1);+ torn.ledger.write([ran(START + HOUR)]);+ const again = w.open();+ expect(again.opened.state).toBe("ok");+ expect([...again.ledger.all()].map((record) => record.dueAt)).toEqual([START, START + HOUR]);+ expect(again.ledger.seq).toBe(3);+ });++ it("drops a line that is not a record, and nothing else", () => {+ const w = world();+ writeFileSync(w.ledger, [JSON.stringify({ v: 1, s: 9 }), JSON.stringify({ s: 10, o: ran(START) }), "not json", JSON.stringify({ s: 11, o: { ...ran(START + HOUR), state: "exploded" } }),+ JSON.stringify({ s: 12, o: { ...ran(START + 2 * HOUR), routineId: "../../etc/passwd" } }), JSON.stringify({ o: ran(START + 3 * HOUR) }), ""].join("\n"));+ const { ledger, opened } = w.open();+ expect(opened.state).toBe("damaged");+ expect([...ledger.all()].map((record) => record.dueAt)).toEqual([START]);+ expect(ledger.seq).toBe(12);+ expect(loadOccurrence({ ...ran(START), count: 1, lastAt: START - 1, reason: "made-up", lease: { machine: "m" } })).toEqual(ran(START));+ });++ it("is rewritten whole once it has grown, keeps what is not ended, and lets old ended records go routine by routine", () => {+ const w = world(START + 100 * 24 * HOUR), { ledger } = w.open();+ const old = Array.from({ length: LEDGER_KEEP_PER_ROUTINE + 40 }, (_, index) => ran(START + index * HOUR));+ ledger.write(old);+ ledger.write([ran(START - HOUR, { routineId: "routine-2" }), { ...ran(START - 2 * HOUR, { routineId: "routine-3" }), state: "queued", attempts: 0, endedAt: undefined }]);+ const recent = Array.from({ length: 30 }, (_, index) => ran(w.clock.now - LEDGER_KEEP_ALL_MS + (index + 1) * 60_000, { routineId: "routine-4" }));+ ledger.write(recent);+ for (let changes = 0; changes < 50; changes += 1) ledger.write([], [], true);+ const lines = readFileSync(w.ledger, "utf8").trim().split("\n");+ expect(lines.length).toBeLessThan(60);+ expect(JSON.parse(lines[0]!)).toMatchObject({ v: 1 });++ const again = w.open();+ expect(again.opened.state).toBe("ok");+ expect(again.ledger.seq).toBe(ledger.seq);+ expect(again.ledger.ofRoutine("routine-1")).toHaveLength(0);+ expect(again.ledger.ofRoutine("routine-2")).toHaveLength(0);+ expect(again.ledger.ofRoutine("routine-3")).toMatchObject([{ state: "queued" }]);+ expect(again.ledger.ofRoutine("routine-4")).toHaveLength(30);+ });++ it("keeps each routine's newest ended records past two days, however many another routine makes", () => {+ const w = world(START + 10 * 24 * HOUR), { ledger } = w.open();+ ledger.write(Array.from({ length: LEDGER_KEEP_PER_ROUTINE + 60 }, (_, index) => ran(START + index * 300_000, { routineId: "every-five-minutes" })));+ ledger.write([ran(START), ran(START + 24 * HOUR)]);+ for (let changes = 0; changes < 50; changes += 1) ledger.write([], [], true);+ const again = w.open().ledger;+ expect(again.ofRoutine("every-five-minutes")).toHaveLength(LEDGER_KEEP_PER_ROUTINE);+ expect(again.get("every-five-minutes", START)).toBeUndefined();+ expect(again.ofRoutine("routine-1")).toHaveLength(2);+ });+});++describe("the mark beside the ledger", () => {+ it("tells a ledger brought back from a backup by its lower sequence number, and until when the newer one was alive", () => {+ const w = world(), { ledger } = w.open();+ ledger.write([ran(START)]);+ const backup = readFileSync(w.ledger, "utf8");+ w.clock.now = START + 2 * HOUR;+ ledger.write([ran(START + HOUR)]);+ ledger.write([ran(START + 2 * HOUR)]);++ writeFileSync(w.ledger, backup);+ w.clock.now = START + 5 * HOUR;+ const restored = w.open();+ expect(restored.opened).toEqual({ state: "ok", restoredThrough: START + 2 * HOUR });+ expect(restored.ledger.seq).toBe(1);+ restored.ledger.write([ran(START + 5 * HOUR)]);+ expect(w.open().opened.restoredThrough).toBeNull();+ });++ it("carries the sequence number past a ledger that is lost or damaged, and takes neither for a restore", () => {+ const w = world(), { ledger } = w.open();+ for (const hour of [0, 1, 2]) ledger.write([ran(START + hour * HOUR)]);+ rmSync(w.ledger);+ const lost = w.open();+ expect(lost.opened).toEqual({ state: "missing", restoredThrough: null });+ expect(lost.ledger.seq).toBe(4);+ lost.ledger.write([ran(START)]);+ const seq = lost.ledger.seq;++ writeFileSync(w.ledger, "garbage\n");+ const damaged = w.open();+ expect(damaged.opened).toEqual({ state: "damaged", restoredThrough: null });+ expect(damaged.ledger.seq).toBeGreaterThan(seq);+ rmSync(w.mark);+ expect(w.open().opened.restoredThrough).toBeNull();+ });++ it("takes an empty ledger for a lost one, never for a restore", () => {+ const w = world(), { ledger } = w.open();+ for (const hour of [0, 1, 2]) ledger.write([ran(START + hour * HOUR)]);+ for (const empty of ["", "\n", " \n"]) {+ writeFileSync(w.ledger, empty);+ const opened = w.open();+ expect(opened.opened).toEqual({ state: "missing", restoredThrough: null });+ expect(opened.ledger.seq).toBe(4);+ expect(opened.ledger.sync()).toBe(false);+ }+ });++ it("reads the file again only when another process has written to it", () => {+ const w = world(), mine = w.open().ledger;+ mine.write([ran(START)]);+ expect(mine.sync()).toBe(false);+ const theirs = w.open().ledger;+ theirs.write([ran(START + HOUR)]);+ expect(mine.sync()).toBe(true);+ expect(mine.get("routine-1", START + HOUR)).toMatchObject({ state: "ran" });+ expect(mine.seq).toBe(theirs.seq);+ expect(mine.sync()).toBe(false);+ });++ it("leaves memory as it was when a write fails, and when the file cannot be read again", () => {+ const w = world(), { ledger } = w.open();+ ledger.write([ran(START)]);+ vi.spyOn(console, "error").mockImplementation(() => {});+ // A folder where the file should be: neither an append nor a read works, on Windows as on any other system.+ rmSync(w.ledger);+ mkdirSync(w.ledger);+ expect(() => ledger.write([ran(START + HOUR)])).toThrow();+ ledger.sync();+ expect(ledger.seq).toBe(1);+ expect([...ledger.all()].map((record) => record.dueAt)).toEqual([START]);+ rmSync(w.ledger, { recursive: true });+ ledger.write([ran(START + HOUR)]);+ expect(w.open().ledger.get("routine-1", START + HOUR)).toBeDefined();+ });+});diff --git a/server/routine-ledger.ts b/server/routine-ledger.tsnew file mode 100644index 0000000000..678ec1e3e1--- /dev/null+++ b/server/routine-ledger.ts@@ -0,0 +1,305 @@+// The occurrence ledger's file: one record per scheduled occurrence of each routine, keyed by the routine's id and the+// scheduled-for time. It sits beside routines.json as JSON lines, appended and flushed one change at a time (a start is+// on disk before its turn begins) and rewritten whole, atomically, when it has grown past its records. A record holds+// ids, times, counts and fixed words only: nothing of a routine's name, prompt or output. A second small file, the mark,+// keeps the sequence number and time of this folder's last change, so a ledger brought back from a backup is recognised and a+// lost ledger never starts its sequence again from zero.+import { appendFileSync, closeSync, fstatSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";+import { basename, dirname, join } from "node:path";++import { writeFileAtomic } from "./atomic.ts";++export type OccurrenceState = "queued" | "running" | "ran" | "failed" | "missed" | "skipped";+export const OCCURRENCE_STATES: readonly OccurrenceState[] = ["queued", "running", "ran", "failed", "missed", "skipped"];++/** Why an occurrence ended as it did, as a fixed word. */+export const OCCURRENCE_REASONS = [+ "previous-run-active", "computer-no-start", "bot-busy", "computer-off", "cloud-down", "scheduler-late", "restored", "run-limit",+ "superseded", "restarted", "turn-gone", "cancelled", "failed", "not-started",+] as const;+export type OccurrenceReason = typeof OCCURRENCE_REASONS[number];++/** Who is running a started occurrence, renewed while its run lives: another machine holding the same data waits for it to lapse. */+export interface OccurrenceLease { machine: string; boot: string; until: number }++export interface Occurrence {+ routineId: string;+ /** Its scheduled-for time; on a record that stands for several occurrences, the first of them. */+ dueAt: number;+ state: OccurrenceState;+ reason?: OccurrenceReason;+ /** Starts so far. */+ attempts: number;+ /** When its first attempt started. */+ startedAt?: number;+ /** The start counted last, so one start is never counted twice. */+ lastStartAt?: number;+ madeAt: number;+ endedAt?: number;+ /** The occurrences it stands for, when more than one, and the scheduled-for time of the last. */+ count?: number;+ lastAt?: number;+ /** A record written while the clock was ahead stands for nothing after this time, however far its row says it reaches. */+ cut?: number;+ /** Closed for a time that had not come: it stands for no occurrence, and one due at its time is still made. */+ void?: true;+ /** The run rows it produced. */+ runIds: string[];+ lease?: OccurrenceLease;+}++/** Records that have ended are kept this long whatever their number, so the last day's counts are whole. */+export const LEDGER_KEEP_ALL_MS = 48 * 60 * 60_000;+/** Older than that, each routine keeps its newest ended records up to this many, for this long. */+export const LEDGER_KEEP_PER_ROUTINE = 200;+export const LEDGER_KEEP_MS = 90 * 24 * 60 * 60_000;+export const LEDGER_MAX_RECORDS = 10_000;+const COMPACT_SLACK_LINES = 500;+const MAX_SEQ = 1e15, MAX_TIME = 1e15;+const ID = /^[\w:-]{1,64}$/;+const ENDED = new Set<OccurrenceState>(["ran", "failed", "missed", "skipped"]);++export const occurrenceEnded = (occurrence: Pick<Occurrence, "state">) => ENDED.has(occurrence.state);+/** The scheduled-for time of the newest occurrence the record stands for. */+export const occurrenceLastAt = (occurrence: Pick<Occurrence, "dueAt" | "lastAt">) => occurrence.lastAt ?? occurrence.dueAt;++export function ledgerPaths(routinesFile: string): { ledger: string; mark: string } {+ const stem = join(dirname(routinesFile), basename(routinesFile, ".json"));+ return { ledger: `${stem}.ledger.jsonl`, mark: `${stem}.ledger.mark` };+}++const time = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= MAX_TIME;+const optionalTime = (value: unknown): number | undefined => time(value) ? value : undefined;++/** A record as the file may hold it; anything out of shape is dropped whole. */+export function loadOccurrence(value: unknown): Occurrence | null {+ const saved = value as Partial<Occurrence> | null;+ if (!saved || typeof saved !== "object" || typeof saved.routineId !== "string" || !ID.test(saved.routineId) || !time(saved.dueAt) || !time(saved.madeAt) ||+ !OCCURRENCE_STATES.includes(saved.state as OccurrenceState) || !Number.isSafeInteger(saved.attempts) || saved.attempts! < 0 || saved.attempts! > 1_000_000 ||+ !Array.isArray(saved.runIds) || saved.runIds.length > 50 || !saved.runIds.every((id) => typeof id === "string" && ID.test(id))) return null;+ const lease = saved.lease, counted = Number.isSafeInteger(saved.count) && saved.count! > 1 && time(saved.lastAt) && saved.lastAt >= saved.dueAt;+ return {+ routineId: saved.routineId, dueAt: saved.dueAt, state: saved.state!, attempts: saved.attempts!, madeAt: saved.madeAt, runIds: [...saved.runIds],+ ...(OCCURRENCE_REASONS.includes(saved.reason as OccurrenceReason) ? { reason: saved.reason } : {}),+ ...(optionalTime(saved.startedAt) === undefined ? {} : { startedAt: saved.startedAt }),+ ...(optionalTime(saved.lastStartAt) === undefined ? {} : { lastStartAt: saved.lastStartAt }),+ ...(optionalTime(saved.endedAt) === undefined ? {} : { endedAt: saved.endedAt }),+ ...(counted ? { count: saved.count, lastAt: saved.lastAt } : {}),+ ...(optionalTime(saved.cut) === undefined ? {} : { cut: saved.cut }), ...(saved.void === true ? { void: true as const } : {}),+ ...(lease && typeof lease.machine === "string" && ID.test(lease.machine) && typeof lease.boot === "string" && ID.test(lease.boot) && time(lease.until)+ ? { lease: { machine: lease.machine, boot: lease.boot, until: lease.until } } : {}),+ };+}++interface LedgerMark { seq: number; at: number }++/** One line of the file: a sequence number, with a record to keep (`o`) or the key of one to drop (`x`). Null for a torn or damaged line. */+function parseLine(line: string): { s: number; o?: unknown; x?: unknown } | null {+ try {+ const entry = JSON.parse(line) as { s?: unknown; o?: unknown; x?: unknown } | null;+ return entry && typeof entry === "object" && Number.isSafeInteger(entry.s) && (entry.s as number) >= 0 && (entry.s as number) <= MAX_SEQ ? { ...entry, s: entry.s as number } : null;+ } catch { return null; }+}++export interface LedgerOpened {+ /** missing: no ledger yet. damaged: some of it could not be read, and what could is kept. */+ state: "ok" | "missing" | "damaged";+ /** The ledger is older than the last one this folder wrote, which was alive until this time: it came from a backup. */+ restoredThrough: number | null;+}++export class RoutineLedger {+ readonly file: string;+ private readonly mark: string;+ private readonly now: () => number;+ private readonly byRoutine = new Map<string, Map<number, Occurrence>>();+ private readonly byRun = new Map<string, Occurrence>();+ private sequence = 0;+ private lines = 0;+ private bytes = 0;+ private endsMidLine = false;+ private total = 0;+ private changes = 0;+ private readonly slack: number;++ /** `slack`: how many more lines than records the file may hold before it is rewritten. */+ constructor(routinesFile: string, now: () => number, slack = COMPACT_SLACK_LINES) {+ ({ ledger: this.file, mark: this.mark } = ledgerPaths(routinesFile));+ this.now = now;+ this.slack = slack;+ }++ get seq(): number { return this.sequence; }+ /** Goes up whenever the records in memory may have changed. */+ get version(): number { return this.changes; }+ get size(): number { return this.total; }++ open(): LedgerOpened {+ const mark = this.readMark(), text = this.text(), state = text === undefined ? "damaged" : this.read(text);+ const restored = state === "ok" && mark !== null && this.sequence < mark.seq;+ // The mark is written with every change, so it holds the last sequence number even when the ledger itself is lost.+ if (!restored && mark) this.sequence = Math.min(MAX_SEQ, Math.max(this.sequence, state === "ok" ? mark.seq : mark.seq + 1));+ if (state === "damaged" && text !== undefined) this.compact();+ return { state, restoredThrough: restored ? mark.at : null };+ }++ get(routineId: string, dueAt: number): Occurrence | undefined { return this.byRoutine.get(routineId)?.get(dueAt); }+ ofRun(runId: string): Occurrence | undefined { return this.byRun.get(runId); }+ ofRoutine(routineId: string): Occurrence[] { return [...this.byRoutine.get(routineId)?.values() ?? []]; }+ *all(): IterableIterator<Occurrence> { for (const records of this.byRoutine.values()) yield* records.values(); }++ /** The record that stands for the occurrence at `dueAt`: its own, or one counting a span of occurrences that holds it. */+ covering(routineId: string, dueAt: number): Occurrence | undefined {+ const records = this.byRoutine.get(routineId), own = records?.get(dueAt);+ if (own || !records) return own;+ for (const record of records.values()) if (record.lastAt !== undefined && record.dueAt <= dueAt && dueAt <= record.lastAt) return record;+ return undefined;+ }++ /** Appends the changes and flushes them before anything in memory changes: a failed write leaves the ledger as it+ * was, and throws. `counted` false writes without raising the sequence (a renewed lease changes nothing a reader counts). */+ write(put: readonly Occurrence[], remove: readonly Occurrence[] = [], counted = true): void {+ if (put.length === 0 && remove.length === 0 && !counted) return;+ let seq = this.sequence;+ const step = () => counted ? (seq = Math.min(MAX_SEQ, seq + 1)) : seq;+ const lines = [...put.map((o) => JSON.stringify({ s: step(), o })), ...remove.map((gone) => JSON.stringify({ s: step(), x: [gone.routineId, gone.dueAt] }))];+ if (lines.length === 0) lines.push(JSON.stringify({ s: step() }));+ const text = `${this.endsMidLine ? "\n" : ""}${lines.join("\n")}\n`;+ try {+ mkdirSync(dirname(this.file), { recursive: true });+ appendFileSync(this.file, text, { mode: 0o600, flush: true });+ } catch (error) {+ this.endsMidLine = true;+ throw error;+ }+ this.endsMidLine = false;+ this.sequence = seq;+ this.bytes += Buffer.byteLength(text);+ this.lines += lines.length;+ this.changes += 1;+ for (const gone of remove) this.drop(gone);+ for (const record of put) this.keep(record);+ if (this.lines > this.total + this.slack) this.compact();+ if (counted) this.writeMark();+ }++ /** Whether the file can be opened for appending now. Windows opens a folder of that name without complaint, so what was opened is looked at too. */+ writable(): boolean {+ let fd: number | undefined;+ try {+ mkdirSync(dirname(this.file), { recursive: true });+ fd = openSync(this.file, "a", 0o600);+ return fstatSync(fd).isFile();+ } catch { return false; }+ finally { if (fd !== undefined) try { closeSync(fd); } catch { /* nothing was written through it */ } }+ }++ /** Reads the file again when something else has written to it since this process last did. True when it had. A+ * file that cannot be read just now leaves what is in memory as it is. */+ sync(): boolean {+ let size: number;+ try { size = statSync(this.file).size; } catch { size = 0; }+ if (size === this.bytes) return false;+ const text = this.text(), seq = this.sequence;+ if (text === undefined) return false;+ this.read(text);+ this.sequence = Math.max(seq, this.sequence);+ return true;+ }++ /** The file's text; null when there is no file, undefined when it is there and cannot be read. */+ private text(): string | null | undefined {+ try { return readFileSync(this.file, "utf8"); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;+ console.error(`routines: the run ledger ${this.file} cannot be read`);+ return undefined;+ }+ }++ private keep(record: Occurrence): void {+ const records = this.byRoutine.get(record.routineId) ?? new Map<number, Occurrence>();+ this.byRoutine.set(record.routineId, records);+ const before = records.get(record.dueAt);+ if (!before) this.total += 1;+ for (const id of before?.runIds ?? []) if (this.byRun.get(id) === before) this.byRun.delete(id);+ records.set(record.dueAt, record);+ for (const id of record.runIds) this.byRun.set(id, record);+ }++ private drop(gone: Pick<Occurrence, "routineId" | "dueAt">): void {+ const records = this.byRoutine.get(gone.routineId), record = records?.get(gone.dueAt);+ if (!records || !record) return;+ records.delete(gone.dueAt);+ this.total -= 1;+ if (records.size === 0) this.byRoutine.delete(gone.routineId);+ for (const id of record.runIds) if (this.byRun.get(id) === record) this.byRun.delete(id);+ }++ private read(text: string | null): LedgerOpened["state"] {+ this.byRoutine.clear(); this.byRun.clear(); this.changes += 1;+ this.sequence = 0; this.lines = 0; this.bytes = 0; this.total = 0; this.endsMidLine = false;+ // An empty file holds no ledger: it is made again from the rows, like one that is not there.+ if (text === null || text.trim() === "") { this.bytes = text === null ? 0 : Buffer.byteLength(text); this.endsMidLine = Boolean(text) && !text!.endsWith("\n"); return "missing"; }+ this.bytes = Buffer.byteLength(text);+ this.endsMidLine = text.length > 0 && !text.endsWith("\n");+ let damaged = this.endsMidLine;+ for (const line of text.split("\n")) {+ if (!line) continue;+ this.lines += 1;+ const entry = parseLine(line);+ if (!entry) { damaged = true; continue; }+ this.sequence = Math.max(this.sequence, entry.s);+ if (Array.isArray(entry.x)) this.drop({ routineId: String(entry.x[0]), dueAt: Number(entry.x[1]) });+ else if (entry.o !== undefined) {+ const record = loadOccurrence(entry.o);+ if (record) this.keep(record); else damaged = true;+ }+ }+ return damaged ? "damaged" : "ok";+ }++ /** Ended records past their keep, oldest first. A record that has not ended is never dropped here. */+ private expired(): Occurrence[] {+ const now = this.now(), gone: Occurrence[] = [], kept: Occurrence[] = [];+ // Never later than now: a time stamped while the clock was ahead does not keep a record past its keep.+ const endedAt = (record: Occurrence) => Math.min(now, record.endedAt ?? occurrenceLastAt(record));+ for (const records of this.byRoutine.values()) {+ const ended = [...records.values()].filter(occurrenceEnded).sort((a, b) => occurrenceLastAt(b) - occurrenceLastAt(a));+ ended.forEach((record, index) => {+ const age = now - endedAt(record);+ (age > LEDGER_KEEP_MS || (age > LEDGER_KEEP_ALL_MS && index >= LEDGER_KEEP_PER_ROUTINE) ? gone : kept).push(record);+ });+ }+ const over = this.total - gone.length - LEDGER_MAX_RECORDS;+ if (over > 0) gone.push(...kept.sort((a, b) => endedAt(a) - endedAt(b)).slice(0, over));+ return gone;+ }++ /** Rewrites the file as one line per record. A rewrite that fails leaves the longer file, which reads the same. */+ private compact(): void {+ for (const record of this.expired()) this.drop(record);+ const text = `${[JSON.stringify({ v: 1, s: this.sequence }), ...[...this.all()].map((o) => JSON.stringify({ s: this.sequence, o }))].join("\n")}\n`;+ try {+ writeFileAtomic(this.file, text, { mode: 0o600 });+ this.bytes = Buffer.byteLength(text);+ this.lines = this.total + 1;+ this.endsMidLine = false;+ } catch (error) {+ this.lines = this.total;+ console.error("routines: could not rewrite the run ledger; it stays as it is and is rewritten later", error);+ }+ }++ private readMark(): LedgerMark | null {+ try {+ const saved = JSON.parse(readFileSync(this.mark, "utf8")) as Partial<LedgerMark> | null;+ return saved && Number.isSafeInteger(saved.seq) && saved.seq! >= 0 && saved.seq! <= MAX_SEQ && time(saved.at) ? { seq: saved.seq!, at: saved.at } : null;+ } catch { return null; }+ }++ private writeMark(): void {+ try { writeFileAtomic(this.mark, JSON.stringify({ v: 1, seq: this.sequence, at: this.now() } satisfies LedgerMark & { v: 1 }), { mode: 0o600, durable: false }); }+ catch (error) { console.error("routines: could not write the run ledger's mark", error); }+ }+}diff --git a/server/routine-lines.ts b/server/routine-lines.tsindex 2e6ae5b589..062a1fac8d 100644--- a/server/routine-lines.ts+++ b/server/routine-lines.ts@@ -30,6 +30,15 @@ export const ROUTINE_LINE = {"routines.server.part.stillRunning": "the previous run of this routine is still running","routines.server.part.notStarted": "the previous run of this routine has not started yet","routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out",+ "routines.server.missedOne": "Missed because {why}",+ "routines.server.missedMany": "Missed {count} scheduled runs because {why}",+ "routines.server.missedTooLate": "Missed because {why} until more than {hours} hours after its time",+ "routines.server.part.computerOff": "this computer was asleep or OpenMausBot was not running",+ "routines.server.part.cloudDown": "this Cloud was asleep or restarting",+ "routines.server.part.heldUp": "the scheduler was held up starting another run",+ "routines.server.restored": "Not run again: this schedule was restored from a backup made before this run had its turn",+ "routines.server.restoredMany": "Not run again: {count} scheduled runs from before this schedule was restored from a backup",+ "routines.server.duplicate": "Not started: this scheduled run had already started once",} as const;export type RoutineLineKey = keyof typeof ROUTINE_LINE;diff --git a/server/routine-occurrences.ts b/server/routine-occurrences.tsnew file mode 100644index 0000000000..6037e92c63--- /dev/null+++ b/server/routine-occurrences.ts@@ -0,0 +1,318 @@+// Keeps the occurrence ledger (routine-ledger.ts) in step with the run rows. Every save of routines.json hands its rows+// here, and each scheduled row's record is made again from the row and the record before it: the row says what+// happened, the record remembers how often the occurrence started and when it first did. An occurrence's key is what+// makes its start happen once: the scheduler asks `decided` before it makes a row for an occurrence and+// `startedElsewhere` before it starts one, and a start is written and flushed here before its turn begins.+import { randomUUID } from "node:crypto";+import { hostname } from "node:os";++import { ROUTINE_SUPERSEDED } from "./routine-execution.ts";+import { occurrenceEnded, occurrenceLastAt, RoutineLedger, type Occurrence, type OccurrenceLease, type OccurrenceReason, type OccurrenceState } from "./routine-ledger.ts";+import type { Routine, RoutineRun } from "./routines.ts";++/** How long a started occurrence's lease lasts without being renewed, and how often it is renewed while its run lives. */+export const LEASE_MS = 3 * 60_000;+export const LEASE_BEAT_MS = 60_000;+/** A first start later than this after the scheduled time counts as late. */+export const LATE_START_MS = 5 * 60_000;+export const ROUTINE_TURN_GONE = "its turn ended without reporting back";+/** How many scheduler passes a start is held back for a ledger that cannot be written, before it starts unrecorded. */+export const UNRECORDED_START_PASSES = 3;++export interface OccurrenceCounts { ran: number; failed: number; missed: number; late: number; retried: number }++type Row = Pick<RoutineRun, "id" | "routineId" | "scheduledFor" | "status" | "manual" | "triggerSource" | "checkKey" | "webhookId" | "startedAt" | "finishedAt" | "createdAt" |+ "retried" | "skipped" | "error" | "errorCode" | "errorParams" | "attentionCode">;+type Scheduled = Pick<Routine, "id" | "enabled" | "nextRunAt" | "updatedAt">;++/** A run row made for a scheduled occurrence: not one a person, a start-up, an event or a routine's checks made. */+export const isOccurrenceRun = (run: Pick<RoutineRun, "manual" | "triggerSource" | "checkKey" | "webhookId">): boolean =>+ (run.triggerSource ?? (run.manual ? "manual" : "schedule")) === "schedule" && run.checkKey === undefined && run.webhookId === undefined;++const ACTIVE = new Set<RoutineRun["status"]>(["queued", "running", "waiting"]);+const signature = (run: Row) => [run.status, run.startedAt, run.finishedAt, run.attentionCode, run.errorCode, run.error === undefined ? "" : run.error.length, run.skipped?.count, run.skipped?.lastAt].join("|");++/** How often the occurrence has started, from its record and what its row says now. A start the server took back, or+ * its bot refused as busy, was no attempt. */+function starts(run: Row, before: Occurrence | undefined): Pick<Occurrence, "attempts" | "startedAt" | "lastStartAt"> {+ const busyOnly = run.errorCode === "routines.server.stillBusy" || run.errorCode === "routines.server.busyTooLong";+ if (!before) {+ if (run.startedAt == null || busyOnly) return { attempts: 0 };+ return { attempts: run.retried !== undefined && run.status !== "queued" ? 2 : 1, startedAt: run.startedAt, ...(run.status === "queued" ? {} : { lastStartAt: run.startedAt }) };+ }+ const { startedAt, lastStartAt } = before;+ const refused = run.status === "queued" ? run.startedAt == null || run.attentionCode === "routines.server.waitingToStart" : busyOnly;+ if (run.status === "queued" || (refused && lastStartAt !== undefined)) {+ const attempts = refused && lastStartAt !== undefined ? Math.max(0, before.attempts - 1) : before.attempts;+ return { attempts, ...(attempts > 0 && startedAt !== undefined ? { startedAt } : {}) };+ }+ const startedNow = run.status === "running" ? run.startedAt !== lastStartAt : before.attempts === 0 && (run.status === "waiting" || run.status === "completed");+ if (run.startedAt != null && startedNow) return { attempts: before.attempts + 1, startedAt: startedAt ?? run.startedAt, lastStartAt: run.startedAt };+ return { attempts: before.attempts, ...(startedAt === undefined ? {} : { startedAt }), ...(lastStartAt === undefined ? {} : { lastStartAt }) };+}++function stateOf(run: Row, attempts: number): OccurrenceState {+ if (run.status === "queued") return attempts > 0 ? "running" : "queued";+ if (run.status === "running" || run.status === "waiting") return "running";+ if (run.status === "completed") return "ran";+ if (run.skipped) return run.skipped.behind.startsWith("down:") ? "missed" : "skipped";+ if (String(run.errorParams?.why ?? "").endsWith("heldUp")) return "skipped";+ return attempts > 0 ? "failed" : run.status === "cancelled" ? "skipped" : "missed";+}++function reasonOf(run: Row, state: OccurrenceState): OccurrenceReason | undefined {+ if (state === "queued" || state === "running" || state === "ran") return undefined;+ const behind = run.skipped?.behind, code = run.errorCode, why = String(run.errorParams?.why ?? "");+ if (behind?.startsWith("late:") || why.endsWith("heldUp")) return "scheduler-late";+ if (behind) return behind.startsWith("no-start:") ? "computer-no-start" : behind.startsWith("down:cloud") ? "cloud-down" : behind.startsWith("down:") ? "computer-off" : behind.startsWith("restored:") ? "restored" : "previous-run-active";+ if (code === "routines.server.missedTooLate" || code === "routines.server.missedOne" || code === "routines.server.missedMany") return why.endsWith("cloudDown") ? "cloud-down" : "computer-off";+ if (code === "routines.server.busyTooLong" || code === "routines.server.stillBusy") return "bot-busy";+ if (code === "routines.server.overLimit") return "run-limit";+ if (code === "routines.server.restored") return "restored";+ if (run.error === ROUTINE_SUPERSEDED) return "superseded";+ if (String(run.errorParams?.failure ?? run.error ?? "").includes(ROUTINE_TURN_GONE)) return "turn-gone";+ if (run.status === "cancelled") return "cancelled";+ return state === "failed" ? "failed" : "not-started";+}++/** The record with nothing in it after `end`: a span is shortened to there, and one that begins later is void. */+function cutAt(record: Occurrence, end: number): Occurrence {+ const { count, lastAt, ...rest } = record, last = Math.min(lastAt ?? record.dueAt, end);+ const ended = { ...rest, cut: end, ...(record.endedAt === undefined ? {} : { endedAt: Math.min(record.endedAt, Math.max(0, end)) }) };+ if (record.dueAt > end) return { ...ended, void: true };+ const kept = count === undefined || lastAt === undefined || lastAt <= record.dueAt ? 1 : Math.max(1, Math.round(count * (last - record.dueAt) / (lastAt - record.dueAt)));+ return kept > 1 && last > record.dueAt ? { ...ended, count: kept, lastAt: last } : ended;+}++function recordOf(run: Row, before: Occurrence | undefined, now: number, holder: Omit<OccurrenceLease, "until">): Occurrence {+ const started = starts(run, before), state = stateOf(run, started.attempts), reason = reasonOf(run, state);+ const held = run.status === "running" || run.status === "waiting";+ const lease = !held ? undefined : before?.lease?.boot === holder.boot ? before.lease : { ...holder, until: now + LEASE_MS };+ const record: Occurrence = {+ routineId: run.routineId, dueAt: before?.dueAt ?? run.skipped?.firstAt ?? run.scheduledFor, state, ...(reason ? { reason } : {}), ...started,+ madeAt: before?.madeAt ?? run.createdAt, ...(ACTIVE.has(run.status) ? {} : { endedAt: run.finishedAt ?? now }),+ ...(run.skipped && run.skipped.count > 1 ? { count: run.skipped.count, lastAt: run.skipped.lastAt } : {}),+ runIds: before?.runIds.includes(run.id) ? before.runIds : [run.id], ...(lease ? { lease } : {}),+ };+ if (ACTIVE.has(run.status) || started.attempts > 0) return record;+ // A row closed without starting says nothing about a time after the one it was cut at, or, read with no record, after now.+ const cut = before ? before.cut : now;+ return cut !== undefined && (before?.cut !== undefined || occurrenceLastAt(record) > cut) ? cutAt(record, cut) : record;+}++/** Field by field, whatever order they are in: a record read back from the file lists them in its own. */+const ordered = (record: Occurrence) => JSON.stringify(Object.entries(record).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : 1));+const same = (a: Occurrence, b: Occurrence) => ordered(a) === ordered(b);+const machineName = (value: string | undefined) => (value ?? hostname()).replace(/[^\w:-]/g, "-").slice(0, 64) || "local";++export class Occurrences {+ readonly ledger: RoutineLedger;+ /** Since this process started. */+ readonly counts: OccurrenceCounts = { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 };+ /** Occurrences that already had a record and were not made or started a second time, since this process started. */+ duplicates = 0;+ /** After a restore from a backup: until when the schedule it replaced had been alive. Null otherwise. */+ restoredThrough: number | null;+ private readonly holder: Omit<OccurrenceLease, "until">;+ private readonly now: () => number;+ private readonly signatures = new Map<string, string>();+ private rowIds = new Set<string>();+ private fingerprint: string | undefined;+ private unreadable = false;+ /** The ledger cannot be written, and runs start without it: routines.json alone keeps a run from starting twice. */+ degraded = false;+ private failing = false;+ private refused = 0;+ private held: { version: number; records: Occurrence[] } = { version: -1, records: [] };++ constructor(routinesFile: string, now: () => number, machine?: string) {+ this.now = now;+ this.holder = { machine: machineName(machine), boot: randomUUID() };+ this.ledger = new RoutineLedger(routinesFile, now);+ this.restoredThrough = this.ledger.open().restoredThrough;+ }++ /** Works out every scheduled row's record from the rows about to be saved. A change that holds a start is written at+ * once, before the turn begins; any other by the function returned, which the caller runs once routines.json itself+ * is saved, so the ledger never says more than the rows do. A write that fails is logged once and made again with+ * the next save: it never fails the save, or the start. `counting` false at start, when the rows are older than this+ * process and nothing they say happened in it. */+ observe(routines: readonly Scheduled[], runs: readonly Row[], counting = true): () => void {+ this.trim();+ const now = this.now(), rows = runs.filter(isOccurrenceRun), ids = new Set(rows.map((run) => run.id));+ const put = new Map<string, { before: Occurrence | undefined; after: Occurrence }>(), seen = new Map<string, string>();+ let starting = false;+ // Rows that count skipped occurrences come last: a row that ran keeps the record of its own time.+ for (const run of [...rows.filter((row) => !row.skipped), ...rows.filter((row) => row.skipped)]) {+ const mark = signature(run);+ if (this.signatures.get(run.id) === mark) continue;+ seen.set(run.id, mark);+ const before = this.ledger.ofRun(run.id);+ if (!before) {+ const dueAt = run.skipped?.firstAt ?? run.scheduledFor, key = `${run.routineId}\n${dueAt}`;+ const taken = put.get(key)?.after ?? this.standing(run.routineId, dueAt);+ // A second row for an occurrence that has its record gets none of its own, and is never started.+ if (taken && (put.has(key) || !this.unclaimed(taken, ids))) continue;+ }+ const after = recordOf(run, before, now, this.holder);+ if (before && same(before, after)) continue;+ if (counting && run.status === "running" && after.attempts > (before?.attempts ?? 0)) starting = true;+ put.set(`${after.routineId}\n${after.dueAt}`, { before, after });+ }+ const remove: Occurrence[] = [];+ for (const record of this.ledger.all()) {+ if (occurrenceEnded(record) || record.runIds.some((id) => ids.has(id)) || put.has(`${record.routineId}\n${record.dueAt}`)) continue;+ // Its row is gone. One that never started was never saved and is dropped; one that started stays decided.+ if (record.attempts === 0) remove.push(record);+ else put.set(`${record.routineId}\n${record.dueAt}`, { before: record, after: { ...record, state: "failed", reason: "cancelled", endedAt: now, lease: undefined } });+ }+ const fingerprint = routines.map((routine) => `${routine.id}:${routine.enabled ? 1 : 0}:${routine.nextRunAt}:${routine.updatedAt}`).join(",");+ // At start the routines are as the last process left them: with no record to change, nothing is written.+ if (put.size === 0 && remove.length === 0 && (fingerprint === this.fingerprint || !counting)) { this.rowIds = ids; this.fingerprint = fingerprint; return () => {}; }+ const write = () => {+ try { this.ledger.write([...put.values()].map(({ after }) => JSON.parse(JSON.stringify(after)) as Occurrence), remove); }+ catch (error) { return this.failed(error); }+ this.written();+ this.rowIds = ids;+ this.fingerprint = fingerprint;+ for (const [id, mark] of seen) this.signatures.set(id, mark);+ for (const id of this.signatures.keys()) if (!ids.has(id)) this.signatures.delete(id);+ if (counting) for (const { before, after } of put.values()) this.count(before, after);+ };+ if (!starting) return write;+ write();+ // The start goes ahead whether or not it was recorded; unrecorded, the report says so until the ledger takes a write.+ if (this.failing && !this.degraded) { this.degraded = true; console.error(`routines: the run ledger ${this.ledger.file} cannot be written; scheduled runs start without it until it can`); }+ return () => {};+ }++ /** Whether a queued run may start now. A scheduled occurrence waits while the ledger cannot take its start, for+ * UNRECORDED_START_PASSES passes; after that it starts unrecorded, and so does every other until the ledger can be+ * written again: a run that starts matters more than its record. Any other run never waits. */+ ready(run: Row): boolean {+ if (!isOccurrenceRun(run) || this.degraded) return true;+ if (this.ledger.writable()) { this.refused = 0; return true; }+ this.refused += 1;+ if (this.refused <= UNRECORDED_START_PASSES) return false;+ this.degraded = true;+ console.error(`routines: the run ledger ${this.ledger.file} cannot be written; scheduled runs start without it until it can`);+ return true;+ }++ private failed(error: unknown): void {+ if (!this.failing) console.error("routines: could not write the run ledger; each save tries again", error);+ this.failing = true;+ }++ private written(): void {+ if (this.degraded) console.error("routines: the run ledger can be written again");+ this.failing = false; this.degraded = false; this.refused = 0;+ }++ /** The occurrence already has a record that stands, so no row is made for it again: it ran, was closed, or is another+ * row's. The file is read again first when another process has written to it. */+ decided(routineId: string, dueAt: number): boolean {+ this.refresh();+ this.trim(routineId, dueAt);+ const record = this.standing(routineId, dueAt);+ if (!record || this.unclaimed(record, this.rowIds)) return false;+ this.duplicates += 1;+ console.warn("routines: a scheduled occurrence that already has its record was not made again");+ return true;+ }++ /** A queued row whose occurrence belongs to another row's record: starting it would start the occurrence twice. */+ startedElsewhere(run: Row): boolean {+ if (!isOccurrenceRun(run)) return false;+ this.refresh();+ if (this.ledger.ofRun(run.id)) return false;+ const record = this.standing(run.routineId, run.skipped?.firstAt ?? run.scheduledFor);+ if (!record || this.unclaimed(record, new Set([...this.rowIds].filter((id) => id !== run.id)))) return false;+ this.duplicates += 1;+ return true;+ }++ /** When a run cut by a restart may start again: not before the lease another machine holds on it has lapsed. Undefined when nothing holds it back. */+ retryAfterBoot(run: Pick<RoutineRun, "id">): number | undefined {+ const lease = this.ledger.ofRun(run.id)?.lease;+ return lease && lease.machine !== this.holder.machine && lease.until > this.now() ? lease.until + 1_000 : undefined;+ }++ private mine(): Occurrence[] {+ if (this.held.version !== this.ledger.version) this.held = { version: this.ledger.version, records: [...this.ledger.all()].filter((record) => record.lease?.boot === this.holder.boot && !occurrenceEnded(record)) };+ return this.held.records;+ }++ /** When the leases this process holds are next renewed; null while it holds none. */+ beatDueAt(): number | null {+ const due = this.mine().map((record) => record.lease!.until - (LEASE_MS - LEASE_BEAT_MS));+ return due.length ? Math.min(...due) : null;+ }++ /** Renews this process's leases that are due. */+ beat(): void {+ const now = this.now(), due = this.mine().filter((record) => record.lease!.until - now <= LEASE_MS - LEASE_BEAT_MS);+ if (due.length === 0) return;+ try { this.ledger.write(due.map((record) => ({ ...record, lease: { ...this.holder, until: now + LEASE_MS } })), [], false); }+ catch (error) { this.failed(error); }+ }++ /** At shutdown: the leases are given up, so whichever process starts next on this data need not wait for them. */+ close(): void {+ const leased = this.mine();+ if (leased.length === 0) return;+ try { this.ledger.write(leased.map(({ lease: _lease, ...record }) => record), [], false); }+ catch (error) { console.error("routines: could not give up a run's lease", error); }+ }++ /** The ledger's sequence number, raised first when whether routines.json can be read has changed since it was last asked. */+ sequence(unreadable: boolean): number {+ if (unreadable !== this.unreadable) {+ try { this.ledger.write([]); this.unreadable = unreadable; }+ catch (error) { this.failed(error); }+ }+ return this.ledger.seq;+ }++ /** The record that stands for the occurrence, leaving out one closed for a time that had not come. */+ private standing(routineId: string, dueAt: number): Occurrence | undefined {+ const record = this.ledger.covering(routineId, dueAt);+ return record?.void ? undefined : record;+ }++ /** A record that reaches past now was written while the clock was ahead. One closed without starting is cut back to+ * now; and since nothing says when the clock was put right, one already cut is cut again to just before `due` when+ * that occurrence of its routine is asked about, so an occurrence that has not had its time is still made. One that+ * ran keeps its key, and only its end time is brought back. */+ private trim(routineId?: string, due?: number): void {+ const now = this.now(), end = Math.min(now, (due ?? Infinity) - 1), put: Occurrence[] = [];+ for (const record of routineId === undefined ? this.ledger.all() : this.ledger.ofRoutine(routineId)) {+ if (!occurrenceEnded(record) || record.void) continue;+ const last = occurrenceLastAt(record), ahead = last > now || (record.cut !== undefined && last > end);+ if (record.attempts === 0 && ahead) put.push(cutAt(record, end));+ else if (record.attempts > 0 && (record.endedAt ?? 0) > now) put.push({ ...record, endedAt: now });+ }+ if (put.length === 0) return;+ try { this.ledger.write(put.map((record) => JSON.parse(JSON.stringify(record)) as Occurrence)); this.signatures.clear(); }+ catch (error) { this.failed(error); }+ }++ private refresh(): void {+ if (this.ledger.sync()) this.signatures.clear();+ }++ /** A record no row stands behind and that never started: its row was never saved, so the occurrence is still to be made. */+ private unclaimed(record: Occurrence, rows: ReadonlySet<string>): boolean {+ return record.attempts === 0 && !occurrenceEnded(record) && !record.runIds.some((id) => rows.has(id));+ }++ private count(before: Occurrence | undefined, after: Occurrence): void {+ const was = before?.attempts ?? 0, closed = (record: Occurrence | undefined) => record && !record.void && record.reason !== "scheduler-late" && (record.state === "missed" || record.state === "skipped") ? record.count ?? 1 : 0;+ if (after.state === "ran" && before?.state !== "ran") this.counts.ran += 1;+ if (after.state === "failed" && before?.state !== "failed") this.counts.failed += 1;+ this.counts.missed += Math.max(0, closed(after) - closed(before));+ const late = (record: Occurrence | undefined) => record !== undefined && record.attempts > 0 && record.startedAt !== undefined && record.startedAt - record.dueAt > LATE_START_MS ? 1 : 0;+ this.counts.late = Math.max(0, this.counts.late + late(after) - late(before));+ this.counts.retried = Math.max(0, this.counts.retried + Math.max(1, after.attempts) - Math.max(1, was));+ }+}diff --git a/server/routine-reliability.test.ts b/server/routine-reliability.test.tsindex a9b59fcbae..537ab879b8 100644--- a/server/routine-reliability.test.ts+++ b/server/routine-reliability.test.ts@@ -841,7 +841,7 @@ describe("a routines.json that cannot be read", () => {it("saves through a temporary file and a rename, so a reader never sees half a file", () => {const h = harness();h.manager.create(every(60));- expect(readdirSync(dirname(h.file))).toEqual(["routines.json"]);+ expect(readdirSync(dirname(h.file)).sort()).toEqual(["routines.json", "routines.ledger.jsonl", "routines.ledger.mark"]);expect(() => JSON.parse(readFileSync(h.file, "utf8"))).not.toThrow();});});diff --git a/server/routine-run-history.test.ts b/server/routine-run-history.test.tsnew file mode 100644index 0000000000..2cd3ab6cc5--- /dev/null+++ b/server/routine-run-history.test.ts@@ -0,0 +1,20 @@+import { expect, it } from "vitest";++import { evictRuns } from "./routine-run-history.ts";+import type { RoutineRun } from "./routines.ts";++const run = (id: string, routineId: string, status: RoutineRun["status"] = "completed") => ({ id, routineId, status }) as RoutineRun;++it("drops the oldest ended rows of the routine that holds the most, never one that has not ended", () => {+ const runs = [run("daily-1", "daily"), run("busy-1", "busy", "running"), ...Array.from({ length: 6 }, (_, index) => run(`busy-${index + 2}`, "busy")), run("daily-2", "daily"), run("weekly-1", "weekly", "waiting")];+ evictRuns(runs, 7);+ expect(runs.map((row) => row.id)).toEqual(["daily-1", "busy-1", "busy-5", "busy-6", "busy-7", "daily-2", "weekly-1"]);+ evictRuns(runs, 7);+ expect(runs).toHaveLength(7);+});++it("stops when only rows that have not ended are left", () => {+ const runs = [run("a", "one", "queued"), run("b", "one", "running"), run("c", "two")];+ evictRuns(runs, 1);+ expect(runs.map((row) => row.id)).toEqual(["a", "b"]);+});diff --git a/server/routine-run-history.ts b/server/routine-run-history.tsnew file mode 100644index 0000000000..daad487ec0--- /dev/null+++ b/server/routine-run-history.ts@@ -0,0 +1,19 @@+import type { RoutineRun } from "./routines.ts";++const ACTIVE = new Set<RoutineRun["status"]>(["queued", "running", "waiting"]);++/** Keeps at most `max` run rows. A row that has not ended is never dropped: it owns its run's stop, limit and events.+ * Each row dropped is the oldest ended one of the routine holding the most of them, so a routine that runs every few+ * minutes uses up its own history and not the others'. */+export function evictRuns(runs: RoutineRun[], max: number): void {+ let excess = runs.length - max;+ if (excess <= 0) return;+ const ended = new Map<string, number>();+ for (const run of runs) if (!ACTIVE.has(run.status)) ended.set(run.routineId, (ended.get(run.routineId) ?? 0) + 1);+ for (; excess > 0 && ended.size > 0; excess -= 1) {+ let most = "", held = 0;+ for (const [routineId, count] of ended) if (count > held) [most, held] = [routineId, count];+ runs.splice(runs.findIndex((run) => run.routineId === most && !ACTIVE.has(run.status)), 1);+ if (held === 1) ended.delete(most); else ended.set(most, held - 1);+ }+}diff --git a/server/routine-run-watch.ts b/server/routine-run-watch.tsnew file mode 100644index 0000000000..2cb2799a9e--- /dev/null+++ b/server/routine-run-watch.ts@@ -0,0 +1,51 @@+// A started run whose turn is gone is not left `running` for ever. The host says whether a run's conversation still has+// a turn of its own; once it has said no for TURN_GONE_MS of scheduler passes in a row, with no event from that+// conversation in between, the run is handed back to be started again or failed. The passes are added up one at a+// time, each step capped, so the hours a computer slept count for nothing.+import { COUNT_STEP_CAP_MS, COUNT_STEP_MS } from "./routine-bounds.ts";+import type { RoutineRun } from "./routines.ts";++export const TURN_GONE_MS = 5 * 60_000;++type Watched = Pick<RoutineRun, "id" | "status" | "startedAt" | "threadId" | "target" | "botId" | "groupId">;++export class RunWatch {+ private readonly live: ((run: RoutineRun) => boolean | null) | undefined;+ private readonly events = new Map<string, number>();+ private readonly gone = new Map<string, { ms: number; lookedAt: number; events: number }>();++ /** `live`: whether the run's conversation has a turn working or about to; null when the host cannot tell. */+ constructor(live: ((run: RoutineRun) => boolean | null) | undefined) {+ this.live = live;+ }++ /** An event arrived from this conversation. */+ seen(threadId: string): void {+ if (this.live) this.events.set(threadId, (this.events.get(threadId) ?? 0) + 1);+ }++ /** The runs whose turn has now been gone for TURN_GONE_MS. */+ lost<R extends RoutineRun>(runs: readonly R[], now: number): R[] {+ const lost: R[] = [], watched = new Set<string>();+ if (!this.live) return lost;+ for (const run of runs) {+ if (!started(run)) continue;+ const events = this.events.get(run.threadId!) ?? 0, before = this.gone.get(run.id);+ if (this.live(run) !== false) continue;+ watched.add(run.id);+ const ms = before && before.events === events ? before.ms + Math.min(COUNT_STEP_CAP_MS, Math.max(0, now - before.lookedAt)) : 0;+ this.gone.set(run.id, { ms, lookedAt: now, events });+ if (ms >= TURN_GONE_MS) lost.push(run);+ }+ for (const id of this.gone.keys()) if (!watched.has(id)) this.gone.delete(id);+ for (const threadId of this.events.keys()) if (!runs.some((run) => run.threadId === threadId && started(run))) this.events.delete(threadId);+ return lost;+ }++ /** When the scheduler must next look: a step on while a run is at work, so a turn that goes is noticed. */+ dueAt(runs: readonly Watched[], now: number): number | null {+ return this.live && runs.some(started) ? now + COUNT_STEP_MS : null;+ }+}++const started = (run: Watched) => run.status === "running" && run.startedAt != null && run.threadId !== undefined;diff --git a/server/routine-run-window.test.ts b/server/routine-run-window.test.tsindex 8947a8cd0f..7b0f7e4f77 100644--- a/server/routine-run-window.test.ts+++ b/server/routine-run-window.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from "vitest";-import { appRunWindow, NEWEST_RUNS_PER_AUTOMATION, routineRunsFor } from "./routine-run-window.ts";-import type { RoutineRun } from "./routines.ts";+import type { Occurrence } from "./routine-ledger.ts";+import { appRunWindow, NEWEST_RUNS_PER_AUTOMATION, routineHistoryFor, routineRunsFor } from "./routine-run-window.ts";+import type { Routine, RoutineRun } from "./routines.ts";const DAY = 86_400_000;const NOW = Date.UTC(2026, 10, 1);@@ -57,4 +58,14 @@ describe("the app's run window", () => {expect(ids(routineRunsFor(listRuns, new URLSearchParams({ thread: "t1" })))).toEqual(["a"]);expect(ids(routineRunsFor(listRuns, new URLSearchParams({ since: String(NOW - 7 * DAY) })))).toEqual(["a", "b"]);});++ it("adds one routine's occurrences when asked for its history, without the lease or what the asker may not see", () => {+ const record: Occurrence = { routineId: "r", dueAt: NOW, state: "running", attempts: 1, startedAt: NOW, lastStartAt: NOW, madeAt: NOW, runIds: ["a"], lease: { machine: "host", boot: "boot", until: NOW + 1 } };+ const manager = { listRoutines: () => [{ id: "r" }, { id: "hidden" }] as Routine[], occurrences: (id: string) => id === "r" ? [record] : [{ ...record, routineId: id }] };+ const visible = (routine: Routine) => routine.id !== "hidden";+ expect(routineHistoryFor(manager, new URLSearchParams({ history: "r" }), visible)).toEqual({ occurrences: [{ dueAt: NOW, state: "running", attempts: 1, startedAt: NOW, madeAt: NOW, runIds: ["a"] }] });+ expect(routineHistoryFor(manager, new URLSearchParams({ history: "hidden" }), visible)).toEqual({});+ expect(routineHistoryFor(manager, new URLSearchParams({ history: "gone" }), visible)).toEqual({});+ expect(routineHistoryFor(manager, new URLSearchParams(), visible)).toEqual({});+ });});diff --git a/server/routine-run-window.ts b/server/routine-run-window.tsindex 2dcffa5934..15fc9fefc7 100644--- a/server/routine-run-window.ts+++ b/server/routine-run-window.ts@@ -1,5 +1,6 @@import { isRoutineProblemRun } from "../shared/routines.ts";-import type { RoutineRun } from "./routines.ts";+import type { Occurrence } from "./routine-ledger.ts";+import type { Routine, RoutineRun } from "./routines.ts";/** However old they are, each automation keeps at least this many of its newest runs in the app's window. */export const NEWEST_RUNS_PER_AUTOMATION = 5;@@ -34,3 +35,15 @@ export function routineRunsFor(listRuns: (from?: number, to?: number) => Routineif (thread) return listRuns().filter((run) => run.threadId === thread);return since === undefined ? listRuns(time("from"), time("to")) : appRunWindow(listRuns(), since);}++/** A scheduled occurrence as the app reads it: when it was due, how it ended and why, how often it started, and its run rows. */+export type RoutineOccurrence = Omit<Occurrence, "routineId" | "lastStartAt" | "lease">;++/** `history` names one routine: its scheduled occurrences from the ledger, newest first, beside the runs. Nothing for a+ * routine the asker may not see, or when no routine is named. */+export function routineHistoryFor(manager: { listRoutines(): Routine[]; occurrences(routineId: string): Occurrence[] }, query: URLSearchParams,+ visible: (routine: Routine) => boolean): { occurrences?: RoutineOccurrence[] } {+ const routine = manager.listRoutines().find((candidate) => candidate.id === query.get("history"));+ if (!routine || !visible(routine)) return {};+ return { occurrences: manager.occurrences(routine.id).map(({ routineId: _routineId, lastStartAt: _lastStartAt, lease: _lease, ...occurrence }) => occurrence) };+}diff --git a/server/routine-schedule-report.test.ts b/server/routine-schedule-report.test.tsnew file mode 100644index 0000000000..e34191f108--- /dev/null+++ b/server/routine-schedule-report.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vitest";++import type { Occurrence } from "./routine-ledger.ts";+import { dayCounts, scheduleSection } from "./routine-schedule-report.ts";++const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR;+const NOW = Date.parse("2026-11-16T08:00:00Z");+const NONE = { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 };+const record = (dueAt: number, state: Occurrence["state"], more: Partial<Occurrence> = {}): Occurrence => ({+ routineId: "routine-1", dueAt, state, attempts: state === "ran" || state === "failed" || state === "running" ? 1 : 0, madeAt: dueAt, runIds: ["run"],+ ...(state === "ran" || state === "failed" || state === "running" ? { startedAt: dueAt + 1_000 } : {}), ...(state === "queued" || state === "running" ? {} : { endedAt: dueAt + MINUTE }), ...more,+});+const section = (records: Occurrence[], next: Array<{ at: number; paused: boolean }> = [], more: Record<string, unknown> = {}) =>+ scheduleSection({ seq: 41, unreadable: false, slowStops: 0, next, records, boot: NONE, now: NOW, ...more });++describe("the schedule section", () => {+ it("is exactly the contract's fields", () => {+ expect(section([record(NOW - HOUR, "ran")], [{ at: NOW + HOUR, paused: false }])).toEqual({+ v: 1, seq: 41, unreadable: false, nextDueAt: NOW + HOUR, oldestUnconfirmed: null,+ lastConfirmed: { dueAt: NOW - HOUR, startedAt: NOW - HOUR + 1_000, state: "ran" },+ due: { boot: NONE, day: { ...NONE, ran: 1 } }, slowStops: 0,+ });+ expect(section([])).toMatchObject({ nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null });+ });++ it("names the earliest occurrence that has not started, whether or not it has a row, and never hides it behind a run", () => {+ const records = [record(NOW - 3 * HOUR, "running"), record(NOW - 2 * HOUR, "queued", { madeAt: NOW - 2 * HOUR + 300 }), record(NOW - HOUR, "queued")];+ expect(section(records)).toMatchObject({ oldestUnconfirmed: { dueAt: NOW - 2 * HOUR, state: "queued", since: NOW - 2 * HOUR + 300 }, lastConfirmed: { dueAt: NOW - 3 * HOUR, state: "running" } });+ expect(section(records, [{ at: NOW - 4 * HOUR, paused: false }, { at: NOW + HOUR, paused: false }]))+ .toMatchObject({ nextDueAt: NOW - 4 * HOUR, oldestUnconfirmed: { dueAt: NOW - 4 * HOUR, state: "due", since: NOW - 4 * HOUR } });+ expect(section([], [{ at: NOW, paused: false }])).toMatchObject({ nextDueAt: NOW, oldestUnconfirmed: { dueAt: NOW, state: "due" } });+ });++ it("leaves a paused bot's routine out of the next due time, but not out of what has not started", () => {+ expect(section([], [{ at: NOW - HOUR, paused: true }, { at: NOW + HOUR, paused: false }])).toMatchObject({ nextDueAt: NOW + HOUR, oldestUnconfirmed: { dueAt: NOW - HOUR, state: "due" } });+ expect(section([], [{ at: NOW + HOUR, paused: true }]).nextDueAt).toBeNull();+ });++ it("takes the newest decided occurrence by the last time its record stands for, with no start time for one closed unstarted", () => {+ const counted = record(NOW - 5 * HOUR, "skipped", { count: 4, lastAt: NOW - 2 * HOUR });+ expect(section([record(NOW - 3 * HOUR, "ran"), counted]).lastConfirmed).toEqual({ dueAt: NOW - 2 * HOUR, startedAt: null, state: "skipped" });+ expect(section([record(NOW - 3 * HOUR, "missed"), record(NOW - 4 * HOUR, "failed")]).lastConfirmed).toEqual({ dueAt: NOW - 3 * HOUR, startedAt: null, state: "missed" });+ expect(section([record(NOW - HOUR, "failed", { startedAt: undefined })]).lastConfirmed).toEqual({ dueAt: NOW - HOUR, startedAt: NOW - HOUR + MINUTE, state: "failed" });+ });++ it("says nothing is known while the saved routines cannot be read", () => {+ expect(section([record(NOW - HOUR, "ran")], [{ at: NOW - HOUR, paused: false }], { unreadable: true, slowStops: 3, boot: { ...NONE, ran: 2 } })).toEqual({+ v: 1, seq: 41, unreadable: true, nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null, due: { boot: { ...NONE, ran: 2 }, day: NONE }, slowStops: 3,+ });+ });++ it("keeps every number whole and within the contract's range", () => {+ const wild = section([], [], { seq: 2e15, slowStops: -4, boot: { ran: 5e9, failed: 1.6, missed: Number.NaN, late: -1, retried: Infinity } });+ expect(wild).toMatchObject({ seq: 1e15, slowStops: 0, due: { boot: { ran: 1e9, failed: 2, missed: 0, late: 0, retried: 0 } } });+ });+});++describe("the last day's counts", () => {+ it("come from the records: what ended in the day, what started late in it, and the starts after the first", () => {+ const records = [+ record(NOW - 2 * HOUR, "ran"), record(NOW - 3 * HOUR, "ran", { startedAt: NOW - 3 * HOUR + 6 * MINUTE }), record(NOW - 4 * HOUR, "failed", { attempts: 2 }),+ record(NOW - 5 * HOUR, "missed"), record(NOW - 6 * HOUR, "skipped"), record(NOW - 7 * HOUR, "running", { attempts: 3, startedAt: NOW - 7 * HOUR + 5 * MINUTE }),+ record(NOW - 8 * HOUR, "queued"), record(NOW - 30 * HOUR, "ran"), record(NOW - 30 * HOUR, "failed", { attempts: 2 }), record(NOW - 30 * HOUR, "missed"),+ ];+ expect(dayCounts(records, NOW)).toEqual({ ran: 2, failed: 1, missed: 2, late: 1, retried: 3 });+ });++ it("take from a record that counts a span of occurrences the share that fell in the day", () => {+ expect(dayCounts([record(NOW - 2 * DAY, "skipped", { count: 48, lastAt: NOW, endedAt: NOW })], NOW).missed).toBe(24);+ expect(dayCounts([record(NOW - 3 * HOUR, "missed", { count: 3, lastAt: NOW - HOUR, endedAt: NOW })], NOW).missed).toBe(3);+ expect(dayCounts([record(NOW - 3 * DAY, "missed", { count: 3, lastAt: NOW - 2 * DAY, endedAt: NOW - 2 * DAY })], NOW).missed).toBe(0);+ });+});diff --git a/server/routine-schedule-report.ts b/server/routine-schedule-report.tsnew file mode 100644index 0000000000..d468dea1b2--- /dev/null+++ b/server/routine-schedule-report.ts@@ -0,0 +1,84 @@+// The `schedule` section of a Cloud home's health report, made from the occurrence ledger each time the report is read.+// Times, counts, booleans and fixed state words only: no routine's id, name, prompt, output, schedule rule or bot.+import { occurrenceEnded, occurrenceLastAt, type Occurrence, type OccurrenceState } from "./routine-ledger.ts";+import { LATE_START_MS, type OccurrenceCounts } from "./routine-occurrences.ts";++export interface ScheduleSection {+ v: 1;+ /** Goes up with every change to what this section says; saved with the ledger, so a restart never lowers it. */+ seq: number;+ /** The saved routines could not be read, so nothing runs; the three fields below are then null. */+ unreadable: boolean;+ /** The earliest scheduled-for time among occurrences that have no run row yet; it may be past. */+ nextDueAt: number | null;+ /** The due occurrence with the earliest scheduled-for time of which no attempt has started. */+ oldestUnconfirmed: { dueAt: number; state: "due" | "queued"; since: number } | null;+ /** The occurrence with the latest scheduled-for time that started or was closed without starting. */+ lastConfirmed: { dueAt: number; startedAt: number | null; state: Exclude<OccurrenceState, "queued"> } | null;+ due: { boot: OccurrenceCounts; day: OccurrenceCounts };+ /** How often stopping a turn outlasted the scheduler's wait, since this process started. */+ slowStops: number;+}++const DAY_MS = 24 * 60 * 60_000, MAX_TIME = 1e15, MAX_COUNT = 1e9;+const whole = (value: number, max: number) => Math.min(max, Math.max(0, Math.round(Number.isFinite(value) ? value : 0)));+const counts = (value: OccurrenceCounts): OccurrenceCounts => ({ ran: whole(value.ran, MAX_COUNT), failed: whole(value.failed, MAX_COUNT), missed: whole(value.missed, MAX_COUNT), late: whole(value.late, MAX_COUNT), retried: whole(value.retried, MAX_COUNT) });++/** The last 24 hours, from the saved records. A record that counts a span of occurrences gives the share of them that+ * falls in the day. Occurrences passed over only because the scheduler itself was held up are no misses and are left out. */+export function dayCounts(records: Iterable<Occurrence>, now: number): OccurrenceCounts {+ const day: OccurrenceCounts = { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 }, from = now - DAY_MS;+ const within = (at: number | undefined) => at !== undefined && at > from && at <= now;+ for (const record of records) {+ if (record.void || record.reason === "scheduler-late") continue;+ if (record.attempts > 0 && within(record.startedAt)) {+ if (record.startedAt! - record.dueAt > LATE_START_MS) day.late += 1;+ day.retried += record.attempts - 1;+ }+ if (!occurrenceEnded(record)) continue;+ if (record.state === "ran" || record.state === "failed") { if (within(record.endedAt)) day[record.state] += 1; continue; }+ const last = occurrenceLastAt(record), span = last - record.dueAt, total = record.count ?? 1;+ if (total === 1 || span <= 0) { if (within(record.endedAt ?? last)) day.missed += total; continue; }+ const overlap = Math.min(last, now) - Math.max(record.dueAt, from);+ if (overlap >= 0) day.missed += Math.min(total, Math.max(1, Math.ceil(total * overlap / span)));+ }+ return day;+}++export interface ScheduleReportInput {+ seq: number;+ unreadable: boolean;+ slowStops: number;+ /** The scheduled-for time of each routine's next run that has no row yet: routines that are on and run by the clock. `paused`: its bot takes no runs now. */+ next: ReadonlyArray<{ at: number; paused: boolean }>;+ records: Iterable<Occurrence>;+ boot: OccurrenceCounts;+ now: number;+}++export function scheduleSection({ seq, unreadable, slowStops, next, records, boot, now }: ScheduleReportInput): ScheduleSection {+ const all = [...records], base = { v: 1 as const, seq: whole(seq, MAX_TIME), unreadable };+ const due = { boot: counts(boot), day: counts(unreadable ? { ran: 0, failed: 0, missed: 0, late: 0, retried: 0 } : dayCounts(all, now)) };+ if (unreadable) return { ...base, nextDueAt: null, oldestUnconfirmed: null, lastConfirmed: null, due, slowStops: whole(slowStops, MAX_COUNT) };+ const upcoming = next.filter((one) => !one.paused).map((one) => one.at);+ let oldest: ScheduleSection["oldestUnconfirmed"] = null, last: Occurrence | null = null;+ for (const { at } of next) if (at <= now && (!oldest || at < oldest.dueAt)) oldest = { dueAt: whole(at, MAX_TIME), state: "due", since: whole(at, MAX_TIME) };+ for (const record of all) {+ if (record.void) continue;+ if (record.state === "queued") {+ if (record.dueAt <= now && (!oldest || record.dueAt < oldest.dueAt)) oldest = { dueAt: whole(record.dueAt, MAX_TIME), state: "queued", since: whole(record.madeAt, MAX_TIME) };+ } else if (!last || occurrenceLastAt(record) > occurrenceLastAt(last)) last = record;+ }+ const state = last?.state as Exclude<OccurrenceState, "queued"> | undefined;+ return {+ ...base,+ nextDueAt: upcoming.length ? whole(Math.min(...upcoming), MAX_TIME) : null,+ oldestUnconfirmed: oldest,+ lastConfirmed: last && state ? {+ dueAt: whole(occurrenceLastAt(last), MAX_TIME),+ startedAt: state === "missed" || state === "skipped" ? null : whole(last.startedAt ?? last.endedAt ?? last.madeAt, MAX_TIME),+ state,+ } : null,+ due, slowStops: whole(slowStops, MAX_COUNT),+ };+}diff --git a/server/routine-skips.test.ts b/server/routine-skips.test.tsindex 47386c7035..9cee9acf01 100644--- a/server/routine-skips.test.ts+++ b/server/routine-skips.test.ts@@ -55,6 +55,17 @@ describe("occurrences skipped for one cause", () => {expect(recordSkip(runs, make, cause, ROUTINE_DEFERRAL_NOTICE_MS * 2, 30).tell).toBe(false);expect(runs).toHaveLength(1);});++ it("count with an occurrence the ones that came due before it while nothing could look", () => {+ const runs: RoutineRun[] = [];+ const make = () => { const row = run(`row-${runs.length}`, "queued"); runs.push(row); return row; };+ const cause = { behind: "worker", why: "routines.server.part.stillRunning" as const };+ recordSkip(runs, make, cause, 40, 45, { count: 3, scheduledFor: 10 });+ expect(runs[0]).toMatchObject({ error: "Skipped 4 scheduled runs because the previous run of this routine is still running", skipped: { count: 4, firstAt: 10, lastAt: 40 } });+ recordSkip(runs, make, cause, 70, 75, { count: 2, scheduledFor: 50 });+ expect(runs).toHaveLength(1);+ expect(runs[0]!.skipped).toMatchObject({ count: 7, firstAt: 10, lastAt: 70 });+ });});describe("skip counts read back from routines.json", () => {diff --git a/server/routine-skips.ts b/server/routine-skips.tsindex 3a7a4678b0..5239c2c07f 100644--- a/server/routine-skips.ts+++ b/server/routine-skips.ts@@ -29,16 +29,18 @@ export function blockingRun(runs: readonly RoutineRun[], routineId: string): { rreturn { run, why: run.status === "queued" ? "routines.server.part.notStarted" : "routines.server.part.stillRunning" };}-/** Counts the occurrence at `scheduledFor` on its cause's row, which `make` adds the first time. `tell` is true once per+/** Counts the occurrence at `scheduledFor` on its cause's row, which `make` adds the first time, and with it the+ * `earlier` occurrences that came due before it while nothing could look (routine-catch-up.ts). `tell` is true once per* waiting run, for the first occurrence skipped after it had waited a notice window: the owner is told then, and the row* shows as not yet seen. Any other skip is on a row already seen: a run that is still working when the next one comes* due, or a spacing the owner was told about when it began, asks nothing more of them. */-export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun, cause: { behind: string; why: SkipWhy; waitingSince?: number }, scheduledFor: number, now: number): { row: RoutineRun; added: boolean; tell: boolean } {+export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun, cause: { behind: string; why: SkipWhy; waitingSince?: number }, scheduledFor: number, now: number,+ earlier?: { count: number; scheduledFor: number }): { row: RoutineRun; added: boolean; tell: boolean } {const found = runs.findLast((run) => run.status === "missed" && run.skipped?.behind === cause.behind);- const row = found ?? make();+ const row = found ?? make(), count = 1 + (earlier?.count ?? 0);const skipped: RoutineSkips = found?.skipped- ? { ...found.skipped, count: found.skipped.count + 1, lastAt: Math.max(found.skipped.lastAt, scheduledFor) }- : { count: 1, firstAt: scheduledFor, lastAt: scheduledFor, behind: cause.behind };+ ? { ...found.skipped, count: found.skipped.count + count, lastAt: Math.max(found.skipped.lastAt, scheduledFor) }+ : { count, firstAt: earlier?.scheduledFor ?? scheduledFor, lastAt: scheduledFor, behind: cause.behind };const tell = !skipped.told && cause.waitingSince !== undefined && scheduledFor >= cause.waitingSince + ROUTINE_DEFERRAL_NOTICE_MS;if (tell) skipped.told = true;const line = skipped.count === 1 ? codedLine("error", "routines.server.skippedOne", { why: cause.why }) : codedLine("error", "routines.server.skippedMany", { count: skipped.count, why: cause.why });diff --git a/server/routine-turn-live.test.ts b/server/routine-turn-live.test.tsnew file mode 100644index 0000000000..7707851dab--- /dev/null+++ b/server/routine-turn-live.test.ts@@ -0,0 +1,20 @@+import { expect, it } from "vitest";++import { runTurnLive, type RunTurnFacts } from "./routine-turn-live.ts";++const IDLE: RunTurnFacts = { busy: false, settling: false, queued: false, pending: false, parked: false };+const live = (facts: Partial<RunTurnFacts>, run: { target: "bot" | "room-goal"; threadId: string } = { target: "bot", threadId: "thread-1" }) => runTurnLive(run, () => ({ ...IDLE, ...facts }));++it("takes a run's turn for gone only when nothing of it is left to carry on", () => {+ expect(live({})).toBe(false);+ for (const fact of ["busy", "settling", "queued", "pending"] as const) expect(live({ [fact]: true })).toBe(true);+});++it("keeps a turn parked for a computer alive: it resumes by itself when the computer is free, so the run is never started beside it", () => {+ expect(live({ parked: true })).toBe(true);+});++it("cannot tell for a room goal's run or one with no conversation", () => {+ expect(live({}, { target: "room-goal" as const, threadId: "thread-1" })).toBeNull();+ expect(runTurnLive({ target: "bot", threadId: undefined }, () => IDLE)).toBeNull();+});diff --git a/server/routine-turn-live.ts b/server/routine-turn-live.tsnew file mode 100644index 0000000000..9bddbb4176--- /dev/null+++ b/server/routine-turn-live.ts@@ -0,0 +1,23 @@+import type { RoutineRun } from "./routines.ts";++/** What the host knows of a run's conversation. */+export interface RunTurnFacts {+ /** A turn is working there, or one is being started. */+ busy: boolean;+ /** Its last turn is still being settled. */+ settling: boolean;+ /** A message waits there for its turn. */+ queued: boolean;+ /** Work it handed on, or a turn the runtime will resume, is still open. */+ pending: boolean;+ /** Its turn gave up waiting for a computer another conversation holds, and resumes by itself when that is free. */+ parked: boolean;+}++/** Whether a bot's run still has a turn of its own, working or able to carry on by itself: while it has, the run is+ * never started again beside it. Null for a run the host cannot tell this for (a room goal's, one with no conversation). */+export function runTurnLive(run: Pick<RoutineRun, "target" | "threadId">, facts: (threadId: string) => RunTurnFacts): boolean | null {+ if (run.target !== "bot" || !run.threadId) return null;+ const { busy, settling, queued, pending, parked } = facts(run.threadId);+ return busy || settling || queued || pending || parked;+}diff --git a/server/routines-startup.test.ts b/server/routines-startup.test.tsindex 145fb23f0f..5035e1c9bf 100644--- a/server/routines-startup.test.ts+++ b/server/routines-startup.test.ts@@ -138,12 +138,26 @@ it("recovers queued/due work and a waiting routine's imported hand-off after res}expect(runs, readFileSync(logPath, "utf8").slice(-4_000)).toEqual(expect.arrayContaining([expect.objectContaining({ routineId: scheduled.id, scheduledFor: dueAt, status: "completed" }),- expect.objectContaining({ routineId: cron.id, scheduledFor: cronDueAt, status: "completed" }),+ expect.objectContaining({ routineId: cron.id, triggerSource: "schedule", status: "completed" }),+ // Found five minutes late, the every-minute rule runs its newest minute; the ones before it are counted on one row.+ expect.objectContaining({ routineId: cron.id, scheduledFor: cronDueAt, status: "missed", skipped: expect.objectContaining({ firstAt: cronDueAt }) }),expect.objectContaining({ id: queued.id, routineId: manual.id, status: "completed" }),expect.objectContaining({ routineId: onStartup.id, triggerSource: "startup", status: "completed" }),expect.objectContaining({ id: "interrupted-run", status: "completed" }),]));expect(runs.filter(run => run.routineId === onStartup.id)).toHaveLength(1);+ expect(runs.filter((run) => run.routineId === cron.id && run.status === "completed")).toEqual([expect.objectContaining({ scheduledFor: expect.any(Number) })]);+ const ranFor = runs.find((run) => run.routineId === cron.id && run.status === "completed")!.scheduledFor;+ expect(ranFor).toBeGreaterThan(cronDueAt);+ // The ledger beside routines.json holds one record for the minute that ran and one that counts the minutes before it.+ const history = (await api("GET", `/api/routines?history=${cron.id}`)).occurrences as Array<Record<string, unknown>>;+ expect(history).toEqual(expect.arrayContaining([+ expect.objectContaining({ dueAt: ranFor, state: "ran", attempts: 1 }),+ expect.objectContaining({ dueAt: cronDueAt, state: "missed", reason: "computer-off", attempts: 0 }),+ ]));+ expect(JSON.stringify(history)).not.toContain("lease");+ expect(readFileSync(join(dataDir, "routines.ledger.jsonl"), "utf8")).not.toContain("Recover one cron run");+ expect((await api("GET", "/api/routines")).occurrences).toBeUndefined();const resumedRun = runs.find((run) => run.id === "interrupted-run")!;expect(resumedRun.error).toBeUndefined();expect(resumedRun.finishedAt).toBeGreaterThan(dueAt);diff --git a/server/routines.test.ts b/server/routines.test.tsindex 151961d82a..196e7ce9c8 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -786,26 +786,31 @@ describe("cron routines use the existing persistent scheduler", () => {expect(h.manager.wakeHold()).toEqual({ hold: true, reason: "running" });});- it("catches up once within twelve hours and does not replay missed minute slots", async () => {+ it.each([8, 20])("catches up once with the newest slot after %i hours and counts the missed minute slots on one row", async (hours) => {const h = harness(start);const routine = h.manager.create(input({ ...monthly, expression: "* * * * *" }));- h.setNow(start + 8 * 3_600_000);+ h.setNow(start + hours * 3_600_000);await h.manager.tick(); await h.manager.tick();expect(h.started).toHaveLength(1);- expect(h.manager.listRuns()).toHaveLength(1);- expect(h.manager.listRuns()[0]).toMatchObject({ scheduledFor: routine.nextRunAt, status: "running" });- expect(h.manager.listRoutines()[0].nextRunAt).toBe(start + 8 * 3_600_000 + 60_000);+ expect(h.manager.listRuns()).toHaveLength(2);+ expect(h.manager.listRuns()[0]).toMatchObject({ scheduledFor: start + hours * 3_600_000, status: "running" });+ const older = (start + hours * 3_600_000 - routine.nextRunAt!) / 60_000;+ expect(h.manager.listRuns()[1]).toMatchObject({ scheduledFor: routine.nextRunAt, status: "missed", seenAt: start + hours * 3_600_000,+ skipped: { count: older, firstAt: routine.nextRunAt, lastAt: start + hours * 3_600_000 - 60_000 } });+ expect(h.failed).toHaveLength(0);+ expect(h.manager.listRoutines()[0].nextRunAt).toBe(start + hours * 3_600_000 + 60_000);});- it("records one missed receipt after longer downtime and advances straight to the future", async () => {+ it("records one missed receipt when even the newest occurrence is more than twelve hours old, and advances straight to the future", async () => {const h = harness(start);- const routine = h.manager.create(input({ ...monthly, expression: "* * * * *" }));- h.setNow(start + 20 * 3_600_000);+ const routine = h.manager.create(input({ ...monthly, expression: "0 9 * * *" }));+ h.setNow(routine.nextRunAt! + 13 * 3_600_000);await h.manager.tick(); await h.manager.tick();expect(h.started).toHaveLength(0);expect(h.manager.listRuns()).toHaveLength(1);expect(h.manager.listRuns()[0]).toMatchObject({ scheduledFor: routine.nextRunAt, status: "missed" });- expect(h.manager.listRoutines()[0].nextRunAt).toBe(start + 20 * 3_600_000 + 60_000);+ expect(h.failed).toHaveLength(1);+ expect(h.manager.listRoutines()[0].nextRunAt).toBe(routine.nextRunAt! + 24 * 3_600_000);});it("does not accumulate cron work while a previous run is queued or active", async () => {@@ -2075,7 +2080,8 @@ describe("RoutineManager", () => {expect(h.manager.listRuns()).toMatchObject([{status: "running",scheduledFor: anchorAt + 10 * 60_000,- }]);+ }, { status: "missed", scheduledFor: anchorAt, skipped: { count: 2, firstAt: anchorAt, lastAt: anchorAt + 5 * 60_000 } }]);+ expect(h.started).toHaveLength(1);expect(h.manager.listRoutines()[0]?.nextRunAt).toBe(anchorAt + 15 * 60_000);});@@ -2101,7 +2107,7 @@ describe("RoutineManager", () => {expect(h.manager.listRuns()).toMatchObject([{status: "running",scheduledFor: new Date(2026, 7, 17, 10, 0, 0).getTime(),- }]);+ }, { status: "missed", scheduledFor: new Date(2026, 7, 17, 9, 0, 0).getTime(), skipped: { count: 2, lastAt: new Date(2026, 7, 17, 9, 30, 0).getTime() } }]);expect(h.manager.listRoutines()[0]?.nextRunAt).toBe(new Date(2026, 7, 24, 9, 0, 0).getTime());});@@ -3665,8 +3671,10 @@ describe("run on startup", () => {try {await expect.poll(() => booted.isTicking).toBe(false);expect(h.started).toHaveLength(0);- expect(booted.listRuns()).toHaveLength(1);- expect(booted.listRuns()[0]).toMatchObject({ routineId: routine.id, triggerSource: "schedule", status: "missed" });+ expect(booted.listRuns()).toMatchObject([+ { routineId: routine.id, triggerSource: "schedule", status: "missed", scheduledFor: endsAt, error: "The routine ended before this scheduled run could start" },+ { routineId: routine.id, triggerSource: "schedule", status: "missed", skipped: { count: hours - 1, firstAt: start + 60 * 60_000, lastAt: endsAt - 60 * 60_000 } },+ ]);expect(booted.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });expect(new RoutineManager(h.options).listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });} finally {diff --git a/server/routines.ts b/server/routines.tsindex c243722b62..3ff7867b78 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -30,14 +30,15 @@ import { askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waitimport { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";import { busyWait, markStop, RunClock, runOverLimit, SlowStops, withBoundedStops, type StopState } from "./routine-bounds.ts"; import { keepUnreadableAside, readRoutineFile, UNREADABLE_RETRY_MS } from "./routine-file.ts";import { afterSpacing, noStartAlert, noStartSpacing, turnBackOn } from "./routine-no-start.ts"; import { blockingRun, recordSkip, type RoutineSkips } from "./routine-skips.ts";-import { routineHealthOf, type RoutineHealth } from "./routine-health.ts";+import { routineHealthOf, type RoutineHealth } from "./routine-health.ts"; import { Occurrences, ROUTINE_TURN_GONE } from "./routine-occurrences.ts"; import type { Occurrence } from "./routine-ledger.ts";+import { CATCH_UP_MS, planOccurrence, settleRestored, staggered } from "./routine-catch-up.ts"; import { evictRuns } from "./routine-run-history.ts"; import { RunWatch } from "./routine-run-watch.ts"; import { scheduleSection, type ScheduleSection } from "./routine-schedule-report.ts";import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";import { attachmentPathsOf, cloneAttachments } from "./routine-attachments.ts";import { loadInstalledPackage, matchingRequestReceipt, rememberRequest } from "./routine-load.ts";import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts";import { sanitizeInput } from "./routine-input.ts";-import { applyCheckResult, clipRunOutput, routineLine, runLineFields, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";+import { applyCheckResult, clipRunOutput, codedLine, routineLine, runLineFields, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";import { checkHold, CHECK_BOOT_HOLD_MS, type CheckHold } from "./routine-check-pacing.ts";import { resolveRoutineResultsThread, routineRunDefinition, type ResultsThreadAllocation } from "./routine-run-definition.ts";@@ -294,13 +295,17 @@ export interface RoutineManagerOptions {onReadable?: () => void;/** This copy is frozen by a move to another home (move-freeze.ts): nothing here is turned back on. */moveFrozen?: () => boolean;+ /** The machine this runs on, so a run another machine holds a lease on is told from one this machine left behind; and whether it is a Cloud home, for the words of a missed run. */+ home?: { machine?: string; cloud?: boolean };+ /** Whether the run's conversation has a turn working or about to start; null when that cannot be told. Without it no run is taken for lost. */+ turnLive?: (run: RoutineRun) => boolean | null;}-const CATCH_UP_MS = 12 * 60 * 60_000;const WAKE_HORIZON_MS = 60 * 60_000;export const ROUTINE_RESTARTED = "OpenMausBot restarted while this routine was running";const MAX_RUNS = 2_000;+const earliest = (...times: Array<number | null>): number | null => times.reduce<number | null>((first, at) => at === null ? first : first === null ? at : Math.min(first, at), null);function cloneRoutine(routine: Routine): Routine {return {...routine,@@ -342,12 +347,13 @@ export class RoutineManager {private frozenPending = false;private readonly bootedAt: number;private readonly checking = new Set<string>(); private readonly progress = new RunProgressSave(() => this.file, () => this.save()); private readonly gate = createRunGate<RoutineRun>((run, signal) => this.options.prepareRun?.(cloneRun(run), signal) ?? null, () => this.tickInBackground());+ private readonly ledger: Occurrences; private readonly watch: RunWatch; private passedAt = -Infinity;constructor(options: RoutineManagerOptions) {this.options = withBoundedStops(options, this.slowStops);this.file = options.file ?? join(DATA_DIR, "routines.json"); this.disk = new OwnedFile(this.file, { mode: 0o600 });this.now = options.now ?? Date.now;- this.bootedAt = this.now();+ this.bootedAt = this.now(); this.ledger = new Occurrences(this.file, this.now, options.home?.machine); this.watch = new RunWatch(options.turnLive);this.load();}@@ -362,14 +368,14 @@ export class RoutineManager {webhookRunReceipts: this.webhookRunReceipts, frozenPending: this.frozenPending, ownerNotices: this.ownerNotices, holds: this.holds,startupLaunchId: this.startupLaunchId, noStartOffsChecked: this.noStartOffsChecked } = read);this.disk.loaded(read.text);- const cut: RoutineRun[] = [];+ const cut = settleRestored(this.routines, this.runs, this.ledger.restoredThrough, this.now(), (routine, past) => this.advancePastOccurrence(routine, past, past)).map(cloneRun); this.ledger.restoredThrough = null;for (const run of this.runs.filter((candidate) => candidate.status === "running" || candidate.status === "waiting")) {settleAsk(run, undefined, this.now());if (run.threadId && run.target === "bot" && this.options.hasPendingDelegations?.(run.threadId) === true) {this.wait(run, ROUTINE_HANDOFF_WAIT);continue;}- if (!requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now())) {+ if (!requeueOnce(run, "restarted", ROUTINE_RESTARTED, this.now(), this.ledger.retryAfterBoot(run))) {Object.assign(run, { status: "failed", error: ROUTINE_RESTARTED, attention: undefined, finishedAt: this.now() } satisfies Partial<RoutineRun>);if (run.target === "room-goal") run.goalStatus = "failed";}@@ -378,7 +384,7 @@ export class RoutineManager {const look = !this.noStartOffsChecked && this.options.moveFrozen?.() !== true;const back = look ? turnBackOn(this.routines, this.runs, this.holds[0], this.now(), (schedule, now) => this.initialOccurrence(schedule, now)) : [];// The look is noted with the next save: reading a file in which nothing changes writes nothing.- if (look) { this.noStartOffsChecked = true; this.turnedBackOn = back.filter((routine) => routine.enabled); }+ if (look) { this.noStartOffsChecked = true; this.turnedBackOn = back.filter((routine) => routine.enabled); } this.ledger.observe(this.routines, this.runs, false)();if (cut.length > 0 || back.length > 0) this.saveLater();for (const run of cut) {if (run.threadId) this.options.onRunCut?.(run);@@ -434,6 +440,14 @@ export class RoutineManager {/** Whether routines.json cannot be read, and how often stopping a turn outlasted its wait: for the app and the health report. */schedulerState(): { unreadable: boolean; slowStops: number } { return { unreadable: this.unreadable, slowStops: this.slowStops.count }; }health(cap: number): RoutineHealth[] { return routineHealthOf(this.routines, this.runs, cap); }+ /** The health report's `schedule` section (routine-schedule-report.ts), from the ledger as it is now. */+ scheduleReport(): ScheduleSection {+ const next = this.unreadable ? [] : this.routines.filter((routine) => routine.enabled && !routine.checks && routine.nextRunAt != null && this.targetState(routine) !== "missing")+ .map((routine) => ({ at: routine.nextRunAt!, paused: routine.target !== "room-goal" && Boolean(this.options.pausedText?.(routine.botId)) }));+ return scheduleSection({ seq: this.ledger.sequence(this.unreadable), unreadable: this.unreadable || this.ledger.degraded, slowStops: this.slowStops.count, next, records: this.ledger.ledger.all(), boot: this.ledger.counts, now: this.now() });+ }+ /** A routine's scheduled occurrences as the ledger holds them, newest first: ids, times, counts and fixed words. */+ occurrences(routineId: string): Occurrence[] { return this.ledger.ledger.ofRoutine(routineId).sort((a, b) => b.dueAt - a.dueAt).map((record) => structuredClone(record)); }/** Routines an earlier version had switched off that this start turned back on, handed over once, for a line to their bots. */takeTurnedBackOn(): Routine[] { return this.turnedBackOn.splice(0).map(cloneRoutine); }/** Each routine with the next run it will really make: one whose runs are spaced out is not due for the occurrences it skips. */@@ -946,7 +960,7 @@ export class RoutineManager {if (this.closing || this.timer) return;if (!this.startupRunsQueued) this.startupRunsQueued = this.queueStartupRuns();this.timer = startDueTimer({ run: () => this.tick(), now: this.now, onError: (error) => console.error("routines: a scheduler pass failed", error),- next: () => this.unreadable ? this.now() + UNREADABLE_RETRY_MS : schedulerDueOf(this.routines, this.runs, this.now(), this.bootedAt + CHECK_BOOT_HOLD_MS, (routine) => this.targetState(routine) === "missing") });+ next: () => this.unreadable ? this.now() + UNREADABLE_RETRY_MS : earliest(schedulerDueOf(this.routines, this.runs, this.now(), this.bootedAt + CHECK_BOOT_HOLD_MS, (routine) => this.targetState(routine) === "missing"), this.ledger.beatDueAt(), this.watch.dueAt(this.runs, this.now())) });}stop() {@@ -957,7 +971,7 @@ export class RoutineManager {/** At shutdown: a run whose turn the shutdown cuts stays running on disk, for the next start to pick up once. */close() {this.closing = true; this.progress.atOnce();- this.stop();+ this.stop(); this.ledger.close();}private queueStartupRuns(): boolean {@@ -1009,6 +1023,7 @@ export class RoutineManager {this.options.onReadable?.(); for (const routine of this.routines) this.emitRoutine(routine);}for (const threadId of this.slowStops.sweep()) interruptRunTurns(this.runs.filter((run) => run.threadId === threadId).slice(-1), this.options);+ this.ledger.beat(); for (const run of this.watch.lost(this.runs, now)) this.settleFailure(run, ROUTINE_TURN_GONE, {});for (const run of this.runs) {const over = runOverLimit(run, this.clock, now);if (over) await this.stopRun(Object.assign(run, over.codes), over.text, "limit-reached");@@ -1023,7 +1038,7 @@ export class RoutineManager {for (const run of stale) await this.cancelRun(run.id, ROUTINE_SUPERSEDED);}const dueRoutines = this.routines.filter(isDue);- const scheduledRuns: RoutineRun[] = [], countedSkips: RoutineRun[] = [];+ const scheduledRuns: RoutineRun[] = [], countedSkips: RoutineRun[] = []; let lateStarts = 0;const allocations: ResultsThreadAllocation[] = [];const checks: Array<{ id: string; hold?: CheckHold }> = [];if (dueRoutines.length > 0) {@@ -1036,32 +1051,23 @@ export class RoutineManager {delete routine.wakeAt;continue;}- const pendingAt = routine.nextRunAt!;- const late = now - pendingAt;- const scheduledFor = routine.schedule.type === "interval" && late <= CATCH_UP_MS- ? latestIntervalOccurrence(routine.schedule, now) ?? pendingAt- : pendingAt;+ const plan = planOccurrence(routine, now, this.options.home?.cloud === true, this.passedAt >= routine.nextRunAt!), scheduledFor = plan.scheduledFor;+ if (this.ledger.decided(routine.id, scheduledFor)) { this.advancePastOccurrence(routine, now, plan.through); continue; }const once = runsOnce(routine.schedule), blocker = once ? undefined : blockingRun(this.runs, routine.id), spaced = once ? null : noStartSpacing(routine, this.runs);const scheduledQueued = this.runs.some(run => run.routineId === routine.id && run.status === "queued" &&(run.triggerSource ?? (run.manual ? "manual" : "schedule")) === "schedule");const skipFor = blocker && !(routine.overlap === "queue" && !scheduledQueued) ? { behind: blocker.run.id, why: blocker.why, waitingSince: blocker.waitingSince }: spaced && spaced.until > now ? { behind: `no-start:${spaced.last.id}`, why: "routines.server.part.computerNoStart" as const } : undefined;if (!skipFor) {- const run = this.newRun(routine, scheduledFor, false, allocations);- // A reset is a state, not a moment: it still holds however late the computer wakes.- if (late > CATCH_UP_MS && routine.schedule.type !== "limit_reset") {- run.status = "missed";- run.finishedAt = now;- run.error = "This computer was offline for more than 12 hours after the scheduled time";- }- scheduledRuns.push(run);+ if (plan.older) countedSkips.push(Object.assign(this.newRun(routine, plan.older.scheduledFor, false, allocations), plan.older.fields));+ scheduledRuns.push(Object.assign(this.newRun(routine, scheduledFor, false, allocations), plan.fields, plan.late ? staggered(now, lateStarts++) : {}));} else {- const skip = recordSkip(this.runs, () => this.newRun(routine, scheduledFor, false, allocations), skipFor, scheduledFor, now);+ const skip = recordSkip(this.runs, () => this.newRun(routine, plan.through, false, allocations), skipFor, plan.through, now, plan.count > 1 ? { count: plan.count - 1, scheduledFor: plan.first } : undefined);(skip.tell ? scheduledRuns : countedSkips).push(skip.row);- routine.skippedRuns = Math.min(Number.MAX_SAFE_INTEGER, (routine.skippedRuns ?? 0) + 1);- routine.lastSkippedAt = scheduledFor;+ routine.skippedRuns = Math.min(Number.MAX_SAFE_INTEGER, (routine.skippedRuns ?? 0) + plan.count);+ routine.lastSkippedAt = plan.through;}- this.advancePastOccurrence(routine, now, scheduledFor);+ this.advancePastOccurrence(routine, now, plan.through);}}, () => this.discardResultsThreads(allocations));}@@ -1132,6 +1138,7 @@ export class RoutineManager {}if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);+ if (!this.ledger.ready(run)) continue; if (this.ledger.startedElsewhere(run)) { const line = codedLine("error", "routines.server.duplicate"); Object.assign(run, line.codes); void this.cancelRun(run.id, line.text); continue; }if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { this.failRun(run, gated); continue; }const startedAt = this.now();const suffix = ` · ${new Date(startedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;@@ -1188,7 +1195,7 @@ export class RoutineManager {}}} finally {- this.ticking = false;+ this.ticking = false; this.passedAt = this.now();}}@@ -1247,7 +1254,7 @@ export class RoutineManager {handleRuntimeEvent(event: RuntimeEvent): RoutineRun | null {const run = this.runs.find((r) => r.threadId === event.threadId && ["running", "waiting"].includes(r.status));- if (event.type === "turn.completed") this.slowStops.confirmed(event.threadId);+ if (event.type === "turn.completed") this.slowStops.confirmed(event.threadId); this.watch.seen(event.threadId);if (!run || (run.target === "bot" && run.status === "waiting" && !run.asked && this.options.routineTurn?.(event.threadId) === false)) return null;if (event.type === "turn.started" || event.type === "turn.completed") settleAsk(run, undefined, this.now());// A room goal's orchestrator owns its result (finishGoalRun); a member's completion is intermediate.@@ -1526,16 +1533,7 @@ export class RoutineManager {/** Lands at the end of the running save batch (server/save-batch.ts); what a caller rolls back on failure uses save. */ private saveLater() { saveSoon(this, () => this.save()); }private save() {if (this.unreadable) { this.progress.written(); return; }- // Evict only terminal receipts: an active one owns cancellation, timeout and event routing.- let excess = this.runs.length - MAX_RUNS;- for (let index = 0; index < this.runs.length && excess > 0;) {- if (["queued", "running", "waiting"].includes(this.runs[index]!.status)) {- index += 1;- continue;- }- this.runs.splice(index, 1);- excess -= 1;- }+ evictRuns(this.runs, MAX_RUNS); const recordOccurrences = this.ledger.observe(this.routines, this.runs);mkdirSync(dirname(this.file), { recursive: true });this.disk.write(JSON.stringify({version: 1,@@ -1548,6 +1546,6 @@ export class RoutineManager {...(this.ownerNotices.length ? { ownerNotices: this.ownerNotices } : {}),...(this.holds.length ? { holds: this.holds } : {}),} satisfies RoutineFile));- this.progress.written();+ this.progress.written(); recordOccurrences();}}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 9248d1da10..fac1a9f01a 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10079,6 +10079,15 @@"routines.server.part.stillRunning": "the previous run of this routine is still running","routines.server.part.notStarted": "the previous run of this routine has not started yet","routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out",+ "routines.server.missedOne": "Missed because {why}",+ "routines.server.missedMany": "Missed {count} scheduled runs because {why}",+ "routines.server.missedTooLate": "Missed because {why} until more than {hours} hours after its time",+ "routines.server.part.computerOff": "this computer was asleep or OpenMausBot was not running",+ "routines.server.part.cloudDown": "this Cloud was asleep or restarting",+ "routines.server.part.heldUp": "the scheduler was held up starting another run",+ "routines.server.restored": "Not run again: this schedule was restored from a backup made before this run had its turn",+ "routines.server.restoredMany": "Not run again: {count} scheduled runs from before this schedule was restored from a backup",+ "routines.server.duplicate": "Not started: this scheduled run had already started once","approval.applied.waitFollowUp": "Then {name} will: {followUp}","chat.notice.waitDone.urlContains": "{label}: done. {url} now says “{text}”.","chat.notice.waitDone.urlMissing": "{label}: done. {url} no longer says “{text}”.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex cb34cd06ae..e40e57dd8a 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10010,6 +10010,15 @@"routines.server.part.stillRunning": "a execução anterior desta rotina ainda está em andamento","routines.server.part.notStarted": "a execução anterior desta rotina ainda não começou","routines.server.part.computerNoStart": "o desktop na nuvem dela não iniciou, então as próximas tentativas ficam mais espaçadas",+ "routines.server.missedOne": "Não rodou porque {why}",+ "routines.server.missedMany": "{count} execuções agendadas não rodaram porque {why}",+ "routines.server.missedTooLate": "Não rodou porque {why} até mais de {hours} horas depois do horário",+ "routines.server.part.computerOff": "este computador estava em repouso ou o OpenMausBot não estava aberto",+ "routines.server.part.cloudDown": "este Cloud estava dormindo ou reiniciando",+ "routines.server.part.heldUp": "o agendador ficou preso iniciando outra execução",+ "routines.server.restored": "Não rodou de novo: este agendamento foi restaurado de um backup feito antes de esta execução ter a vez dela",+ "routines.server.restoredMany": "Não rodaram de novo: {count} execuções agendadas de antes de este agendamento ser restaurado de um backup",+ "routines.server.duplicate": "Não iniciou: esta execução agendada já tinha iniciado uma vez","approval.applied.waitFollowUp": "Depois da espera, {name} fará o seguinte: {followUp}","chat.notice.waitDone.urlContains": "Espera concluída: {label}. {url} agora contém “{text}”.","chat.notice.waitDone.urlMissing": "Espera concluída: {label}. {url} não contém mais “{text}”.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex bdc2fc0c0b..8b16496054 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -36983,6 +36983,15 @@"routines.server.part.computerNoStart": "1e1166d01f459bda1f8f5d5f47a750770f92da7874a0d56a5ac94edf7a3de7cd","server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d","server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f",+ "routines.server.missedOne": "53921b4529c366da5012a02c6a6eb73db3a4f6608811b7538681e5c81c5a1a96",+ "routines.server.missedMany": "49b4f390d66cbd36d1f6c8ba20ce7df2f0619a70760b161e5f084a56206beb61",+ "routines.server.missedTooLate": "b4bc3b35791875ece5ed1666e1593e5e217bf8cafce01153ffa3dfce0d74772a",+ "routines.server.part.computerOff": "0826a9c5c5c0254c9beb2ec8874130cf89027a73085a70281b97902763f4ebf9",+ "routines.server.part.cloudDown": "4895a8d573efe7c9926b129a0c2c6693806c1e884443ef8331cd366437301d9c",+ "routines.server.part.heldUp": "063962b8b2377401fc7c77570d5b83e349db2aab6b118886331359dc4bca259f",+ "routines.server.restored": "00cd6b284581fcc1d33a42f19a12ff4900e11019a4db0359d0a18618f6c7bb12",+ "routines.server.restoredMany": "39401539696f40bc0c2f3cd39a1d4a42fd1b76e740722dfc91f4c44c9e1e36f4",+ "routines.server.duplicate": "7516b9e9ffcc2126a9074d00d7277d204e0887e1d13c77fe94920e0428006fcd","engines.unhideAria": "69da7203caed81388e25e663947d80d80a2f54c62d5c4b49800c7225e539a9e8","accounts.signOutCliBody": "dec35f25acc8211621523f7a2d962b28a9a3e91a3aa4864e9c4e87894d40b0a2","accounts.signOutAria": "2986263f26f5e9fe9d5e4722b51d0c989a02d3ff6875adf711e66ed3ef50f4b6",@@ -47213,6 +47222,15 @@"routines.server.part.computerNoStart": "1e1166d01f459bda1f8f5d5f47a750770f92da7874a0d56a5ac94edf7a3de7cd","server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d","server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f",+ "routines.server.missedOne": "53921b4529c366da5012a02c6a6eb73db3a4f6608811b7538681e5c81c5a1a96",+ "routines.server.missedMany": "49b4f390d66cbd36d1f6c8ba20ce7df2f0619a70760b161e5f084a56206beb61",+ "routines.server.missedTooLate": "b4bc3b35791875ece5ed1666e1593e5e217bf8cafce01153ffa3dfce0d74772a",+ "routines.server.part.computerOff": "0826a9c5c5c0254c9beb2ec8874130cf89027a73085a70281b97902763f4ebf9",+ "routines.server.part.cloudDown": "4895a8d573efe7c9926b129a0c2c6693806c1e884443ef8331cd366437301d9c",+ "routines.server.part.heldUp": "063962b8b2377401fc7c77570d5b83e349db2aab6b118886331359dc4bca259f",+ "routines.server.restored": "00cd6b284581fcc1d33a42f19a12ff4900e11019a4db0359d0a18618f6c7bb12",+ "routines.server.restoredMany": "39401539696f40bc0c2f3cd39a1d4a42fd1b76e740722dfc91f4c44c9e1e36f4",+ "routines.server.duplicate": "7516b9e9ffcc2126a9074d00d7277d204e0887e1d13c77fe94920e0428006fcd","engines.unhideAria": "69da7203caed81388e25e663947d80d80a2f54c62d5c4b49800c7225e539a9e8","accounts.signOutCliBody": "dec35f25acc8211621523f7a2d962b28a9a3e91a3aa4864e9c4e87894d40b0a2","accounts.signOutAria": "2986263f26f5e9fe9d5e4722b51d0c989a02d3ff6875adf711e66ed3ef50f4b6",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 45cb42433b..62fb0d238c 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7746,6 +7746,15 @@"routines.server.part.stillRunning": "这个例行任务的上一次运行仍在进行","routines.server.part.notStarted": "这个例行任务的上一次运行还没有开始","routines.server.part.computerNoStart": "它的云端桌面未能启动,所以之后的尝试会隔得更久",+ "routines.server.missedOne": "没有运行,因为{why}",+ "routines.server.missedMany": "有 {count} 次调度运行没有运行,因为{why}",+ "routines.server.missedTooLate": "没有运行,因为{why},直到超过预定时间 {hours} 小时",+ "routines.server.part.computerOff": "这台电脑处于睡眠状态,或 OpenMausBot 没有运行",+ "routines.server.part.cloudDown": "这个 Cloud 正在休眠或重启",+ "routines.server.part.heldUp": "调度器在启动另一次运行时被耽搁了",+ "routines.server.restored": "没有再次运行:这个日程是从备份恢复的,而备份早于这次运行",+ "routines.server.restoredMany": "没有再次运行:{count} 次调度运行发生在这个日程从备份恢复之前",+ "routines.server.duplicate": "没有启动:这次调度运行已经启动过一次","approval.applied.waitFollowUp": "然后 {name} 会:{followUp}","chat.notice.waitDone.urlContains": "{label}:完成。{url} 现在显示“{text}”。","chat.notice.waitDone.urlMissing": "{label}:完成。{url} 不再显示“{text}”。",