Skip to content

Commit b23c7bd

Browse files
authored
feat(cron): convert heartbeat tasks: entries into independent cron jobs (#113165)
Each legacy heartbeat tasks: entry becomes an editable system-created cron job (declaration key heartbeat-task:<agentId>:<hash>, per-occurrence identity for duplicate names) that fires a guarded heartbeat wake carrying the task prompt plus current monitor scratch context. Task cadence is now independent of the base heartbeat interval; active-hours, busy-retry, min-spacing, and flood guards are preserved, deferred payload-carrying wakes are retained and retried after the spacing floor, and colliding task/event wakes cannot starve each other. openclaw doctor --fix migrates existing blocks: async parse/plan, then one synchronous SQLite transaction that rereads the pinned scratch revision, upserts job rows, and strips the tasks: block atomically — concurrent doctors serialize on the database and a losing run aborts untouched. Orphan fields, invalid intervals, and incomplete entries block migration of their block with a clear finding instead of silent text loss. The runtime tasks: parser is deleted; leftover text is ordinary scratch prose. Nine Codex gpt-5.6-sol xhigh autoreview cycles; final verdict clean.
1 parent b3b9e69 commit b23c7bd

45 files changed

Lines changed: 2785 additions & 525 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ aa2a56b4448c8ebdec9d06aac95d809995f533093d42fa32cd75e1d852967245 module/questio
103103
bd2355e94248d21c252148085e5afa5db9a2f3f48f665a8b3e0fcf77326d9b6c module/reply-dispatch-runtime
104104
ac2b199e95c5c8b1e2a65e62bd41d1b6322e531bca294ef4979a297a12640bce module/reply-history
105105
f394fe4d5a7ed9e4d574063ae44e8d6af85c9a0e7d8b329f750ca16b0664325f module/reply-payload
106-
554bbc681b17bf102a5e240e3f563c7d3c3f1dbab31f8fa3c9285f106c3e8111 module/reply-runtime
106+
6b8a50764563f096175162c49d1acf5593eee3363edd45976c1aa641a3d532cf module/reply-runtime
107107
d78db621b8f4f0cc679cad2d5d21b6c95b5418c58611dd347cdf09049ed124f6 module/routing
108108
ff6cca86f54f94f238205f5b122af36666314e0a380f3ec7f0ccb9ed9208df31 module/run-command
109109
53b0295cec105696a1664c5c7f5576a7b55d197eb95dcd9185486f010bd53750 module/runtime

‎docs/automation/cron-jobs.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,14 @@ Timestamps without a timezone are treated as UTC. Add `--tz America/New_York` to
7777

7878
Recurring top-of-hour expressions (minute `0` with a wildcard hour field) are automatically staggered by up to 5 minutes to reduce load spikes. Use `--exact` to force precise timing, or `--stagger 30s` for an explicit window (cron schedules only).
7979

80+
### Heartbeat task migration
81+
82+
Older heartbeat scratch supported a structured `tasks:` block. Run `openclaw doctor --fix` after upgrading to convert each entry into an ordinary editable main-session cron job. Doctor preserves the interval and previous last-run timing, creates the jobs before removing the block, and safely converges the same declaration keys on rerun.
83+
84+
These migrated jobs carry public `systemEvent` payloads, so `openclaw cron list`, `get`, `edit`, and `remove` plus the cron tool manage them like other jobs. Their execution uses the guarded heartbeat task wake: active hours, minimum spacing, flood control, and busy retries still apply, while cron owns each task's independent cadence. Jobs due in the same coalescing window can share one heartbeat turn. A scheduled occurrence outside heartbeat active hours is skipped and retried at the job's next occurrence.
85+
86+
Heartbeat scratch is now monitor prose only. Runtime heartbeats do not parse `tasks:` text as schedules; create new recurring work with cron.
87+
8088
### Stream sources
8189

8290
A stream schedule keeps an operator-authored argv command running under the Gateway and fires the job from its stdout and stderr lines. Stream schedules are event-driven, never time-due, and require `cron.triggers.enabled: true` because the long-lived command has the same unattended trust class as trigger scripts. Disabling or removing the job stops the process; Gateway shutdown waits for process-tree teardown. Fast failures restart with cron's built-in error backoff. Five consecutive runs shorter than 60 seconds leave the job in an error state and use the normal failure-alert path; manually re-enable the job to clear the restart cap.

‎docs/automation/index.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,14 +95,14 @@ See [Hooks](/automation/hooks).
9595

9696
### Heartbeat
9797

98-
Heartbeat is a periodic main-session turn (default every 30 minutes). It batches multiple checks (inbox, calendar, notifications) in one agent turn with full session context. Heartbeat turns do not create task records and do not extend daily/idle session reset freshness. Use `HEARTBEAT.md` for a small checklist, or a `tasks:` block when you want due-only periodic checks inside heartbeat itself. Empty heartbeat files skip as `empty-heartbeat-file`; due-only task mode skips as `no-tasks-due`. Heartbeats defer while cron work is active or queued, and `heartbeat.skipWhenBusy` can also defer an agent while that same agent's session-keyed subagent or nested lanes are busy.
98+
Heartbeat is a periodic main-session turn (default every 30 minutes). It batches checklist-style monitoring (inbox, calendar, notifications) in one agent turn with full session context. Heartbeat turns do not create task records and do not extend daily/idle session reset freshness. Heartbeat scratch is small prompt context; schedule recurring work as cron jobs. Empty heartbeat scratch skips as `empty-heartbeat-file`. Heartbeats defer while cron work is active or queued, and `heartbeat.skipWhenBusy` can also defer an agent while that same agent's session-keyed subagent or nested lanes are busy.
9999

100100
See [Heartbeat](/gateway/heartbeat).
101101

102102
## How they work together
103103

104104
- **Cron** handles precise schedules (daily reports, weekly reviews) and one-shot reminders. All cron executions create task records.
105-
- **Heartbeat** handles routine monitoring (inbox, calendar, notifications) in one batched turn every 30 minutes.
105+
- **Heartbeat** handles one batched monitoring checklist every 30 minutes; cron owns checks that need independent cadences.
106106
- **Hooks** react to specific events (session resets, compaction, message flow) with custom scripts. Plugin hooks cover tool calls.
107107
- **Standing orders** give the agent persistent context and authority boundaries.
108108
- **Task Flow** coordinates multi-step flows above individual tasks.

‎docs/docs_map.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
6666
- H2: Quick start
6767
- H2: How cron works
6868
- H2: Schedule types
69+
- H3: Heartbeat task migration
6970
- H3: Stream sources
7071
- H3: Dynamic cadence (pacing)
7172
- H3: Day-of-month and day-of-week use OR logic
@@ -3602,7 +3603,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
36023603
- H3: Per-channel vs per-account examples
36033604
- H3: Common patterns
36043605
- H2: Monitor scratch (optional)
3605-
- H3: tasks: blocks
3606+
- H3: Schedule recurring checks with cron
36063607
- H3: Can the agent update its scratch?
36073608
- H2: Manual wake (on-demand)
36083609
- H2: Cost awareness

‎docs/gateway/heartbeat.md‎

Lines changed: 10 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Troubleshooting: [Scheduled Tasks](/automation/cron-jobs#troubleshooting)
2828
Leave heartbeats enabled (default is `30m`, or `1h` when Anthropic OAuth/token auth is configured, including Claude CLI reuse) or set your own cadence.
2929
</Step>
3030
<Step title="Add monitor scratch (optional)">
31-
Store a tiny checklist or `tasks:` block in the heartbeat monitor's scratch with `openclaw cron scratch <jobId> --set "..."`.
31+
Store a tiny checklist in the heartbeat monitor's scratch with `openclaw cron scratch <jobId> --set "..."`.
3232
</Step>
3333
<Step title="Decide where heartbeat messages should go">
3434
`target: "none"` is the default; set `target: "last"` to route to the last contact.
@@ -63,7 +63,7 @@ Example config:
6363
## Defaults
6464

6565
- Interval: `30m`. Applying Anthropic provider defaults bumps this to `1h` when the resolved auth mode is OAuth/token (including Claude CLI reuse), but only while `heartbeat.every` is unset. Set `agents.defaults.heartbeat.every` or per-agent `agents.entries.*.heartbeat.every`; use `0m` to disable.
66-
- Prompt body (configurable via `agents.defaults.heartbeat.prompt`): `Follow the heartbeat monitor scratch context when provided. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`
66+
- Prompt body (configurable via `agents.defaults.heartbeat.prompt`): `Follow the heartbeat monitor scratch context when provided. Recurring tasks are cron jobs; create or change their schedules with cron tools or the openclaw cron CLI, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`
6767
- 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.
6868
- 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.
6969
- 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.
@@ -107,7 +107,7 @@ Outside heartbeats, stray `HEARTBEAT_OK` at the start/end of a message is stripp
107107
target: "last", // default: none | options: last | none | <channel id> (core or plugin, e.g. "imessage")
108108
to: "+15551234567", // optional channel-specific override
109109
accountId: "ops-bot", // optional multi-account channel id
110-
prompt: "Follow the heartbeat monitor scratch context when provided. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.",
110+
prompt: "Follow the heartbeat monitor scratch context when provided. Recurring tasks are cron jobs; create or change their schedules with cron tools or the openclaw cron CLI, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.",
111111
},
112112
},
113113
},
@@ -146,7 +146,7 @@ Example: two agents, only the second agent runs heartbeats.
146146
target: "whatsapp",
147147
to: "+15551234567",
148148
timeoutSeconds: 45,
149-
prompt: "Follow the heartbeat monitor scratch context when provided. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.",
149+
prompt: "Follow the heartbeat monitor scratch context when provided. Recurring tasks are cron jobs; create or change their schedules with cron tools or the openclaw cron CLI, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.",
150150
},
151151
},
152152
],
@@ -382,7 +382,7 @@ Writes are compare-and-swap guarded: pass `--expected-revision <n>` to fail inst
382382
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.
383383

