Skip to content

Commit 96e3051

Browse files
Manage Claw cron jobs through the gateway (#102383)
* Manage Claw cron jobs through the gateway * test(claws): cover scheduled work lifecycle * docs(claws): document scheduled work * fix(claws): preserve modified cron jobs * fix(claws): internalize cron gateway payloads * fix(claws): make cron removal convergent * style(claws): satisfy intermediate lifecycle lint * refactor(claws): extract lifecycle state contracts * test(claws): clean cron restack fixtures --------- Co-authored-by: Patrick Erichsen <[email protected]>
1 parent bb3f6c5 commit 96e3051

20 files changed

Lines changed: 1390 additions & 224 deletions

‎docs/.i18n/glossary.zh-CN.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@
4747
"source": "Claws",
4848
"target": "Claws"
4949
},
50+
{
51+
"source": "Cron jobs",
52+
"target": "定时任务"
53+
},
5054
{
5155
"source": "ClawRouter (managed multi-provider routing)",
5256
"target": "ClawRouter(托管式多提供商路由)"

‎docs/cli/claws.md‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,28 @@ or reuses matching ones and records whether the Claw introduced or referenced
9696
each resource. Plugins remain process-wide OpenClaw capabilities rather than
9797
per-agent installations.
9898

99+
Cron jobs declare scheduled work for the new agent:
100+
101+
```json
102+
{
103+
"cronJobs": [
104+
{
105+
"id": "daily-summary",
106+
"name": "Daily incident summary",
107+
"schedule": { "cron": "0 9 * * *", "timezone": "UTC" },
108+
"session": "isolated",
109+
"message": "Summarize active incidents."
110+
}
111+
]
112+
}
113+
```
114+
115+
Claws use the existing Gateway scheduler and bind created jobs to the new
116+
agent. Preview, provenance, status, and removal cover those jobs without
117+
changing the behavior of ordinary cron commands. Removal rereads the live job
118+
through the Gateway and preserves it when its owned definition changed after
119+
planning.
120+
99121
## Inspect and preview
100122

101123
Validate the source without planning local changes:
@@ -138,8 +160,8 @@ openclaw claws status
138160
openclaw claws status incident-triage --json
139161
```
140162

141-
`status` compares the installed agent and its recorded workspace and package
142-
provenance with current state. It reports incomplete installs, missing
163+
`status` compares the installed agent and its recorded workspace, package, and
164+
cron provenance with current state. It reports incomplete installs, missing
143165
resources, and drift without changing local state.
144166

145167
Claw provenance distinguishes two relationships:
@@ -215,3 +237,4 @@ Use `--json` for experimental machine-readable output.
215237
- [Agents](/cli/agents)
216238
- [Skills](/tools/skills)
217239
- [Plugins](/tools/plugin)
240+
- [Cron jobs](/automation/cron-jobs)

‎src/claws/add.ts‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ import { DEFAULT_AGENT_ID, normalizeAgentId } from "../routing/session-key.js";
1313
import type { RuntimeEnv } from "../runtime.js";
1414
import type { OpenClawStateDatabaseOptions } from "../state/openclaw-state-db.js";
1515
import { resolveUserPath } from "../utils.js";
16+
import {
17+
ClawCronInstallError,
18+
installClawCronJobs,
19+
type ClawCronGateway,
20+
type PersistedClawCronRef,
21+
} from "./cron.js";
1622
import { ClawPackageInstallError, installClawPackages } from "./packages.js";
1723
import {
1824
deleteClawInstallRecord,
@@ -41,6 +47,8 @@ type ClawAddApplyOptions = OpenClawStateDatabaseOptions & {
4147
createWorkspaceFiles?: typeof createClawWorkspaceFiles;
4248
runtime?: RuntimeEnv;
4349
installPackages?: typeof installClawPackages;
50+
installCronJobs?: typeof installClawCronJobs;
51+
cronGateway?: Pick<ClawCronGateway, "add" | "list">;
4452
nowMs?: number;
4553
};
4654
export class ClawAddMutationError extends Error {
@@ -66,6 +74,7 @@ type ClawAddResult = {
6674
configCommitted: boolean;
6775
workspaceFiles: PersistedClawWorkspaceFile[];
6876
packages: PersistedClawPackageRef[];
77+
cronJobs: PersistedClawCronRef[];
6978
installRecord?: PersistedClawInstall;
7079
error?: {
7180
code: string;
@@ -76,7 +85,8 @@ type ClawAddResult = {
7685

7786
function hasUnsupportedMutationActions(plan: ClawAddPlan): boolean {
7887
return plan.actions.some(
79-
(action) => !["agent", "workspace", "workspaceFile", "package"].includes(action.kind),
88+
(action) =>
89+
!["agent", "workspace", "workspaceFile", "package", "cronJob"].includes(action.kind),
8090
);
8191
}
8292

@@ -140,6 +150,7 @@ function partialResult(params: {
140150
workspaceFiles?: PersistedClawWorkspaceFile[];
141151
packages?: PersistedClawPackageRef[];
142152
installStatus?: ClawInstallStatus;
153+
cronJobs?: PersistedClawCronRef[];
143154
error: ClawAddResult["error"];
144155
nowMs?: number;
145156
}): ClawAddResult {
@@ -156,6 +167,7 @@ function partialResult(params: {
156167
configCommitted: params.configCommitted,
157168
workspaceFiles: params.workspaceFiles ?? [],
158169
packages: params.packages ?? [],
170+
cronJobs: params.cronJobs ?? [],
159171
installRecord: {
160172
...params.installRecord,
161173
status: params.installStatus ?? "partial",
@@ -175,7 +187,7 @@ export async function applyClawAddPlan(
175187
if (hasUnsupportedMutationActions(plan)) {
176188
throw new ClawAddMutationError(
177189
"unsupported_components",
178-
"This build can add agent settings, workspace files, and declared packages; MCP servers and cron jobs require later lifecycle slices.",
190+
"This build can add agent settings, workspace files, packages, and cron jobs; declared MCP servers require a later lifecycle slice.",
179191
);
180192
}
181193
if (options.consentPlanIntegrity !== plan.planIntegrity) {
@@ -401,6 +413,7 @@ export async function applyClawAddPlan(
401413
configCommitted,
402414
workspaceFiles: workspaceError.createdFiles,
403415
packages,
416+
cronJobs: [],
404417
installRecord: {
405418
...installRecord,
406419
status: "config_committed",
@@ -414,9 +427,10 @@ export async function applyClawAddPlan(
414427
};
415428
}
416429

430+
let cronJobs: PersistedClawCronRef[] = [];
417431
try {
418-
// Package mutation is last: skills now have their workspace, and a package
419-
// failure cannot leave a later workspace/configuration step unapplied.
432+
// Skills require their workspace. Recurring work is enabled only after all
433+
// package mutation succeeds.
420434
packages = await installPackages(plan, options);
421435
} catch (error) {
422436
const packageError =
@@ -440,6 +454,33 @@ export async function applyClawAddPlan(
440454
});
441455
}
442456

457+
const installCronJobs = options.installCronJobs ?? installClawCronJobs;
458+
try {
459+
cronJobs = await installCronJobs(plan, { ...options, gateway: options.cronGateway });
460+
} catch (error) {
461+
const cronError =
462+
error instanceof ClawCronInstallError
463+
? error
464+
: new ClawCronInstallError(
465+
"cron_install_failed",
466+
error instanceof Error ? error.message : String(error),
467+
cronJobs,
468+
);
469+
markInstallStatus(plan.agent.finalId, "config_committed", ["config_committed"], options);
470+
return partialResult({
471+
plan,
472+
installRecord,
473+
workspaceCreated,
474+
configCommitted,
475+
workspaceFiles,
476+
packages,
477+
cronJobs: cronError.cronJobs,
478+
installStatus: "config_committed",
479+
error: { code: cronError.code, message: cronError.message },
480+
nowMs: options.nowMs,
481+
});
482+
}
483+
443484
try {
444485
markInstallStatus(plan.agent.finalId, "complete", ["config_committed", "complete"], options);
445486
return {
@@ -454,6 +495,7 @@ export async function applyClawAddPlan(
454495
workspaceCreated,
455496
configCommitted,
456497
packages,
498+
cronJobs,
457499
workspaceFiles,
458500
installRecord: {
459501
...installRecord,
@@ -469,6 +511,7 @@ export async function applyClawAddPlan(
469511
configCommitted,
470512
workspaceFiles,
471513
packages,
514+
cronJobs,
472515
error: { code: "provenance_failed", message: (error as Error).message },
473516
});
474517
}

‎src/claws/cron.test.ts‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import { join } from "node:path";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { validateCronAddParams } from "../../packages/gateway-protocol/src/index.js";
4+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
6+
import { installClawCronJobs, readClawCronRefs } from "./cron.js";
7+
import { buildClawAddPlan } from "./lifecycle.js";
8+
import { parseClawManifest } from "./schema.js";
9+
import type { ClawSourceIdentity } from "./types.js";
10+
11+
afterEach(() => closeOpenClawStateDatabaseForTest());
12+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
13+
14+
async function fixture() {
15+
const root = tempDirs.make("openclaw-claw-cron-");
16+
const parsed = parseClawManifest({
17+
schemaVersion: 1,
18+
agent: { id: "worker" },
19+
cronJobs: [
20+
{
21+
id: "daily-report",
22+
name: "Daily report",
23+
schedule: { cron: "0 9 * * *", timezone: "UTC" },
24+
session: "main",
25+
message: "Prepare the report",
26+
delivery: { mode: "announce", channel: "last" },
27+
},
28+
],
29+
});
30+
if (!parsed.ok) {
31+
throw new Error(JSON.stringify(parsed.diagnostics));
32+
}
33+
const source: ClawSourceIdentity = {
34+
kind: "package",
35+
name: "@acme/worker",
36+
version: "1.0.0",
37+
packageRoot: root,
38+
manifestPath: join(root, "openclaw.claw.json"),
39+
integrityKind: "artifact",
40+
integrity: "sha256:manifest",
41+
byteLength: 100,
42+
};
43+
const plan = await buildClawAddPlan({
44+
manifest: parsed.manifest,
45+
source,
46+
context: { workspace: join(root, "workspace"), agentId: "worker-two" },
47+
});
48+
return { root, plan, env: { OPENCLAW_STATE_DIR: join(root, "state") } };
49+
}
50+
51+
describe("installClawCronJobs", () => {
52+
it("pins declarations and execution to the final agent id", async () => {
53+
const current = await fixture();
54+
const add = vi.fn().mockResolvedValue({ id: "scheduler-123" });
55+
56+
const refs = await installClawCronJobs(current.plan, {
57+
env: current.env,
58+
gateway: { add },
59+
nowMs: 42,
60+
});
61+
62+
expect(add).toHaveBeenCalledWith({
63+
name: "Daily report",
64+
declarationKey: "claw:worker-two:daily-report",
65+
displayName: "Daily report",
66+
owner: { agentId: "worker-two" },
67+
enabled: true,
68+
agentId: "worker-two",
69+
schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },
70+
sessionTarget: "session:agent:worker-two:main",
71+
wakeMode: "now",
72+
payload: { kind: "agentTurn", message: "Prepare the report" },
73+
delivery: { mode: "announce", channel: "last" },
74+
});
75+
expect(validateCronAddParams(add.mock.calls[0]?.[0])).toBe(true);
76+
expect(refs).toMatchObject([
77+
{
78+
schemaVersion: "openclaw.clawCronRef.v1",
79+
agentId: "worker-two",
80+
manifestId: "daily-report",
81+
schedulerJobId: "scheduler-123",
82+
status: "complete",
83+
},
84+
]);
85+
expect(readClawCronRefs("worker-two", { env: current.env })).toEqual(refs);
86+
});
87+
88+
it("accepts declaration convergence results from cron.add", async () => {
89+
const current = await fixture();
90+
91+
const refs = await installClawCronJobs(current.plan, {
92+
env: current.env,
93+
gateway: { add: vi.fn().mockResolvedValue({ created: false, job: { id: "existing-1" } }) },
94+
});
95+
96+
expect(refs[0]).toMatchObject({ schedulerJobId: "existing-1", status: "complete" });
97+
});
98+
99+
it("preserves an ambiguous pending reference when cron.add fails", async () => {
100+
const current = await fixture();
101+
102+
await expect(
103+
installClawCronJobs(current.plan, {
104+
env: current.env,
105+
gateway: { add: vi.fn().mockRejectedValue(new Error("gateway unavailable")) },
106+
}),
107+
).rejects.toMatchObject({
108+
code: "cron_install_failed",
109+
cronJobs: [{ manifestId: "daily-report", status: "pending", error: "gateway unavailable" }],
110+
});
111+
expect(readClawCronRefs("worker-two", { env: current.env })).toMatchObject([
112+
{ manifestId: "daily-report", status: "pending", error: "gateway unavailable" },
113+
]);
114+
});
115+
116+
it("reconciles a response-lost retry by declaration key", async () => {
117+
const current = await fixture();
118+
const add = vi.fn().mockRejectedValue(new Error("response lost"));
119+
120+
await expect(
121+
installClawCronJobs(current.plan, {
122+
env: current.env,
123+
gateway: { add },
124+
}),
125+
).rejects.toMatchObject({
126+
code: "cron_install_failed",
127+
cronJobs: [{ status: "pending" }],
128+
});
129+
130+
const refs = await installClawCronJobs(current.plan, {
131+
env: current.env,
132+
gateway: {
133+
add,
134+
list: vi.fn().mockResolvedValue({
135+
jobs: [
136+
{
137+
id: "scheduler-after-lost-response",
138+
declarationKey: "claw:worker-two:daily-report",
139+
},
140+
],
141+
}),
142+
},
143+
});
144+
145+
expect(add).toHaveBeenCalledTimes(1);
146+
expect(refs).toMatchObject([
147+
{ schedulerJobId: "scheduler-after-lost-response", status: "complete" },
148+
]);
149+
});
150+
151+
it("converges concurrent installs through the declaration key", async () => {
152+
const current = await fixture();
153+
const jobs = new Map<string, { id: string; declarationKey: string }>();
154+
const add = vi.fn(async (input: Record<string, unknown>) => {
155+
await Promise.resolve();
156+
const declarationKey = String(input.declarationKey);
157+
const existing = jobs.get(declarationKey);
158+
if (existing) {
159+
return { created: false, job: existing };
160+
}
161+
const created = { id: "scheduler-converged", declarationKey };
162+
jobs.set(declarationKey, created);
163+
return { created: true, job: created };
164+
});
165+
166+
const [first, second] = await Promise.all([
167+
installClawCronJobs(current.plan, { env: current.env, gateway: { add } }),
168+
installClawCronJobs(current.plan, { env: current.env, gateway: { add } }),
169+
]);
170+
171+
expect(jobs.size).toBe(1);
172+
expect(first[0]).toMatchObject({ schedulerJobId: "scheduler-converged", status: "complete" });
173+
expect(second[0]).toMatchObject({ schedulerJobId: "scheduler-converged", status: "complete" });
174+
});
175+
});

0 commit comments

Comments
 (0)