Skip to content

Commit 87d412d

Browse files
authored
fix(cron): keep scheduler state and quarantine in SQLite (#117071)
1 parent 727216b commit 87d412d

20 files changed

Lines changed: 873 additions & 550 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,6 @@ Use the latest-generation, best-tier model available from your provider for untr
739739
{
740740
cron: {
741741
enabled: true,
742-
store: "~/.openclaw/cron/jobs.json",
743742
triggers: {
744743
enabled: false,
745744
},
@@ -753,7 +752,7 @@ Use the latest-generation, best-tier model available from your provider for untr
753752
Webhook URLs must not include embedded username/password credentials; use
754753
`webhookToken` when the receiver supports bearer authentication.
755754

756-
`cron.store` is a logical store key and doctor migration path, not a live JSON file to hand-edit. Job data lives in SQLite; use the CLI or Gateway API for changes.
755+
Automation jobs, run history, and quarantined malformed jobs live in the shared SQLite state database. Use the CLI or Gateway API to change jobs; `cron.store` is retired.
757756

758757
Disable automations: `cron.enabled: false` or `OPENCLAW_SKIP_CRON=1`.
759758

@@ -768,7 +767,7 @@ Disable automations: `cron.enabled: false` or `OPENCLAW_SKIP_CRON=1`.
768767
`cron.sessionRetention` (default `24h`, `false` disables) prunes isolated run-session entries. Run history keeps the newest 2000 terminal rows per job; lost rows retain their 24-hour cleanup window.
769768
</Accordion>
770769
<Accordion title="Legacy store migration">
771-
On upgrade, run `openclaw doctor --fix` to import legacy `~/.openclaw/cron/jobs.json`, `jobs-state.json`, and `runs/*.jsonl` files into SQLite and rename them with a `.migrated` suffix. Malformed job rows are skipped from runtime and copied to `jobs-quarantine.json` for later repair or review.
770+
On upgrade, run `openclaw doctor --fix` to import historical `~/.openclaw/cron/jobs.json`, `jobs-state.json`, `jobs-quarantine.json`, and `runs/*.jsonl` files into SQLite and archive the originals with a `.migrated` suffix. Malformed job rows remain recoverable in SQLite while valid jobs keep running.
772771
</Accordion>
773772
</AccordionGroup>
774773

‎docs/cli/doctor.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ compare restored legacy artifacts with the SQLite rows before importing.
396396
- On Linux, doctor ignores inactive extra gateway-like systemd units and does not rewrite command/entrypoint metadata for a running systemd gateway service during repair. Stop the service first, or use `openclaw gateway install --force` to replace the active launcher.
397397
- `doctor --fix --non-interactive` reports missing or stale gateway service definitions but does not install or rewrite them outside update repair mode. Run `openclaw gateway install` for a missing service, or `openclaw gateway install --force` to replace the launcher.
398398
- State integrity checks detect orphan transcript files in the sessions directory. Archiving them as `.deleted.<timestamp>` requires interactive confirmation; `--fix`, `--yes`, and headless runs leave them in place.
399-
- Doctor scans `~/.openclaw/cron/jobs.json` (or `cron.store`) for legacy cron job shapes and rewrites them before importing canonical rows into SQLite.
399+
- Doctor scans historical `~/.openclaw/cron/jobs.json` stores and previously configured legacy store locations for old cron job shapes, imports jobs and quarantine records into SQLite, and archives the migrated JSON files.
400400
- Doctor reports cron jobs with an explicit `payload.model` override, including provider-namespace counts and mismatches against `agents.defaults.model`, so scheduled jobs that do not inherit the default model are visible during auth or billing investigations.
401401
- Doctor reports cron jobs still marked in-flight (`state.runningAtMs`), which can make `openclaw cron list` show them as `running`. This check is read-only: if no Gateway is currently executing a marked job, the next cron service startup records the interrupted run and clears the marker.
402402
- On Linux, doctor warns when the user's crontab still runs the unmaintained legacy `~/.openclaw/bin/ensure-whatsapp.sh`, which can misreport `Gateway inactive` when cron lacks the systemd user-bus environment.

‎docs/gateway/configuration-examples.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,6 @@ Save to `~/.openclaw/openclaw.json` and you can DM the bot from that number.
367367
// Cron jobs
368368
cron: {
369369
enabled: true,
370-
store: "~/.openclaw/cron/jobs.json",
371370
sessionRetention: "24h",
372371
},
373372

‎docs/gateway/doctor.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ That stages grounded durable candidates into the short-term dreaming store while
422422
- payload `provider` delivery aliases → explicit `delivery.channel`
423423
- legacy `notify: true` webhook fallback jobs → explicit webhook delivery from the retired raw `cron.webhook` value when valid; announce jobs keep their chat delivery and get `delivery.completionDestination`. Doctor then removes the old config key. Without a usable legacy webhook, the inert top-level `notify` marker is removed for no-target jobs (existing delivery, including announce, is preserved) since runtime delivery never reads it.
424424

425-
The Gateway also sanitizes malformed cron rows at load time so valid jobs keep running. Raw malformed rows are copied to `jobs-quarantine.json` next to the active store before removal from `jobs.json`; doctor reports quarantined rows so you can review or repair them manually.
425+
The Gateway also sanitizes malformed cron rows at load time so valid jobs keep running. Malformed rows are quarantined in the shared SQLite state database in the same transaction that removes them from active scheduling; doctor reports those records and imports any `jobs-quarantine.json` sidecars left by older releases.
426426

427427
Gateway startup normalizes the runtime projection and ignores the top-level `notify` marker, but leaves persisted cron state for doctor repair. Doctor removes inert markers for jobs with no migration target (`delivery.mode` none/absent, an unusable legacy webhook target, or existing announce/chat delivery), leaving existing delivery untouched, so repeated `doctor --fix` runs no longer re-warn about the same job.
428428

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

Lines changed: 124 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
77
import type { OpenClawConfig } from "../../../config/config.js";
88
import {
99
loadCronJobsStoreWithConfigJobs,
10-
loadCronQuarantineFile,
10+
loadCronQuarantinedJobs,
1111
loadCronStore,
12-
resolveCronQuarantinePath,
12+
saveCronQuarantinedJobs,
1313
saveCronStore,
1414
} from "../../../cron/store.js";
1515
import { cronStoreKey } from "../../../cron/store/key.js";
@@ -39,6 +39,10 @@ async function makeTempStorePath() {
3939
return path.join(tempRoot, "cron", "jobs.json");
4040
}
4141

42+
function resolveLegacyCronQuarantinePath(storePath: string): string {
43+
return storePath.replace(/\.json$/, "-quarantine.json");
44+
}
45+
4246
afterEach(async () => {
4347
vi.unstubAllEnvs();
4448
noteMock.mockClear();
@@ -260,26 +264,17 @@ describe("collectLegacyCronStoreHealthFindings", () => {
260264
it("reports quarantined cron rows while leaving the active store untouched", async () => {
261265
const storePath = await makeTempStorePath();
262266
await writeCurrentCronStore(storePath, []);
263-
await fs.mkdir(path.dirname(resolveCronQuarantinePath(storePath)), { recursive: true });
264-
await fs.writeFile(
265-
resolveCronQuarantinePath(storePath),
266-
JSON.stringify(
267+
saveCronQuarantinedJobs({
268+
storePath,
269+
nowMs: Date.parse("2026-05-29T09:00:00.000Z"),
270+
entries: [
267271
{
268-
version: 1,
269-
jobs: [
270-
{
271-
quarantinedAtMs: Date.parse("2026-05-29T09:00:00.000Z"),
272-
sourceIndex: 1,
273-
reason: "missing-schedule",
274-
job: { id: "bad-cron", name: "Bad cron" },
275-
},
276-
],
272+
sourceIndex: 1,
273+
reason: "missing-schedule",
274+
job: { id: "bad-cron", name: "Bad cron" },
277275
},
278-
null,
279-
2,
280-
),
281-
"utf-8",
282-
);
276+
],
277+
});
283278

284279
const findings = await collectLegacyCronStoreHealthFindings({
285280
cfg: createCronConfig(storePath),
@@ -288,7 +283,7 @@ describe("collectLegacyCronStoreHealthFindings", () => {
288283
expect(findings).toEqual([
289284
expect.objectContaining({
290285
checkId: "core/doctor/legacy-cron-store",
291-
path: resolveCronQuarantinePath(storePath),
286+
path: resolveOpenClawStateSqlitePath(),
292287
requirement: "quarantined-cron-rows",
293288
}),
294289
]);
@@ -318,31 +313,50 @@ describe("collectLegacyCronStoreHealthFindings", () => {
318313
collectLegacyCronStoreHealthFindings({ cfg: createCronConfig(storePath) }),
319314
).resolves.toEqual([]);
320315
});
316+
317+
it("reports a legacy quarantine sidecar without creating or modifying a SQLite database", async () => {
318+
const storePath = await makeTempStorePath();
319+
vi.stubEnv("OPENCLAW_STATE_DIR", path.dirname(path.dirname(storePath)));
320+
const quarantinePath = resolveLegacyCronQuarantinePath(storePath);
321+
await fs.mkdir(path.dirname(quarantinePath), { recursive: true });
322+
const historicalBytes = JSON.stringify({
323+
version: 1,
324+
jobs: [{ quarantinedAtMs: 123, sourceIndex: 0, reason: "invalid-schedule", raw: null }],
325+
});
326+
await fs.writeFile(quarantinePath, historicalBytes, "utf-8");
327+
328+
const findings = await collectLegacyCronStoreHealthFindings({
329+
cfg: createCronConfig(storePath),
330+
});
331+
332+
expect(findings).toEqual([
333+
expect.objectContaining({
334+
path: quarantinePath,
335+
requirement: "legacy-cron-quarantine",
336+
}),
337+
]);
338+
await expect(fs.readFile(quarantinePath, "utf-8")).resolves.toBe(historicalBytes);
339+
await expect(fs.stat(resolveOpenClawStateSqlitePath())).rejects.toMatchObject({
340+
code: "ENOENT",
341+
});
342+
});
321343
});
322344

323345
describe("maybeRepairLegacyCronStore", () => {
324346
it("reports quarantined cron rows even when the active store is already sanitized", async () => {
325347
const storePath = await makeTempStorePath();
326-
await writeCronStore(storePath, []);
327-
await fs.writeFile(
328-
resolveCronQuarantinePath(storePath),
329-
JSON.stringify(
348+
await writeCurrentCronStore(storePath, []);
349+
saveCronQuarantinedJobs({
350+
storePath,
351+
nowMs: Date.parse("2026-05-29T09:00:00.000Z"),
352+
entries: [
330353
{
331-
version: 1,
332-
jobs: [
333-
{
334-
quarantinedAtMs: Date.parse("2026-05-29T09:00:00.000Z"),
335-
sourceIndex: 1,
336-
reason: "missing-schedule",
337-
job: { id: "bad-cron", name: "Bad cron" },
338-
},
339-
],
354+
sourceIndex: 1,
355+
reason: "missing-schedule",
356+
job: { id: "bad-cron", name: "Bad cron" },
340357
},
341-
null,
342-
2,
343-
),
344-
"utf-8",
345-
);
358+
],
359+
});
346360

347361
await maybeRepairLegacyCronStore({
348362
cfg: createCronConfig(storePath),
@@ -354,6 +368,74 @@ describe("maybeRepairLegacyCronStore", () => {
354368
expectNoteContaining("1 row was removed from the active cron store", "Cron");
355369
});
356370

371+
it("imports and archives standalone legacy quarantine files without losing recovery fields", async () => {
372+
const storePath = await makeTempStorePath();
373+
await writeCurrentCronStore(storePath, []);
374+
const quarantinePath = resolveLegacyCronQuarantinePath(storePath);
375+
await fs.mkdir(path.dirname(quarantinePath), { recursive: true });
376+
const historicalJob = {
377+
quarantinedAtMs: Date.parse("2026-05-29T09:00:00.000Z"),
378+
sourceIndex: 7,
379+
reason: "invalid-schedule",
380+
job: { id: "historical-bad-cron", name: "Historical bad cron" },
381+
raw: { observed: true },
382+
state: { nextRunAtMs: 456 },
383+
updatedAtMs: 789,
384+
scheduleIdentity: "historical-schedule",
385+
};
386+
await fs.writeFile(quarantinePath, JSON.stringify({ version: 1, jobs: [historicalJob] }));
387+
const prompter = makePrompter(true);
388+
389+
await maybeRepairLegacyCronStore({
390+
cfg: createCronConfig(storePath),
391+
options: {},
392+
prompter,
393+
});
394+
395+
expect(loadCronQuarantinedJobs(storePath)).toEqual([historicalJob]);
396+
await expect(fs.stat(quarantinePath)).rejects.toMatchObject({ code: "ENOENT" });
397+
await expect(fs.stat(`${quarantinePath}.migrated`)).resolves.toBeDefined();
398+
expect(prompter.confirm).toHaveBeenCalledTimes(1);
399+
expectNoteContaining("Cron quarantine migrated to SQLite", "Doctor changes");
400+
});
401+
402+
it("deduplicates migrated quarantine records when sidecar archival must be retried", async () => {
403+
const storePath = await makeTempStorePath();
404+
await writeCurrentCronStore(storePath, []);
405+
const quarantinePath = resolveLegacyCronQuarantinePath(storePath);
406+
await fs.mkdir(path.dirname(quarantinePath), { recursive: true });
407+
const historicalJob = {
408+
quarantinedAtMs: 123,
409+
sourceIndex: 0,
410+
reason: "invalid-schedule",
411+
job: { id: "retry-bad-cron" },
412+
};
413+
await fs.writeFile(quarantinePath, JSON.stringify({ version: 1, jobs: [historicalJob] }));
414+
const rename = vi
415+
.spyOn(fs, "rename")
416+
.mockRejectedValueOnce(createFsError("EACCES", "archive unavailable"));
417+
418+
await maybeRepairLegacyCronStore({
419+
cfg: createCronConfig(storePath),
420+
options: {},
421+
prompter: makePrompter(true),
422+
});
423+
424+
expect(loadCronQuarantinedJobs(storePath)).toEqual([historicalJob]);
425+
await expect(fs.stat(quarantinePath)).resolves.toBeDefined();
426+
expectNoteContaining("could not archive the legacy cron file", "Doctor warnings");
427+
rename.mockRestore();
428+
429+
await maybeRepairLegacyCronStore({
430+
cfg: createCronConfig(storePath),
431+
options: {},
432+
prompter: makePrompter(true),
433+
});
434+
435+
expect(loadCronQuarantinedJobs(storePath)).toEqual([historicalJob]);
436+
await expect(fs.stat(`${quarantinePath}.migrated`)).resolves.toBeDefined();
437+
});
438+
357439
it("surfaces cron payload model overrides without rewriting current jobs", async () => {
358440
const storePath = await makeTempStorePath();
359441
await writeCurrentCronStore(storePath, [
@@ -1911,9 +1993,9 @@ describe("maybeRepairLegacyCronStore", () => {
19111993
});
19121994

19131995
expect(await readPersistedJobs(storePath)).toEqual([]);
1914-
const quarantine = await loadCronQuarantineFile(resolveCronQuarantinePath(storePath));
1915-
expect(quarantine.jobs[0]?.reason).toBe("invalid-schedule");
1916-
expect(quarantine.jobs[0]?.job?.id).toBe("invalid-legacy-cron");
1996+
const quarantine = loadCronQuarantinedJobs(storePath);
1997+
expect(quarantine[0]?.reason).toBe("invalid-schedule");
1998+
expect(quarantine[0]?.job?.id).toBe("invalid-legacy-cron");
19171999
});
19182000

19192001
it("repairs legacy root delivery threadId hints into delivery", async () => {

0 commit comments

Comments
 (0)