Skip to content

Commit 08d0952

Browse files
authored
feat(cron): auto-disable repeatedly failing recurring jobs (#118113)
Refs #118089 Release note: recurring automations now auto-disable after 10 consecutive run failures, record the reason, and notify their owning agent.
1 parent 2e0492b commit 08d0952

23 files changed

Lines changed: 899 additions & 46 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,8 @@ Failure notifications follow a separate destination path:
347347

348348
Chat failure notifications include the run start time in the agent's configured user timezone. Webhook message text stays stable; integrations can read the same instant from the structured `runAtMs` field.
349349

350+
Failure alerts are opt-in, but the scheduler also provides an unconditional safety backstop. A time-based recurring job is auto-disabled after 10 consecutive execution failures; a successful run resets that streak. Repeated schedule-computation failures auto-disable after 3 errors. The job records `state.autoDisabled.reason` as `consecutive-failures` or `schedule-errors`, and the owning agent receives a notification with the last error and recovery command. After fixing the cause, run `openclaw automations enable <jobId>`; enabling clears the recorded reason and failure streaks. Because disabled jobs are hidden by the default list, use `openclaw automations list --all` to inspect them.
351+
350352
### Output language
351353

352354
Automation jobs do not infer a reply language from channel, locale, or previous messages. Put the language rule in the scheduled message or template:

‎packages/gateway-protocol/src/cron-validators.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Value } from "typebox/value";
12
// Gateway Protocol tests cover cron validators behavior.
23
import { describe, expect, it } from "vitest";
34
import {
@@ -9,6 +10,7 @@ import {
910
validateCronRunsParams,
1011
validateCronUpdateParams,
1112
} from "./index.js";
13+
import { CronJobSchema } from "./schema/cron.js";
1214

1315
/**
1416
* Cron validator regressions for public scheduler RPC payloads.
@@ -45,6 +47,26 @@ describe("cron protocol validators", () => {
4547
expectCases(validateCronAddParams, true, [minimalAddParams]);
4648
});
4749

50+
it("reports auto-disable state without accepting it in writable patches", () => {
51+
const job = {
52+
...minimalAddParams,
53+
id: "job-1",
54+
enabled: false,
55+
createdAtMs: 1,
56+
updatedAtMs: 2,
57+
state: {
58+
consecutiveErrors: 10,
59+
autoDisabled: {
60+
reason: "consecutive-failures",
61+
atMs: 2,
62+
consecutiveErrors: 10,
63+
},
64+
},
65+
};
66+
expect(Value.Check(CronJobSchema, job)).toBe(true);
67+
expect(validateCronUpdateParams(update({ state: job.state }))).toBe(false);
68+
});
69+
4870
it("rejects client-authored scheduled authority provenance", () => {
4971
const scheduledToolPolicy = { version: 1, mode: "trusted" } as const;
5072
expectCases(validateCronAddParams, false, [add({ scheduledToolPolicy })]);

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,12 @@ const CronFailureNotificationDeliverySchema = closedObject({
430430
error: Type.Optional(Type.String()),
431431
});
432432

433+
const CronAutoDisabledSchema = closedObject({
434+
reason: Type.Union([Type.Literal("consecutive-failures"), Type.Literal("schedule-errors")]),
435+
atMs: Type.Integer({ minimum: 0 }),
436+
consecutiveErrors: Type.Integer({ minimum: 1 }),
437+
});
438+
433439
/** Scheduler-maintained state for the latest run/delivery outcome. */
434440
export const CronJobStateSchema = closedObject({
435441
nextRunAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
@@ -444,6 +450,8 @@ export const CronJobStateSchema = closedObject({
444450
lastErrorReason: Type.Optional(CronFailoverReasonSchema),
445451
lastDurationMs: Type.Optional(Type.Integer({ minimum: 0 })),
446452
consecutiveErrors: Type.Optional(Type.Integer({ minimum: 0 })),
453+
// Report-only scheduler ownership fact; callers cannot patch this field.
454+
autoDisabled: Type.Optional(CronAutoDisabledSchema),
447455
consecutiveSkipped: Type.Optional(Type.Integer({ minimum: 0 })),
448456
lastDelivered: Type.Optional(Type.Boolean()),
449457
lastDeliveryStatus: Type.Optional(CronDeliveryStatusSchema),

‎src/cli/cron-cli/shared.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,51 @@ describe("printCronList", () => {
305305
expect(singleLine).not.toContain("(1x)");
306306
});
307307

308+
it("shows why the scheduler auto-disabled a job without changing JSON status", () => {
309+
const runFailures = createBaseJob({
310+
id: "auto-disabled-runs",
311+
name: "Auto-disabled runs",
312+
enabled: false,
313+
state: {
314+
consecutiveErrors: 10,
315+
autoDisabled: {
316+
reason: "consecutive-failures",
317+
atMs: Date.now(),
318+
consecutiveErrors: 10,
319+
},
320+
},
321+
});
322+
const scheduleErrors = createBaseJob({
323+
id: "auto-disabled-schedule",
324+
name: "Auto-disabled schedule",
325+
enabled: false,
326+
state: {
327+
scheduleErrorCount: 3,
328+
autoDisabled: {
329+
reason: "schedule-errors",
330+
atMs: Date.now(),
331+
consecutiveErrors: 3,
332+
},
333+
},
334+
});
335+
336+
const list = createRuntimeLogCapture();
337+
printCronList([runFailures, scheduleErrors], list.runtime);
338+
expectLogsToInclude(list.logs, "disabled (10x)");
339+
expectLogsToInclude(list.logs, "disabled (schedule)");
340+
341+
const show = createRuntimeLogCapture();
342+
printCronShow(runFailures, show.runtime);
343+
expectLogsToInclude(show.logs, "status: disabled (10x)");
344+
345+
expect(enrichCronJsonWithStatus(runFailures)).toMatchObject({
346+
status: "disabled",
347+
state: {
348+
autoDisabled: { reason: "consecutive-failures", consecutiveErrors: 10 },
349+
},
350+
});
351+
});
352+
308353
it("caps the failure count so the status column never overflows", () => {
309354
const { logs, runtime } = createRuntimeLogCapture();
310355
printCronList(

‎src/cli/cron-cli/shared.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,7 @@ function computeStatus(job: CronJob): string {
174174
}
175175

176176
// Human-facing decoration only: enrichCronJsonWithStatus() emits computeStatus()
177-
// verbatim as the --json `status` field, so the failure count must stay out of it.
178-
// consecutiveErrors resets to 0 on the next successful run, so the count is live.
177+
// verbatim as the --json `status` field, so failure and disable detail stays out of it.
179178
function decorateStatusWithFailures(status: string, consecutiveErrors: number | undefined): string {
180179
const failures = consecutiveErrors ?? 0;
181180
if (status !== "error" || failures <= 1) {
@@ -188,6 +187,11 @@ function decorateStatusWithFailures(status: string, consecutiveErrors: number |
188187

189188
function formatCronStatusForDisplay(job: CronJob): string {
190189
const state = job.state ?? {};
190+
if (computeStatus(job) === "disabled" && state.autoDisabled) {
191+
return state.autoDisabled.reason === "schedule-errors"
192+
? "disabled (schedule)"
193+
: `disabled (${state.autoDisabled.consecutiveErrors}x)`;
194+
}
191195
return decorateStatusWithFailures(computeStatus(job), state.consecutiveErrors);
192196
}
193197

@@ -323,7 +327,7 @@ const CRON_NAME_PAD = 24;
323327
const CRON_SCHEDULE_PAD = 32;
324328
const CRON_NEXT_PAD = 10;
325329
const CRON_LAST_PAD = 10;
326-
const CRON_STATUS_PAD = 12;
330+
const CRON_STATUS_PAD = 19;
327331
const CRON_TARGET_PAD = 9;
328332
const CRON_DELIVERY_PAD = 64;
329333
const CRON_AGENT_PAD = 10;

‎src/commands/doctor/cron/index.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,58 @@ describe("maybeRepairLegacyCronStore", () => {
732732

733733
expectNoNoteContaining("runs in a row", "Cron");
734734
});
735+
736+
it("lists auto-disabled jobs with their recorded reasons and recovery commands", async () => {
737+
const storePath = await makeTempStorePath();
738+
await writeCurrentCronStore(storePath, [
739+
createCurrentCronJob({
740+
id: "run-failure-job",
741+
name: "Run failure job",
742+
enabled: false,
743+
state: {
744+
consecutiveErrors: 10,
745+
autoDisabled: {
746+
reason: "consecutive-failures",
747+
atMs: Date.parse("2026-08-01T10:00:00.000Z"),
748+
consecutiveErrors: 10,
749+
},
750+
},
751+
}),
752+
createCurrentCronJob({
753+
id: "schedule-error-job",
754+
name: "Schedule error job",
755+
enabled: false,
756+
state: {
757+
scheduleErrorCount: 3,
758+
autoDisabled: {
759+
reason: "schedule-errors",
760+
atMs: Date.parse("2026-08-01T11:00:00.000Z"),
761+
consecutiveErrors: 3,
762+
},
763+
},
764+
}),
765+
createCurrentCronJob({
766+
id: "disabled-one-shot",
767+
enabled: false,
768+
state: { lastRunStatus: "error", consecutiveErrors: 9 },
769+
}),
770+
]);
771+
772+
await maybeRepairLegacyCronStore({
773+
cfg: createCronConfig(storePath),
774+
options: {},
775+
prompter: makePrompter(true),
776+
});
777+
778+
expectNoteContaining("2 automations are auto-disabled", "Cron");
779+
expectNoteContaining("Run failure job (run-failure-job)", "Cron");
780+
expectNoteContaining("recorded reason `consecutive-failures` after 10", "Cron");
781+
expectNoteContaining("openclaw automations enable run-failure-job", "Cron");
782+
expectNoteContaining("Schedule error job (schedule-error-job)", "Cron");
783+
expectNoteContaining("recorded reason `schedule-errors` after 3", "Cron");
784+
expectNoteContaining("openclaw automations enable schedule-error-job", "Cron");
785+
expectNoNoteContaining("disabled-one-shot", "Cron");
786+
});
735787
});
736788

737789
it("repairs legacy cron store fields and migrates notify fallback to webhook delivery", async () => {

‎src/commands/doctor/cron/index.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Doctor cron repair orchestration for legacy stores, run logs, payloads, and warnings.
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import { note } from "../../../../packages/terminal-core/src/note.js";
34
import { formatCliCommand } from "../../../cli/command-format.js";
45
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
@@ -85,6 +86,44 @@ function countChronicallyFailingCronJobs(jobs: Array<Record<string, unknown>>):
8586
}).length;
8687
}
8788

89+
type AutoDisabledCronJob = {
90+
id: string;
91+
name: string;
92+
reason: "consecutive-failures" | "schedule-errors";
93+
consecutiveErrors: number;
94+
};
95+
96+
function collectAutoDisabledCronJobs(jobs: Array<Record<string, unknown>>): AutoDisabledCronJob[] {
97+
const autoDisabledJobs: AutoDisabledCronJob[] = [];
98+
for (const job of jobs) {
99+
if (job.enabled !== false || typeof job.id !== "string") {
100+
continue;
101+
}
102+
const state = job.state;
103+
if (!isRecord(state)) {
104+
continue;
105+
}
106+
const autoDisabled = state.autoDisabled;
107+
if (!isRecord(autoDisabled)) {
108+
continue;
109+
}
110+
if (
111+
(autoDisabled.reason !== "consecutive-failures" &&
112+
autoDisabled.reason !== "schedule-errors") ||
113+
typeof autoDisabled.consecutiveErrors !== "number"
114+
) {
115+
continue;
116+
}
117+
autoDisabledJobs.push({
118+
id: job.id,
119+
name: typeof job.name === "string" && job.name.trim() ? job.name.trim() : job.id,
120+
reason: autoDisabled.reason,
121+
consecutiveErrors: autoDisabled.consecutiveErrors,
122+
});
123+
}
124+
return autoDisabledJobs;
125+
}
126+
88127
const LEGACY_CRON_STORE_CHECK_ID = "core/doctor/legacy-cron-store";
89128

90129
function legacyCronStoreFinding(params: {
@@ -408,6 +447,20 @@ export async function maybeRepairLegacyCronStore(params: {
408447
);
409448
}
410449

450+
const autoDisabledJobs = collectAutoDisabledCronJobs(rawJobs);
451+
if (autoDisabledJobs.length > 0) {
452+
note(
453+
[
454+
`${pluralize(autoDisabledJobs.length, "automation")} ${autoDisabledJobs.length === 1 ? "is" : "are"} auto-disabled after repeated failures.`,
455+
...autoDisabledJobs.map(
456+
(job) =>
457+
`- ${job.name} (${job.id}): recorded reason \`${job.reason}\` after ${job.consecutiveErrors} consecutive errors. Fix the cause, then re-enable with ${formatCliCommand(`openclaw automations enable ${job.id}`)}.`,
458+
),
459+
].join("\n"),
460+
"Cron",
461+
);
462+
}
463+
411464
const normalized = normalizeStoredCronJobs(rawJobs);
412465
const notifyCount = rawJobs.filter((job) => job.notify === true).length;
413466
const dreamingStaleCount = countStaleDreamingJobs(rawJobs);

‎src/cron/service/auto-disable.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/** Shared state and owner-notification policy for cron auto-disable transitions. */
2+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
3+
import { parseAgentSessionKey } from "../../routing/session-key.js";
4+
import type { CronJob, CronJobState } from "../types.js";
5+
import { normalizeOptionalAgentId } from "./normalize.js";
6+
import type { CronServiceState } from "./state.js";
7+
8+
type CronAutoDisableReason = NonNullable<CronJobState["autoDisabled"]>["reason"];
9+
10+
export type DeferredAutoDisableNotifications = Array<() => void>;
11+
12+
/**
13+
* Run failures get more room than schedule errors (10 vs. 3) because provider
14+
* and network errors are often transient, and restart-interrupted runs count too.
15+
*/
16+
const MAX_CONSECUTIVE_RUN_FAILURES = 10;
17+
18+
function autoDisableReasonLabel(reason: CronAutoDisableReason): string {
19+
return reason === "consecutive-failures" ? "run failures" : "schedule errors";
20+
}
21+
22+
/** Records one canonical auto-disable fact and queues its owning-agent notification. */
23+
export function autoDisableCronJob(params: {
24+
state: CronServiceState;
25+
job: CronJob;
26+
reason: CronAutoDisableReason;
27+
atMs: number;
28+
consecutiveErrors: number;
29+
error: unknown;
30+
deferredNotifications?: DeferredAutoDisableNotifications;
31+
}): boolean {
32+
const { state, job } = params;
33+
if (!job.enabled || job.state.autoDisabled) {
34+
return false;
35+
}
36+
37+
job.enabled = false;
38+
job.state.nextRunAtMs = undefined;
39+
job.state.autoDisabled = {
40+
reason: params.reason,
41+
atMs: params.atMs,
42+
consecutiveErrors: params.consecutiveErrors,
43+
};
44+
45+
const name = truncateUtf16Safe((job.name || job.id).replace(/\s+/g, " ").trim(), 120);
46+
const error = truncateUtf16Safe(String(params.error).trim() || "unknown reason", 200);
47+
const text = [
48+
`⚠️ Automation "${name}" (${job.id}) was auto-disabled after ${params.consecutiveErrors} consecutive ${autoDisableReasonLabel(params.reason)}.`,
49+
`Last error: ${error}`,
50+
`Fix the underlying cause, then run \`openclaw automations enable ${job.id}\` to re-enable it.`,
51+
].join("\n");
52+
const notify = () => {
53+
const agentId =
54+
normalizeOptionalAgentId(job.agentId) ??
55+
normalizeOptionalAgentId(parseAgentSessionKey(job.sessionKey)?.agentId) ??
56+
normalizeOptionalAgentId(state.deps.resolveDefaultAgentId?.()) ??
57+
normalizeOptionalAgentId(state.deps.defaultAgentId);
58+
const deliveryContext =
59+
agentId || job.sessionKey
60+
? state.deps.resolveOriginDeliveryContext?.({
61+
agentId,
62+
sessionKey: job.sessionKey,
63+
})
64+
: undefined;
65+
state.deps.enqueueSystemEvent(text, {
66+
agentId,
67+
sessionKey: job.sessionKey,
68+
contextKey: `cron:${job.id}:auto-disabled`,
69+
...(deliveryContext ? { deliveryContext } : {}),
70+
});
71+
state.deps.requestHeartbeat({
72+
source: "cron",
73+
intent: "event",
74+
reason: `cron:${job.id}:auto-disabled`,
75+
agentId,
76+
sessionKey: job.sessionKey,
77+
});
78+
};
79+
80+
if (params.deferredNotifications) {
81+
params.deferredNotifications.push(notify);
82+
} else {
83+
notify();
84+
}
85+
return true;
86+
}
87+
88+
/** Auto-disables only time-based recurring jobs once their run-error streak reaches the limit. */
89+
export function maybeAutoDisableCronJobAfterRunFailure(params: {
90+
state: CronServiceState;
91+
job: CronJob;
92+
atMs: number;
93+
error: unknown;
94+
deferredNotifications?: DeferredAutoDisableNotifications;
95+
}): boolean {
96+
const consecutiveErrors = params.job.state.consecutiveErrors ?? 0;
97+
if (
98+
(params.job.schedule.kind !== "cron" && params.job.schedule.kind !== "every") ||
99+
consecutiveErrors < MAX_CONSECUTIVE_RUN_FAILURES
100+
) {
101+
return false;
102+
}
103+
return autoDisableCronJob({
104+
...params,
105+
reason: "consecutive-failures",
106+
consecutiveErrors,
107+
});
108+
}

0 commit comments

Comments
 (0)