384384
<Note>
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.
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, converts any valid legacy `tasks:` entries into cron jobs, 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.
386386
</Note>
387387

388388
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.
@@ -399,45 +399,17 @@ Example scratch:
399399
- If a task is blocked, write down _what is missing_ and ask Peter next time.
400400
```
401401

402-
### `tasks:` blocks
402+
### Schedule recurring checks with cron
403403

404-
Scratch also supports a small structured `tasks:` block for interval-based checks inside heartbeat itself.
404+
Heartbeat scratch is prompt context, not a scheduler. Create each recurring check as a [cron job](/automation/cron-jobs) so it has its own cadence, enable/disable state, and run history. Cron jobs can still target the main session when the check should use the normal conversation context.
405405

406-
Example:
406+
Older scratch may contain a structured `tasks:` block. Run `openclaw doctor --fix` once after upgrading: Doctor converts every valid entry into an independently scheduled cron job, preserves its interval and previous last-run timing, and removes the retired block while keeping surrounding scratch prose. Runtime heartbeat turns do not parse `tasks:` text as schedules.
407407

408-
```md
409-
tasks:
410-
411-
- name: inbox-triage
412-
interval: 30m
413-
prompt: "Check for urgent unread emails and flag anything time sensitive."
414-
- name: calendar-scan
415-
interval: 2h
416-
prompt: "Check for upcoming meetings that need prep or follow-up."
417-
418-
# Additional instructions
419-
420-
- Keep alerts short.
421-
- If nothing needs attention after all due tasks, reply HEARTBEAT_OK.
422-
```
423-
424-
<AccordionGroup>
425-
<Accordion title="Behavior">
426-
- OpenClaw parses the `tasks:` block and checks each task against its own `interval`.
427-
- Only **due** tasks are included in the heartbeat prompt for that tick.
428-
- If no tasks are due, the heartbeat is skipped entirely (`reason=no-tasks-due`) to avoid a wasted model call.
429-
- Non-task scratch content is preserved and appended as additional context after the due-task list.
430-
- Task last-run timestamps are stored in session state (`heartbeatTaskState`), so intervals survive normal restarts.
431-
- Task timestamps are only advanced after a heartbeat run completes its normal reply path. Skipped `empty-heartbeat-file` / `no-tasks-due` runs do not mark tasks as completed.
432-
433-
</Accordion>
434-
</AccordionGroup>
435-
436-
Task mode is useful when you want one scratch document to hold several periodic checks without paying for all of them every tick.
408+
Doctor-created heartbeat task jobs keep heartbeat active-hours, cooldown, flood, and busy guards. Jobs due together can coalesce into one heartbeat turn. An occurrence outside active hours is skipped and tried again at its next cron occurrence.
437409

438410
### Can the agent update its scratch?
439411

440-
Yes. During a heartbeat turn, the agent can pass a `scratch` value to `heartbeat_respond` to fully replace the monitor scratch for future heartbeats. You can also ask it in a normal chat to run `openclaw cron scratch <jobId> --set ...`, or edit the scratch yourself with the same command.
412+
Yes. During a heartbeat turn, the agent can pass a `scratch` value to `heartbeat_respond` to fully replace the monitor prose for future heartbeats. You can also ask it in a normal chat to run `openclaw cron scratch <jobId> --set ...`, or edit the scratch yourself with the same command. Manage recurring schedules with cron instead of writing scheduler syntax into scratch.
441413

442414
<Warning>
443415
Don't put secrets (API keys, phone numbers, private tokens) into monitor scratch - it becomes part of the prompt context.

‎docs/gateway/troubleshooting.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -756,15 +756,14 @@ Look for:
756756
757757
- Cron enabled and next wake present.
758758
- Job run history status (`ok`, `skipped`, `error`).
759-
- Heartbeat skip reasons (`quiet-hours`, `requests-in-flight`, `cron-in-progress`, `lanes-busy`, `alerts-disabled`, `empty-heartbeat-file`, `no-tasks-due`).
759+
- Heartbeat skip reasons (`quiet-hours`, `requests-in-flight`, `cron-in-progress`, `lanes-busy`, `alerts-disabled`, `empty-heartbeat-file`).
760760
761761
<AccordionGroup>
762762
<Accordion title="Common signatures">
763763
- `cron: scheduler disabled; jobs will not run automatically` → cron disabled.
764764
- `cron: timer tick failed` → scheduler tick failed; check file/log/runtime errors.
765765
- `heartbeat skipped` with `reason=quiet-hours` → outside active hours window.
766-
- `heartbeat skipped` with `reason=empty-heartbeat-file` → `HEARTBEAT.md` exists but only contains blank, comment, header, fence, or empty-checklist scaffolding, so OpenClaw skips the model call.
767-
- `heartbeat skipped` with `reason=no-tasks-due` → `HEARTBEAT.md` contains a `tasks:` block, but none of the tasks are due on this tick.
766+
- `heartbeat skipped` with `reason=empty-heartbeat-file` → heartbeat monitor scratch only contains blank, comment, header, fence, or empty-checklist scaffolding, so OpenClaw skips the model call.
768767
- `heartbeat: unknown accountId` → invalid account id for heartbeat delivery target.
769768
- `heartbeat skipped` with `reason=dm-blocked` → heartbeat target resolved to a DM-style destination while `agents.defaults.heartbeat.directPolicy` (or per-agent override) is set to `block`.
770769

‎docs/help/faq-first-run.md‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,10 @@ and troubleshooting see the main [FAQ](/help/faq).
5757
| Skip reason | Meaning |
5858
| --- | --- |
5959
| `quiet-hours` | Outside the configured active-hours window |
60-
| `empty-heartbeat-file` | `HEARTBEAT.md` exists but only has blank, comment, header, fence, or empty-checklist scaffolding |
61-
| `no-tasks-due` | Task mode is active but no task interval is due yet |
60+
| `empty-heartbeat-file` | Heartbeat monitor scratch exists but only has blank, comment, header, fence, or empty-checklist scaffolding |
6261
| `alerts-disabled` | All heartbeat visibility is off (`showOk`, `showAlerts`, and `useIndicator` all disabled) |
6362

64-
In task mode, due timestamps advance only after a real heartbeat run completes.
65-
Skipped runs do not mark tasks as completed.
63+
Older heartbeat `tasks:` blocks migrate to independently scheduled cron jobs with `openclaw doctor --fix`.
6664

6765
Docs: [Heartbeat](/gateway/heartbeat), [Automation](/automation).
6866

‎docs/help/troubleshooting.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -330,8 +330,7 @@ flowchart TD
330330

331331
- `cron: scheduler disabled; jobs will not run automatically` → cron is disabled.
332332
- `heartbeat skipped` reason `quiet-hours` → outside configured active hours.
333-
- `heartbeat skipped` reason `empty-heartbeat-file` → `HEARTBEAT.md` exists but contains only blank, comment, header, fence, or empty-checklist scaffolding.
334-
- `heartbeat skipped` reason `no-tasks-due` → task mode is active but no task interval is due yet.
333+
- `heartbeat skipped` reason `empty-heartbeat-file` → heartbeat monitor scratch contains only blank, comment, header, fence, or empty-checklist scaffolding.
335334
- `heartbeat skipped` reason `alerts-disabled` → `showOk`, `showAlerts`, and `useIndicator` are all off.
336335
- `requests-in-flight` → main lane busy; heartbeat wake deferred.
337336
- `unknown accountId` → heartbeat delivery target account does not exist.

‎docs/reference/templates/HEARTBEAT.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ Shipped default content:
1616

1717
# Keep this file empty (or with only comments) to skip heartbeat API calls.
1818

19-
# Add tasks below when you want the agent to check something periodically.
19+
# Add a short checklist below when the heartbeat should inspect shared context.
2020
```
2121

