Skip to content

Commit 95b86a3

Browse files
authored
refactor(heartbeat): make cron monitor rows own heartbeat cadence (#113135)
* refactor(heartbeat): make cron monitor rows own heartbeat cadence agents.*.heartbeat.every stays the documented desired-state input; gateway reconciliation and openclaw doctor --fix write it through into durable system-owned cron monitor rows, and a scheduled monitor tick carries its persisted everyMs/anchorMs as the authoritative cadence, which the runner adopts for subsequent event cooldowns. Doctor gains a read-only cadence preview (resolves the scheduler seed without creating device identity) and an idempotent fix path that converges monitor rows per agent. The cron-disabled fallback timer is deleted per its named removal plan (#110950): gateways with cron.enabled=false or OPENCLAW_SKIP_CRON=1 log a startup warning and get no scheduled heartbeats; manual and event-driven wakes remain. * fix(ci): drop unused requestHeartbeat import and refresh plugin SDK baseline
1 parent 4ab29c9 commit 95b86a3

22 files changed

Lines changed: 863 additions & 150 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ b013053a61e7d9be3d0c683c02baf57fa7e4393ec54e0df6a46ab0f2fe2348fd module/extensi
6666
ceacad83db01c66e7be6aa21a291597020f13f737b697690eae7d47098e6499a module/gateway-method-runtime
6767
1b8eea4bad785031864822f0f07dc03cbe8670e76e0c3ee8fa51c7a2ee5c5e15 module/gateway-runtime
6868
6062869202e3d7fdaa1f6801d6c1df7bf7406b8118cc4c7167ed409f5257b05c module/group-access
69-
8af05c0b1fbef522b766355360d4ed3d2043f550a86124de7fc93468e8106cef module/health
69+
d117ebba8cc490501725778676a9d75855872b6e5fe2b2f64b1270d4808a2277 module/health
7070
182dc685f2103ff66c1a4839a48f4f40d2eeb0070cd74e449b47aacc4e6f1c22 module/hook-runtime
7171
f6e3c44e7d1090a97aca554a3c247219b8de78b3cb4399cac5efde8a0a6c1156 module/inbound-envelope
7272
f1fa557a1bf0d50c8943433348404bfa5a2e8792199164507c0904f5d288a48d module/inbound-reply-dispatch

‎docs/automation/cron-jobs.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ Every job carries exactly one payload kind, chosen by flag:
166166
| Command | `--command <shell>` or `--command-argv <json>` | A shell/process on the Gateway host, no model call |
167167
| Script | `--script <file\|->` | A headless code-mode script using the owning agent's tools |
168168

169-
One additional payload kind, `heartbeat`, is system-owned: the gateway converges one heartbeat monitor job per heartbeat-enabled agent (see [Heartbeat](/gateway/heartbeat)). It appears in `cron list --all` but cannot be created or edited through the CLI or API — its cadence follows `agents.*.heartbeat` config.
169+
One additional payload kind, `heartbeat`, is system-owned: the gateway converges one heartbeat monitor job per heartbeat-enabled agent (see [Heartbeat](/gateway/heartbeat)). It appears in `cron list --all` but cannot be created or edited through the CLI or API. Heartbeat config is written through to the persisted monitor schedule at startup, on config reload, or by `openclaw doctor --fix`. When cron is disabled, the monitor does not tick and no fallback heartbeat timer runs.
170170

171171
### Agent-turn options
172172

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,7 @@ Periodic heartbeat runs.
571571
```
572572

573573
- `every`: duration string (ms/s/m/h). Default: `30m` (API-key auth) or `1h` (OAuth auth). Set to `0m` to disable.
574+
- Cadence is written into a system-owned cron monitor row. Run `openclaw doctor --fix` to materialize a missing or stale row. If cron is disabled, scheduled heartbeats do not run and the gateway logs a startup warning.
574575
- `includeSystemPromptSection`: when false, omits the Heartbeat section from the system prompt. Default: `true`.
575576
- `suppressToolErrorWarnings`: when true, suppresses tool error warning payloads during heartbeat runs.
576577
- `timeoutSeconds`: maximum time in seconds allowed for a heartbeat agent turn before it is aborted. Leave unset to use `agents.defaults.timeoutSeconds` when set, otherwise the heartbeat cadence capped at 600 seconds.

‎docs/gateway/heartbeat.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ Heartbeat runs **periodic agent turns** in the main session so the model can sur
1515

1616
Heartbeat is a scheduled main-session turn - it does **not** create [background task](/automation/tasks) records. Task records are for detached work (ACP runs, subagents, isolated cron jobs).
1717

18-
Under the hood, heartbeat cadence is owned by the cron scheduler: the gateway maintains one system-owned cron job per heartbeat-enabled agent (visible in `openclaw cron list --all` as `Heartbeat (agent-id)`). Each tick requests a heartbeat wake; the heartbeat runner still applies its own cooldown, active-hours, and busy guards, so a tick outside the configured window is skipped, not delivered. These monitor jobs are converged from your heartbeat config at startup and on config reload — edit `agents.*.heartbeat`, not the cron job.
18+
Under the hood, heartbeat cadence is owned by the cron scheduler: the gateway maintains one system-owned cron job per heartbeat-enabled agent (visible in `openclaw cron list --all` as `Heartbeat (agent-id)`). Heartbeat config remains the desired-state input, while the persisted monitor schedule owns the actual tick and the runner's later cooldown. The gateway writes config changes through at startup and on config reload; `openclaw doctor --fix` can materialize missing or stale monitor rows before the next gateway start. Edit `agents.*.heartbeat`, not the cron job.
19+
20+
Scheduled heartbeats require cron. When `cron.enabled` is `false` or `OPENCLAW_SKIP_CRON=1`, the gateway logs a startup warning and does not run scheduled heartbeats; manual and event-driven heartbeat wakes remain available. There is no separate heartbeat fallback timer.
1921

2022
Troubleshooting: [Scheduled Tasks](/automation/cron-jobs#troubleshooting)
2123

@@ -65,6 +67,7 @@ Example config:
6567
- Timeout: unset heartbeat turns use `agents.defaults.timeoutSeconds` when set. Otherwise, they use the heartbeat cadence capped at 600 seconds. Set `agents.defaults.heartbeat.timeoutSeconds` or per-agent `agents.entries.*.heartbeat.timeoutSeconds` for longer heartbeat work.
6668
- The heartbeat prompt is sent **verbatim** as the user message. The system prompt includes a "Heartbeats" section when heartbeats are enabled for the default agent, and the run is flagged internally.
6769
- When heartbeats are disabled with `0m`, the monitor cron job stays but is disabled, and its scratch is retained for when you re-enable the cadence.
70+
- When cron itself is disabled, scheduled heartbeats do not run even if heartbeat cadence remains enabled.
6871
- Active hours (`heartbeat.activeHours`) are checked in the configured timezone. Outside the window, heartbeats are skipped until the next tick inside the window.
6972
- Heartbeats automatically defer while cron work is active or queued, or while that agent's session-keyed subagent or nested command lanes are busy. Sibling agents do not pause each other.
7073

@@ -379,7 +382,7 @@ Writes are compare-and-swap guarded: pass `--expected-revision <n>` to fail inst
379382
The agent can also update its own scratch: during a heartbeat turn, `heartbeat_respond` accepts an optional `scratch` string that fully replaces the monitor's scratch for future heartbeats.
380383

381384
<Note>
382-
**Migrating from HEARTBEAT.md?** Run `openclaw doctor --fix`. Doctor imports each agent's workspace `HEARTBEAT.md` into the monitor's scratch, archives the original under the state directory (`backups/heartbeat-migration/`), and then removes the file. For one stable upgrade window, an unmigrated legacy file remains a read-only fallback when no scratch revision exists, with a Gateway warning directing you to Doctor; new workspaces and completed migrations use database scratch only.
385+
**Migrating from HEARTBEAT.md or config-only cadence?** Run `openclaw doctor --fix`. Doctor first creates or updates the system-owned monitor rows from `agents.*.heartbeat`, then imports each agent's workspace `HEARTBEAT.md` into the monitor's scratch, archives the original under the state directory (`backups/heartbeat-migration/`), and removes the file. For one stable upgrade window, an unmigrated legacy file remains a read-only fallback when no scratch revision exists, with a Gateway warning directing you to Doctor; new workspaces and completed migrations use database scratch only.
383386
</Note>
384387

385388
If scratch exists but is effectively empty (only blank lines, Markdown/HTML comments, Markdown headings like `# Heading`, fence markers, or empty checklist stubs), OpenClaw skips the heartbeat run to save API calls. That skip is reported as `reason=empty-heartbeat-file`. If no scratch exists, the heartbeat still runs and the model decides what to do.
Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { heartbeatMonitorAgentId } from "../cron/heartbeat-monitor.js";
7+
import { loadCronJobsStore, resolveCronJobsStorePathFromConfig } from "../cron/store.js";
8+
import { loadOrCreateDeviceIdentity } from "../infra/device-identity.js";
9+
import { resolveHeartbeatPhaseMs } from "../infra/heartbeat-schedule.js";
10+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
11+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
12+
import {
13+
collectHeartbeatCadenceMigrationFindings,
14+
maybeMigrateHeartbeatCadenceToCron,
15+
} from "./doctor-heartbeat-cadence-migration.js";
16+
17+
const tempDirs: string[] = [];
18+
let originalHome: string | undefined;
19+
let originalStateDir: string | undefined;
20+
21+
beforeEach(() => {
22+
originalHome = process.env.HOME;
23+
originalStateDir = process.env.OPENCLAW_STATE_DIR;
24+
});
25+
26+
afterEach(async () => {
27+
closeOpenClawStateDatabaseForTest();
28+
vi.restoreAllMocks();
29+
if (originalHome === undefined) {
30+
delete process.env.HOME;
31+
} else {
32+
process.env.HOME = originalHome;
33+
}
34+
if (originalStateDir === undefined) {
35+
delete process.env.OPENCLAW_STATE_DIR;
36+
} else {
37+
process.env.OPENCLAW_STATE_DIR = originalStateDir;
38+
}
39+
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
40+
});
41+
42+
async function createFixture(every = "15m") {
43+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-heartbeat-cadence-"));
44+
tempDirs.push(root);
45+
process.env.HOME = path.join(root, "home");
46+
process.env.OPENCLAW_STATE_DIR = root;
47+
const env = process.env;
48+
const cfg = {
49+
agents: {
50+
defaults: { heartbeat: { every } },
51+
list: [{ id: "main" }],
52+
},
53+
} as OpenClawConfig;
54+
const storePath = resolveCronJobsStorePathFromConfig(cfg, env);
55+
return { cfg, env, storePath };
56+
}
57+
58+
async function loadMonitor(storePath: string, agentId: string) {
59+
const store = await loadCronJobsStore(storePath);
60+
return store.jobs.find((job) => heartbeatMonitorAgentId(job) === agentId);
61+
}
62+
63+
async function loadMainMonitor(storePath: string) {
64+
return loadMonitor(storePath, "main");
65+
}
66+
67+
describe("heartbeat cadence cron migration", () => {
68+
it("previews without mutation, applies, updates, and reruns idempotently", async () => {
69+
const fixture = await createFixture();
70+
71+
const findings = await collectHeartbeatCadenceMigrationFindings(fixture.cfg, fixture.env);
72+
expect(findings).toEqual([
73+
expect.objectContaining({
74+
checkId: "core/doctor/heartbeat-cadence-migration",
75+
requirement: "heartbeat-monitor-create",
76+
target: "main",
77+
}),
78+
]);
79+
80+
const preview = await maybeMigrateHeartbeatCadenceToCron({
81+
cfg: fixture.cfg,
82+
shouldRepair: false,
83+
env: fixture.env,
84+
});
85+
expect(preview).toEqual({ changes: [], warnings: [] });
86+
await expect(fs.access(resolveOpenClawStateSqlitePath(fixture.env))).rejects.toMatchObject({
87+
code: "ENOENT",
88+
});
89+
expect(await loadMainMonitor(fixture.storePath)).toBeUndefined();
90+
91+
const migrated = await maybeMigrateHeartbeatCadenceToCron({
92+
cfg: fixture.cfg,
93+
shouldRepair: true,
94+
env: fixture.env,
95+
});
96+
expect(migrated.warnings).toEqual([]);
97+
expect(migrated.changes).toEqual(['Create heartbeat monitor for agent "main" at 15m.']);
98+
const created = await loadMainMonitor(fixture.storePath);
99+
expect(created).toEqual(
100+
expect.objectContaining({
101+
declarationKey: "heartbeat:main",
102+
enabled: true,
103+
schedule: expect.objectContaining({ kind: "every", everyMs: 15 * 60_000 }),
104+
payload: { kind: "heartbeat" },
105+
}),
106+
);
107+
108+
const updatedCfg = {
109+
...fixture.cfg,
110+
agents: { ...fixture.cfg.agents, defaults: { heartbeat: { every: "45m" } } },
111+
} as OpenClawConfig;
112+
const updated = await maybeMigrateHeartbeatCadenceToCron({
113+
cfg: updatedCfg,
114+
shouldRepair: true,
115+
env: fixture.env,
116+
});
117+
expect(updated.changes).toEqual(['Update heartbeat monitor for agent "main" at 45m.']);
118+
const changed = await loadMainMonitor(fixture.storePath);
119+
expect(changed?.id).toBe(created?.id);
120+
expect(changed?.schedule).toEqual(
121+
expect.objectContaining({ kind: "every", everyMs: 45 * 60_000 }),
122+
);
123+
124+
const rerun = await maybeMigrateHeartbeatCadenceToCron({
125+
cfg: updatedCfg,
126+
shouldRepair: true,
127+
env: fixture.env,
128+
});
129+
expect(rerun).toEqual({ changes: [], warnings: [] });
130+
await expect(
131+
collectHeartbeatCadenceMigrationFindings(updatedCfg, fixture.env),
132+
).resolves.toEqual([]);
133+
});
134+
135+
it("preserves a disabled heartbeat as a disabled monitor row", async () => {
136+
const fixture = await createFixture("0m");
137+
138+
const result = await maybeMigrateHeartbeatCadenceToCron({
139+
cfg: fixture.cfg,
140+
shouldRepair: true,
141+
env: fixture.env,
142+
});
143+
144+
expect(result.warnings).toEqual([]);
145+
expect(await loadMainMonitor(fixture.storePath)).toEqual(
146+
expect.objectContaining({ enabled: false, payload: { kind: "heartbeat" } }),
147+
);
148+
});
149+
150+
it("keeps multi-agent updates and creates scoped to their declared monitors", async () => {
151+
const fixture = await createFixture();
152+
const initialCfg = {
153+
agents: {
154+
list: [
155+
{ id: "alpha", heartbeat: { every: "15m" } },
156+
{ id: "beta", heartbeat: { every: "20m" } },
157+
],
158+
},
159+
} as OpenClawConfig;
160+
await maybeMigrateHeartbeatCadenceToCron({
161+
cfg: initialCfg,
162+
shouldRepair: true,
163+
env: fixture.env,
164+
});
165+
const alphaBefore = await loadMonitor(fixture.storePath, "alpha");
166+
const betaBefore = await loadMonitor(fixture.storePath, "beta");
167+
168+
const updatedCfg = {
169+
agents: {
170+
list: [
171+
{ id: "alpha", heartbeat: { every: "45m" } },
172+
{ id: "gamma", heartbeat: { every: "30m" } },
173+
],
174+
},
175+
} as OpenClawConfig;
176+
const result = await maybeMigrateHeartbeatCadenceToCron({
177+
cfg: updatedCfg,
178+
shouldRepair: true,
179+
env: fixture.env,
180+
});
181+
182+
expect(result).toEqual({
183+
changes: [
184+
'Update heartbeat monitor for agent "alpha" at 45m.',
185+
'Create heartbeat monitor for agent "gamma" at 30m.',
186+
'Remove stale heartbeat monitor for agent "beta".',
187+
],
188+
warnings: [],
189+
});
190+
const alphaAfter = await loadMonitor(fixture.storePath, "alpha");
191+
const gammaAfter = await loadMonitor(fixture.storePath, "gamma");
192+
expect(alphaAfter).toEqual(
193+
expect.objectContaining({
194+
id: alphaBefore?.id,
195+
declarationKey: "heartbeat:alpha",
196+
agentId: "alpha",
197+
schedule: expect.objectContaining({ kind: "every", everyMs: 45 * 60_000 }),
198+
}),
199+
);
200+
expect(gammaAfter).toEqual(
201+
expect.objectContaining({
202+
declarationKey: "heartbeat:gamma",
203+
agentId: "gamma",
204+
schedule: expect.objectContaining({ kind: "every", everyMs: 30 * 60_000 }),
205+
}),
206+
);
207+
expect(gammaAfter?.id).not.toBe(betaBefore?.id);
208+
expect(await loadMonitor(fixture.storePath, "beta")).toBeUndefined();
209+
});
210+
211+
it("uses the supplied environment for the writable scheduler seed", async () => {
212+
const ambientRoot = await fs.mkdtemp(
213+
path.join(os.tmpdir(), "openclaw-heartbeat-cadence-ambient-"),
214+
);
215+
const suppliedRoot = await fs.mkdtemp(
216+
path.join(os.tmpdir(), "openclaw-heartbeat-cadence-supplied-"),
217+
);
218+
tempDirs.push(ambientRoot, suppliedRoot);
219+
process.env.HOME = path.join(ambientRoot, "home");
220+
process.env.OPENCLAW_STATE_DIR = ambientRoot;
221+
const ambientEnv = { ...process.env };
222+
const suppliedEnv = {
223+
...process.env,
224+
HOME: path.join(suppliedRoot, "home"),
225+
OPENCLAW_STATE_DIR: suppliedRoot,
226+
};
227+
const ambientIdentity = loadOrCreateDeviceIdentity({ env: ambientEnv });
228+
const suppliedIdentity = loadOrCreateDeviceIdentity({ env: suppliedEnv });
229+
const intervalMs = 15 * 60_000;
230+
const agentId = ["main", "ops", "alpha", "beta"].find(
231+
(candidate) =>
232+
resolveHeartbeatPhaseMs({
233+
schedulerSeed: ambientIdentity.deviceId,
234+
agentId: candidate,
235+
intervalMs,
236+
}) !==
237+
resolveHeartbeatPhaseMs({
238+
schedulerSeed: suppliedIdentity.deviceId,
239+
agentId: candidate,
240+
intervalMs,
241+
}),
242+
);
243+
if (!agentId) {
244+
throw new Error("expected ambient and supplied identities to produce a distinct phase");
245+
}
246+
const cfg = {
247+
agents: {
248+
defaults: { heartbeat: { every: "15m" } },
249+
list: [{ id: agentId }],
250+
},
251+
} as OpenClawConfig;
252+
const storePath = resolveCronJobsStorePathFromConfig(cfg, suppliedEnv);
253+
254+
const result = await maybeMigrateHeartbeatCadenceToCron({
255+
cfg,
256+
shouldRepair: true,
257+
env: suppliedEnv,
258+
});
259+
260+
expect(result.warnings).toEqual([]);
261+
const monitor = await loadMonitor(storePath, agentId);
262+
expect(monitor?.schedule).toEqual(
263+
expect.objectContaining({
264+
kind: "every",
265+
everyMs: intervalMs,
266+
anchorMs: resolveHeartbeatPhaseMs({
267+
schedulerSeed: suppliedIdentity.deviceId,
268+
agentId,
269+
intervalMs,
270+
}),
271+
}),
272+
);
273+
});
274+
});

0 commit comments

Comments
 (0)