Skip to content

Commit 4e9ae9f

Browse files
authored
feat(cron): system-owned heartbeat monitor jobs replace the dedicated interval scheduler (#112585)
* feat(cron): system-owned heartbeat monitor jobs replace the interval scheduler - new internal cron payload kind {kind:"heartbeat"}: execution pokes requestHeartbeat({source:"interval"}); reported in the protocol job schema, not accepted from client create/patch - gateway converges one declaration-keyed monitor job per heartbeat-enabled agent (schedule every+deterministic phase anchor) at startup and on config reload; removes monitors for unconfigured agents - heartbeat runner loses its interval setTimeout machinery; nextDueMs stays as the cooldown gate, event wakes unchanged * test(cron): heartbeat monitor regressions; docs for cron-owned cadence - converge/prune/failure-containment tests for heartbeat monitor jobs - heartbeat payload run fires an interval wake, no system event - scheduler tests converted from timer self-fire to wake-queue pokes; timer-mechanics-only tests deleted with the timer - persisted-shape accepts the heartbeat payload kind - docs: heartbeat cadence ownership + system payload kind * fix(cron): heartbeat monitor review round 1 - targeted cron-monitor interval ticks use the full per-agent path so due-commitment sessions still deliver - cron-disabled gateways keep a local fallback interval timer (shipped cron.enabled=false contract; removed when heartbeat config folds into cron in #110950) - heartbeat job reconciliations serialize with latest-wins epochs and a bounded 30s retry after a failed convergence pass * fix(cron): chain clamped fallback heartbeat timers past the setTimeout cap * fix(cron): heartbeat monitor review round 3 - targeted monitor redirect skips wakes carrying heartbeat overrides and surfaces the per-agent terminal skip reason instead of not-due - cron-disabled fallback timer re-arms with a 1s floor after each firing so a dropped wake cannot end the chain - heartbeat payloads are system-owned at the service boundary: add requires the gateway opt-in, patches to the kind are rejected * fix(cron): heartbeat monitor review round 4 — full ownership enforcement - prune only jobs proven to be monitors (prefix AND heartbeat payload) - existing monitors reject every update patch; declarative upserts on the monitor key require the gateway opt-in even with a different payload * fix(cron): complete heartbeat monitor ownership boundary - converge scopes declarative matching to real monitors so a colliding user job with the same key is never adopted or overwritten - monitor removal requires the gateway systemOwned opt-in; ad-hoc API/CLI deletion is rejected, reconciliation cleanup still prunes * docs(cron): record intentional enrollment-snapshot semantics for monitor ticks * fix(cron): repair heartbeat monitor CI gates
1 parent 7cf6bd5 commit 4e9ae9f

28 files changed

Lines changed: 1003 additions & 511 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,8 @@ 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.
170+
169171
### Agent-turn options
170172

171173
<ParamField path="--message" type="string" required>

‎docs/gateway/heartbeat.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ 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.
19+
1820
Troubleshooting: [Scheduled Tasks](/automation/cron-jobs#troubleshooting)
1921

2022
## Quick start (beginner)

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,15 @@ const CronPayloadSchema = Type.Union([
286286
}),
287287
]);
288288

289+
/**
290+
* Reported payloads add the system-owned heartbeat monitor kind; it is
291+
* gateway-converged only, so create/patch schemas intentionally omit it.
292+
*/
293+
const CronReportedPayloadSchema = Type.Union([
294+
...CronPayloadSchema.anyOf,
295+
closedObject({ kind: Type.Literal("heartbeat") }),
296+
]);
297+
289298
/** Partial cron payload for job updates. */
290299
const CronPayloadPatchSchema = Type.Union([
291300
closedObject({
@@ -520,7 +529,7 @@ export const CronJobSchema = closedObject({
520529
trigger: Type.Optional(CronTriggerSchema),
521530
sessionTarget: CronSessionTargetSchema,
522531
wakeMode: CronWakeModeSchema,
523-
payload: CronPayloadSchema,
532+
payload: CronReportedPayloadSchema,
524533
delivery: Type.Optional(CronDeliverySchema),
525534
failureAlert: Type.Optional(Type.Union([Type.Literal(false), CronFailureAlertSchema])),
526535
state: CronJobStateSchema,

‎src/cron/normalize.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ export function normalizeCronJobInput(
488488
const kind = typeof next.payload.kind === "string" ? next.payload.kind : "";
489489
// Keep create-time defaults explicit: system events join main, while agent
490490
// turns isolate by default to avoid unbounded token accumulation.
491-
if (kind === "systemEvent") {
491+
if (kind === "systemEvent" || kind === "heartbeat") {
492492
next.sessionTarget = "main";
493493
} else if (kind === "agentTurn" || kind === "command" || kind === "script") {
494494
next.sessionTarget = "isolated";

‎src/cron/persisted-shape.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ export function getInvalidPersistedCronJobReason(
118118
payloadKind !== "systemEvent" &&
119119
payloadKind !== "agentTurn" &&
120120
payloadKind !== "command" &&
121-
payloadKind !== "script"
121+
payloadKind !== "script" &&
122+
payloadKind !== "heartbeat"
122123
) {
123124
return "invalid-payload";
124125
}

‎src/cron/service-contract.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export interface CronServiceContract {
4747
patch: CronUpdateInput,
4848
precondition: CronUpdatePrecondition,
4949
): Promise<CronUpdateResult>;
50-
remove(id: string): Promise<CronRemoveResult>;
50+
remove(id: string, opts?: { systemOwned?: boolean }): Promise<CronRemoveResult>;
5151
run(id: string, mode?: CronRunMode, opts?: CronServiceRunOptions): Promise<CronServiceRunResult>;
5252
enqueueRun(id: string, mode?: CronRunMode): Promise<CronServiceRunResult>;
5353
getJob(id: string): CronJob | undefined;
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// The system heartbeat monitor payload replaces the dedicated interval
2+
// scheduler: firing it must only poke the heartbeat wake queue.
3+
import { describe, expect, it } from "vitest";
4+
import {
5+
createCronStoreHarness,
6+
createNoopLogger,
7+
createStartedCronServiceWithFinishedBarrier,
8+
installCronTestHooks,
9+
} from "./service.test-harness.js";
10+
11+
const noopLogger = createNoopLogger();
12+
const { makeStorePath } = createCronStoreHarness();
13+
installCronTestHooks({ logger: noopLogger });
14+
15+
describe("heartbeat payload execution", () => {
16+
it("fires as an interval heartbeat wake without enqueuing a system event", async () => {
17+
const { storePath, cleanup } = await makeStorePath();
18+
const { cron, enqueueSystemEvent, requestHeartbeat } =
19+
createStartedCronServiceWithFinishedBarrier({ storePath, logger: noopLogger });
20+
try {
21+
await cron.start();
22+
const added = await cron.add(
23+
{
24+
declarationKey: "heartbeat:main",
25+
name: "heartbeat-main",
26+
agentId: "main",
27+
enabled: true,
28+
schedule: { kind: "every", everyMs: 60_000 },
29+
payload: { kind: "heartbeat" },
30+
sessionTarget: "main",
31+
wakeMode: "next-heartbeat",
32+
},
33+
{ enabledExplicit: true, systemOwned: true },
34+
);
35+
const job = "job" in added ? added.job : added;
36+
// System ownership boundary: no caller may create or patch to the
37+
// heartbeat payload without the gateway's opt-in.
38+
await expect(
39+
cron.add({
40+
name: "rogue",
41+
enabled: true,
42+
schedule: { kind: "every", everyMs: 60_000 },
43+
payload: { kind: "heartbeat" },
44+
sessionTarget: "main",
45+
wakeMode: "next-heartbeat",
46+
}),
47+
).rejects.toThrow(/system-owned/);
48+
await expect(cron.update(job.id, { payload: { kind: "heartbeat" } })).rejects.toThrow(
49+
/system-owned/,
50+
);
51+
// Existing monitors reject every patch, not just payload-kind edits.
52+
await expect(cron.update(job.id, { enabled: false })).rejects.toThrow(/system-owned/);
53+
// Ad-hoc deletion is rejected too; only reconciliation cleanup removes.
54+
await expect(cron.remove(job.id)).rejects.toThrow(/system-owned/);
55+
// A declarative upsert on the monitor's key cannot repurpose it either.
56+
await expect(
57+
cron.add({
58+
declarationKey: "heartbeat:main",
59+
name: "rogue-upsert",
60+
enabled: true,
61+
schedule: { kind: "every", everyMs: 60_000 },
62+
payload: { kind: "systemEvent", text: "hijack" },
63+
sessionTarget: "main",
64+
wakeMode: "next-heartbeat",
65+
}),
66+
).rejects.toThrow(/system-owned/);
67+
const result = await cron.run(job.id, "force");
68+
expect(result.ok).toBe(true);
69+
expect(requestHeartbeat).toHaveBeenCalledWith(
70+
expect.objectContaining({ source: "interval", intent: "scheduled", agentId: "main" }),
71+
);
72+
// The monitor never fabricates a system event; the wake is the whole run.
73+
expect(enqueueSystemEvent).not.toHaveBeenCalled();
74+
} finally {
75+
cron.stop();
76+
await cleanup();
77+
}
78+
});
79+
});

‎src/cron/service.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ export class CronService implements CronServiceContract {
117117
return await ops.updateWithPrecondition(this.state, id, patch, precondition);
118118
}
119119

120-
async remove(id: string) {
121-
return await ops.remove(this.state, id);
120+
async remove(id: string, opts?: { systemOwned?: boolean }) {
121+
return await ops.remove(this.state, id, opts);
122122
}
123123

124124
async removeAgentJobsTransactional<T>(agentId: string, commit: () => Promise<T>): Promise<T> {

‎src/cron/service/jobs.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,8 @@ export function assertSupportedJobSpec(
334334
if (
335335
job.sessionTarget === "main" &&
336336
job.payload.kind !== "systemEvent" &&
337-
job.payload.kind !== "script"
337+
job.payload.kind !== "script" &&
338+
job.payload.kind !== "heartbeat"
338339
) {
339340
throw new Error('main cron jobs require payload.kind="systemEvent" or "script"');
340341
}

‎src/cron/service/ops.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,12 @@ function declarativeFields(job: CronJob, includeEnabled: boolean) {
728728
export async function add(state: CronServiceState, input: CronJobCreate, opts?: CronAddOptions) {
729729
return await locked(state, async () => {
730730
warnIfDisabled(state, "add");
731+
// Heartbeat monitors are gateway-converged system jobs; without this
732+
// boundary any internal caller could upsert the declaration key and
733+
// hijack the monitor despite the transport schemas excluding the kind.
734+
if (input.payload?.kind === "heartbeat" && opts?.systemOwned !== true) {
735+
throw new Error("heartbeat payloads are system-owned; jobs cannot be created with them");
736+
}
731737
await ensureLoaded(state, { skipRecompute: true });
732738
const agentId = resolveEffectiveJobAgentId(input, resolveCurrentDefaultAgentId(state));
733739
if (state.deps.isAgentAvailable?.(agentId) === false) {
@@ -753,6 +759,13 @@ export async function add(state: CronServiceState, input: CronJobCreate, opts?:
753759
const existing = matches[0];
754760

755761
if (existing) {
762+
// A declarative upsert may not repurpose an existing heartbeat monitor
763+
// with a different payload; only the gateway's own convergence touches it.
764+
if (existing.payload.kind === "heartbeat" && opts?.systemOwned !== true) {
765+
throw new Error(
766+
"heartbeat monitor jobs are system-owned; edit agents.*.heartbeat config instead",
767+
);
768+
}
756769
const now = state.deps.nowMs();
757770
const nextJob = structuredClone(existing);
758771
applyDeclarativeJobSpec(nextJob, normalizedInput, {
@@ -832,9 +845,23 @@ async function updateLoadedJob(params: {
832845
}) {
833846
const { state, id, patch, precondition } = params;
834847
warnIfDisabled(state, "update");
848+
// Mirrors the add-time boundary: no caller may patch a job into (or edit)
849+
// the system-owned heartbeat payload; the gateway converges via add only.
850+
if (patch.payload?.kind === "heartbeat") {
851+
throw new Error("heartbeat payloads are system-owned; jobs cannot be patched to them");
852+
}
835853
await ensureLoaded(state, { skipRecompute: true });
836854
const snapshot = snapshotStoreForRollback(state);
837855
const job = findJobOrThrow(state, id);
856+
// Existing monitors are config-driven: any patch (disable, reschedule,
857+
// repurpose) would silently diverge from agents.*.heartbeat until the next
858+
// reconcile, so updates are rejected outright. Removal stays allowed — a
859+
// removed monitor self-heals at the next convergence.
860+
if (job.payload.kind === "heartbeat") {
861+
throw new Error(
862+
"heartbeat monitor jobs are system-owned; edit agents.*.heartbeat config instead",
863+
);
864+
}
838865
const now = state.deps.nowMs();
839866
await precondition?.(structuredClone(job), now);
840867
const nextJob = structuredClone(job);
@@ -880,7 +907,11 @@ export async function updateWithPrecondition(
880907
}
881908

882909
/** Removes a cron job by id and re-arms the timer when the in-memory store changes. */
883-
export async function remove(state: CronServiceState, id: string) {
910+
export async function remove(
911+
state: CronServiceState,
912+
id: string,
913+
opts?: { systemOwned?: boolean },
914+
) {
884915
return await locked(state, async () => {
885916
warnIfDisabled(state, "remove");
886917
await ensureLoaded(state, { skipRecompute: true });
@@ -890,6 +921,14 @@ export async function remove(state: CronServiceState, id: string) {
890921
}
891922
const snapshot = snapshotStoreForRollback(state);
892923
const removedJob = state.store.jobs.find((j) => j.id === id);
924+
// Config is the monitor's source of truth: ad-hoc deletion would disable
925+
// heartbeats until an unrelated reload, so only gateway reconciliation
926+
// (stale-monitor cleanup) may remove one.
927+
if (removedJob?.payload.kind === "heartbeat" && opts?.systemOwned !== true) {
928+
throw new Error(
929+
"heartbeat monitor jobs are system-owned; edit agents.*.heartbeat config instead",
930+
);
931+
}
893932
state.store.jobs = state.store.jobs.filter((j) => j.id !== id);
894933
const removed = (state.store.jobs.length ?? 0) !== before;
895934

0 commit comments

Comments
 (0)