22-
Add short tasks below the comment lines only when you want periodic checks. Keep it small: heartbeat runs read this file every tick (default every 30 minutes), so bloated instructions burn tokens on every wake.
22+
Add a short checklist below the comment lines only when one heartbeat turn should inspect the items together. Keep it small: heartbeat runs read this file every tick (default every 30 minutes), so bloated instructions burn tokens on every wake.
2323

24-
For due-only checks instead of a plain checklist, use a structured `tasks:` block with per-task `interval` and `prompt` fields; see [HEARTBEAT.md](/gateway/heartbeat#heartbeatmd-optional) for the format and behavior.
24+
For independently scheduled or due-only checks, create [cron jobs](/automation/cron-jobs). Heartbeat scratch no longer supports scheduler syntax. Run `openclaw doctor --fix` to convert older `tasks:` blocks.
2525

2626
## Related
2727

‎docs/start/openclaw.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ Example:
168168
## Heartbeats (proactive mode)
169169

170170
By default, OpenClaw runs a heartbeat every 30 minutes with the prompt:
171-
`Follow the heartbeat monitor scratch context when provided. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`
171+
`Follow the heartbeat monitor scratch context when provided. Recurring tasks are cron jobs; create or change their schedules with cron tools or the openclaw cron CLI, not heartbeat scratch. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`
172172
Set `agents.defaults.heartbeat.every: "0m"` to disable. Heartbeat checklists live in the monitor's cron scratch (see [Heartbeat](/gateway/heartbeat)); `openclaw doctor --fix` migrates a legacy workspace `HEARTBEAT.md` into it.
173173

174174
- If the monitor 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.

0 commit comments

Comments
 (0)