Skip to content

Commit e2c6fb1

Browse files
committed
fix(cron): add enabled-only immediate runs
1 parent 18ccef3 commit e2c6fb1

16 files changed

Lines changed: 243 additions & 71 deletions

File tree

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,8 @@ Archiving a session (Control UI, or `sessions.patch { key, archived: true, expec
512512

513513
`openclaw automations run <jobId>` returns after enqueueing the manual run. Use `--wait` for shutdown hooks, maintenance scripts, or other automation that must block until the queued run finishes; it polls the returned `runId` (default timeout `10m`, poll interval `2s`) and exits `0` for status `ok`, non-zero for `error`, `skipped`, or a wait timeout.
514514

515+
Direct Gateway event sources can use `cron.run` with `mode: "if-enabled"` to run immediately without overriding an operator-disabled or auto-disabled job. Explicit operator run-now commands continue to use `force`.
516+
515517
The agent `automations` tool returns compact job summaries (`id`, `name`, `enabled`, `nextRunAtMs`, `scheduleKind`, `lastRunStatus`) from `automations(action: "list")`; use `automations(action: "get", jobId: "...")` for one full job definition. Direct Gateway callers can pass `compact: true` to `cron.list`; omitting it preserves the full response with delivery previews.
516518

517519
`openclaw automations create` is an alias for `openclaw automations add`. New jobs can use a positional schedule (`"0 9 * * 1"`, `"every 1h"`, `"20m"`, or an ISO timestamp) followed by a positional agent prompt. Use `--webhook <url>` on `automations add|create` or `automations edit` to POST the finished run payload to an HTTP endpoint; webhook delivery cannot combine with chat delivery flags (`--announce`, `--channel`, `--to`, `--thread-id`, `--account`). On `automations edit`, `--clear-channel`, `--clear-to`, `--clear-thread-id`, and `--clear-account` unset those routing fields individually (each rejected alongside its matching set flag) — distinct from `--no-deliver`, which only disables runner fallback delivery.

‎docs/plugins/workboard.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,8 @@ owns its AI-categorization prompt, model, schedule, and run history. The board
116116
page shows an **Automation** link when that reference is present. Matching
117117
session events nudge the attached automation to run immediately, with events
118118
for the same board coalesced for 60 seconds. The automation's schedule remains
119-
the backstop. Deleting the board does not delete or otherwise mutate the
119+
the backstop. Disabled and auto-disabled automations are never nudged. Deleting
120+
the board does not delete or otherwise mutate the
120121
operator-owned automation job.
121122

122123
Cards are stored in the plugin's own Gateway state and move with the rest of

‎extensions/workboard/src/automation-nudge.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,16 @@ export function createWorkboardAutomationNudgeService(params: {
8585
try {
8686
const result = await params.gateway.request(
8787
"cron.run",
88-
{ id: jobId, mode: "force" },
88+
{ id: jobId, mode: "if-enabled" },
8989
{ scopes: ["operator.admin"] },
9090
);
91+
if (isRecord(result) && result.ran === false) {
92+
const reason = typeof result.reason === "string" ? result.reason : "not-run";
93+
state.logger.warn(
94+
`workboard automation nudge skipped for board ${boardId}: job ${jobId} ${reason}`,
95+
);
96+
return;
97+
}
9198
const runId = isRecord(result) && typeof result.runId === "string" ? result.runId : undefined;
9299
state.logger.info(
93100
`workboard automation nudge requested for board ${boardId}: job ${jobId}${runId ? ` run ${runId}` : ""}`,

‎extensions/workboard/src/lifecycle-sync.test.ts‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ describe("Workboard gateway lifecycle sync", () => {
123123

124124
expect(request).toHaveBeenCalledWith(
125125
"cron.run",
126-
{ id: "job-categorize-planning", mode: "force" },
126+
{ id: "job-categorize-planning", mode: "if-enabled" },
127127
{ scopes: ["operator.admin"] },
128128
);
129129
expect(info).toHaveBeenCalledWith(
@@ -159,7 +159,7 @@ describe("Workboard gateway lifecycle sync", () => {
159159
expect(activeRequest).not.toHaveBeenCalled();
160160
expect(generationRequest).toHaveBeenCalledWith(
161161
"cron.run",
162-
{ id: "job-categorize-planning", mode: "force" },
162+
{ id: "job-categorize-planning", mode: "if-enabled" },
163163
{ scopes: ["operator.admin"] },
164164
);
165165
});
@@ -260,6 +260,32 @@ describe("Workboard gateway lifecycle sync", () => {
260260
expect(warn).toHaveBeenCalledWith(expect.stringContaining("workboard automation nudge failed"));
261261
});
262262

263+
it("logs disabled automation skips without affecting lifecycle sync", async () => {
264+
const store = new WorkboardStore(createMemoryStore());
265+
await store.upsertBoard({ id: "planning", automationJobId: "job-categorize-planning" });
266+
const sessionKey = "agent:main:subagent:workboard-planning-card-disabled";
267+
const card = await createLinkedCard(store, { boardId: "planning", sessionKey });
268+
const request = vi.fn().mockResolvedValue({ ok: true, ran: false, reason: "disabled" });
269+
const warn = vi.fn();
270+
const service = createWorkboardAutomationNudgeService({ store, gateway: { request } });
271+
const context = { logger: { info: vi.fn(), warn } } as never;
272+
await service.start(context);
273+
274+
await expect(
275+
syncWorkboardSubagentEnded({
276+
store,
277+
event: { targetSessionKey: sessionKey, endedAt: card.updatedAt + 1, outcome: "ok" },
278+
onMatched: service.nudge,
279+
}),
280+
).resolves.toBe(1);
281+
await service.stop?.(context);
282+
283+
await expect(store.get(card.id)).resolves.toMatchObject({ status: "review" });
284+
expect(warn).toHaveBeenCalledWith(
285+
"workboard automation nudge skipped for board planning: job job-categorize-planning disabled",
286+
);
287+
});
288+
263289
it("moves a linked running card to review from the subagent hook without UI involvement", async () => {
264290
const store = new WorkboardStore(createMemoryStore());
265291
const sessionKey = "agent:main:subagent:workboard-default-card-1";

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ describe("cron protocol validators", () => {
355355
expectCases(validateCronRunParams, true, [
356356
{ id: "job-1", mode: "force", expectedProcessInstanceId: "process-1" },
357357
{ jobId: "job-2", mode: "due" },
358+
{ jobId: "job-3", mode: "if-enabled" },
358359
]);
359360
expectCases(validateCronRunParams, false, [{ id: "job-1", expectedProcessInstanceId: "" }]);
360361
});

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -719,9 +719,11 @@ export const CronUpdateParamsSchema = cronIdOrJobIdParams({
719719
/** Removes a cron job by id or legacy jobId alias. */
720720
export const CronRemoveParamsSchema = cronIdOrJobIdParams({});
721721

722-
/** Runs a cron job immediately or only if due. */
722+
/** Runs a cron job immediately, immediately if enabled, or only if due. */
723723
export const CronRunParamsSchema = cronIdOrJobIdParams({
724-
mode: Type.Optional(Type.Union([Type.Literal("due"), Type.Literal("force")])),
724+
mode: Type.Optional(
725+
Type.Union([Type.Literal("due"), Type.Literal("force"), Type.Literal("if-enabled")]),
726+
),
725727
/** Rejects the mutation if the Gateway restarted after the caller's preflight. */
726728
expectedProcessInstanceId: Type.Optional(NonEmptyString),
727729
});

‎src/cron/service.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as runOps from "./service/ops-run.js";
1212
import {
1313
type CronAddOptions,
1414
type CronServiceDeps,
15+
type CronRunMode,
1516
type CronUpdatePrecondition,
1617
type CronUpdateOptions,
1718
type CronWakeMode,
@@ -140,15 +141,15 @@ export class CronService implements CronServiceContract {
140141

141142
async run(
142143
id: string,
143-
mode?: "due" | "force",
144+
mode?: CronRunMode,
144145
opts?: CronServiceRunOptions,
145146
): Promise<CronServiceRunResult> {
146147
return await runOps.run(this.state, id, mode, opts);
147148
}
148149

149150
async enqueueRun(
150151
id: string,
151-
mode?: "due" | "force",
152+
mode?: CronRunMode,
152153
opts?: { commitGuard?: () => void },
153154
): Promise<CronServiceRunResult> {
154155
const result = await runOps.enqueueRun(this.state, id, mode, opts);

‎src/cron/service/ops-run-preparation.ts‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,13 @@ import {
2424
} from "./run-admission.js";
2525
import { recomputeUnownedCronSchedules } from "./run-recovery.js";
2626
import { applyCronRuntimeRowsToState, commitCronRuntimeRows } from "./runtime-store.js";
27-
import type { CronEvent, CronServiceState, DeferredCronNotifications } from "./state.js";
28-
import { emit } from "./state.js";
27+
import type {
28+
CronEvent,
29+
CronRunMode,
30+
CronServiceState,
31+
DeferredCronNotifications,
32+
} from "./state.js";
33+
import { emit, isImmediateCronRunMode } from "./state.js";
2934
import { ensureLoaded, runPostPersistCronNotifications, warnIfDisabled } from "./store.js";
3035
import { tryCreateCronTaskRun, tryFinishCronTaskRun } from "./task-runs.js";
3136
import { applyJobResult, armTimer, type CronTriggerEvalOutcome } from "./timer.js";
@@ -36,6 +41,7 @@ type PreparedManualRun =
3641
ran: false;
3742
reason:
3843
| "already-running"
44+
| "disabled"
3945
| "not-due"
4046
| "invalid-spec"
4147
| "restart-recovery-pending"
@@ -145,7 +151,7 @@ function admitsStreamSourceRun(
145151
async function skipInvalidPersistedManualRun(params: {
146152
state: CronServiceState;
147153
job: CronJob;
148-
mode?: "due" | "force";
154+
mode?: CronRunMode;
149155
runId?: string;
150156
terminalTracker?: ManualRunTerminalTracker;
151157
error: unknown;
@@ -168,7 +174,7 @@ async function skipInvalidPersistedManualRun(params: {
168174
endedAt,
169175
},
170176
{
171-
scheduleMode: params.mode === "force" ? "preserve" : "advance",
177+
scheduleMode: isImmediateCronRunMode(params.mode) ? "preserve" : "advance",
172178
deferredNotifications: postPersistNotifications,
173179
},
174180
);
@@ -220,9 +226,9 @@ async function skipInvalidPersistedManualRun(params: {
220226
armTimer(params.state);
221227
}
222228

223-
function recomputeManualRunPreflight(state: CronServiceState, id: string, mode?: "due" | "force") {
229+
function recomputeManualRunPreflight(state: CronServiceState, id: string, mode?: CronRunMode) {
224230
const maintenance = recomputeUnownedCronSchedules(state, {
225-
...(mode === "force" ? { preserveExpiredPacedNextRunJobId: id } : {}),
231+
...(isImmediateCronRunMode(mode) ? { preserveExpiredPacedNextRunJobId: id } : {}),
226232
skipScheduleErrorHandling: true,
227233
});
228234
runPostPersistCronNotifications(state, maintenance.notifications);
@@ -232,7 +238,7 @@ function recomputeManualRunPreflight(state: CronServiceState, id: string, mode?:
232238
async function inspectManualRunPreflight(
233239
state: CronServiceState,
234240
id: string,
235-
mode?: "due" | "force",
241+
mode?: CronRunMode,
236242
runId?: string,
237243
terminalTracker?: ManualRunTerminalTracker,
238244
streamScheduleKey?: string,
@@ -252,6 +258,9 @@ async function inspectManualRunPreflight(
252258
// persist does not block manual triggers for up to STUCK_RUN_MS (#17554).
253259
recomputeManualRunPreflight(state, id, mode);
254260
const job = findJobOrThrow(state, id);
261+
if (mode === "if-enabled" && (!isJobEnabled(job) || job.state.autoDisabled)) {
262+
return { ok: true, ran: false, reason: "disabled" } as const;
263+
}
255264
if (!admitsStreamSourceRun(job, streamScheduleKey, streamSourceIdentity)) {
256265
return { ok: true, ran: false, reason: "not-due" } as const;
257266
}
@@ -265,7 +274,7 @@ async function inspectManualRunPreflight(
265274
return { ok: true, ran: false, reason: "already-running" as const };
266275
}
267276
const now = state.deps.nowMs();
268-
const due = isJobDue(job, now, { forced: mode === "force" });
277+
const due = isJobDue(job, now, { forced: isImmediateCronRunMode(mode) });
269278
if (!due) {
270279
return { ok: true, ran: false, reason: "not-due" } as const;
271280
}
@@ -276,7 +285,7 @@ async function inspectManualRunPreflight(
276285
export async function inspectManualRunDisposition(
277286
state: CronServiceState,
278287
id: string,
279-
mode?: "due" | "force",
288+
mode?: CronRunMode,
280289
): Promise<ManualRunDisposition | { ok: false }> {
281290
// Queue callers need a cheap eligibility check before entering the command
282291
// lane; the real reservation happens later under lock in prepareManualRun.
@@ -293,7 +302,7 @@ export async function inspectManualRunDisposition(
293302
export async function prepareManualRun(
294303
state: CronServiceState,
295304
id: string,
296-
mode?: "due" | "force",
305+
mode?: CronRunMode,
297306
opts?: ManualRunOptions,
298307
): Promise<PreparedManualRun> {
299308
const preflight = await inspectManualRunPreflight(
@@ -329,6 +338,9 @@ export async function prepareManualRun(
329338
await ensureLoaded(state, { skipRecompute: true });
330339
recomputeManualRunPreflight(state, id, mode);
331340
const job = findJobOrThrow(state, id);
341+
if (mode === "if-enabled" && (!isJobEnabled(job) || job.state.autoDisabled)) {
342+
return { ok: true, ran: false, reason: "disabled" } as const;
343+
}
332344
if (!admitsStreamSourceRun(job, opts?.streamScheduleKey, opts?.streamSourceIdentity)) {
333345
return { ok: true, ran: false, reason: "not-due" as const };
334346
}
@@ -350,15 +362,15 @@ export async function prepareManualRun(
350362
}
351363
opts?.commitGuard?.();
352364
const reservationAt = state.deps.nowMs();
353-
if (!isJobDue(job, reservationAt, { forced: mode === "force" })) {
365+
if (!isJobDue(job, reservationAt, { forced: isImmediateCronRunMode(mode) })) {
354366
return { ok: true, ran: false, reason: "not-due" as const };
355367
}
356368
// Persist the queued marker before releasing lock so timer ticks that
357369
// force-reload from disk cannot start the same job concurrently.
358370
const [reserved] = await persistQueuedCronRunReservations({
359371
state,
360372
candidates: [job],
361-
...(mode === "force" ? { forcedJobIds: new Set([job.id]) } : {}),
373+
...(isImmediateCronRunMode(mode) ? { immediateJobIds: new Set([job.id]) } : {}),
362374
reservedAtMs: reservationAt,
363375
});
364376
if (!reserved) {
@@ -409,7 +421,7 @@ export async function prepareManualRun(
409421
export async function activatePreparedManualRun(
410422
state: CronServiceState,
411423
prepared: Extract<PreparedManualRun, { ran: true }>,
412-
mode?: "due" | "force",
424+
mode?: CronRunMode,
413425
): Promise<ActivatedManualRun | Extract<PreparedManualRun, { ran: false }>> {
414426
return await locked(state, async () => {
415427
// Reservations can wait behind another cron run. Reload under the service
@@ -435,6 +447,10 @@ export async function activatePreparedManualRun(
435447
await releasePreparedManualReservationWithRetry(state, prepared);
436448
return { ok: true, ran: false, reason: "not-due" } as const;
437449
}
450+
if (mode === "if-enabled" && (!isJobEnabled(job) || job.state.autoDisabled)) {
451+
await releasePreparedManualReservationWithRetry(state, prepared);
452+
return { ok: true, ran: false, reason: "disabled" } as const;
453+
}
438454
if (!admitsStreamSourceRun(job, prepared.streamScheduleKey, prepared.streamSourceIdentity)) {
439455
// This is reservation identity, not watcher ownership: a force run can
440456
// wait behind cron admission after its owner has stopped for replacement.
@@ -447,7 +463,7 @@ export async function activatePreparedManualRun(
447463
delete dueProbe.state.queuedAtMs;
448464
if (
449465
(prepared.wasEnabled && !isJobEnabled(job)) ||
450-
!isJobDue(dueProbe, state.deps.nowMs(), { forced: mode === "force" })
466+
!isJobDue(dueProbe, state.deps.nowMs(), { forced: isImmediateCronRunMode(mode) })
451467
) {
452468
await releasePreparedManualReservationWithRetry(state, prepared);
453469
return { ok: true, ran: false, reason: "not-due" } as const;
@@ -500,8 +516,8 @@ export async function activatePreparedManualRun(
500516
// target writeback from disk without mutating the running object.
501517
const admittedJob = structuredClone(activatedJob);
502518
const executionJob = structuredClone(activatedJob);
503-
if (mode === "force" && executionJob.trigger && !prepared.evaluateTrigger) {
504-
// Force means run the payload now; strip the gate only from this snapshot
519+
if (isImmediateCronRunMode(mode) && executionJob.trigger && !prepared.evaluateTrigger) {
520+
// Immediate modes run the payload now; strip the gate only from this snapshot
505521
// so persisted trigger state and future due evaluations stay intact.
506522
delete executionJob.trigger;
507523
}

‎src/cron/service/ops-run.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,13 @@ import {
3535
} from "./run-receipts.js";
3636
import { recomputeUnownedCronSchedules } from "./run-recovery.js";
3737
import { applyCronRuntimeRowsToState, commitCronRuntimeRows } from "./runtime-store.js";
38-
import type { CronServiceState, CronWakeMode, DeferredCronNotifications } from "./state.js";
39-
import { emit } from "./state.js";
38+
import type {
39+
CronRunMode,
40+
CronServiceState,
41+
CronWakeMode,
42+
DeferredCronNotifications,
43+
} from "./state.js";
44+
import { emit, isImmediateCronRunMode } from "./state.js";
4045
import { ensureLoaded, publishCronRuntimeRows, runPostPersistCronNotifications } from "./store.js";
4146
import { tryFinishCronTaskRunWithoutHistory } from "./task-runs.js";
4247
import {
@@ -66,7 +71,7 @@ function applyManualRunOutcome(params: {
6671
startedAt: number;
6772
endedAt: number;
6873
triggerSkipped: boolean;
69-
mode?: "due" | "force";
74+
mode?: CronRunMode;
7075
deferredNotifications: DeferredCronNotifications;
7176
}): boolean {
7277
const scheduleOwnership = resolveCronRunScheduleOwnership({
@@ -82,8 +87,8 @@ function applyManualRunOutcome(params: {
8287
const scheduleMode =
8388
scheduleOwnership === "stale"
8489
? "stale-preserve"
85-
: params.mode === "force"
86-
? "force-preserve"
90+
: isImmediateCronRunMode(params.mode)
91+
? "immediate-preserve"
8792
: "advance";
8893
if (params.triggerSkipped) {
8994
applyTriggerNoFireResult(
@@ -107,7 +112,7 @@ function applyManualRunOutcome(params: {
107112
params.job,
108113
{ ...params.coreResult, startedAt: params.startedAt, endedAt: params.endedAt },
109114
{
110-
scheduleMode: scheduleMode === "force-preserve" ? "preserve" : "advance",
115+
scheduleMode: scheduleMode === "immediate-preserve" ? "preserve" : "advance",
111116
scheduleOwnership,
112117
scheduleOwnershipAtMs: params.prepared.scheduleOwnershipAtMs,
113118
deferredNotifications: params.deferredNotifications,
@@ -132,7 +137,7 @@ function applyManualRunOutcome(params: {
132137
async function finishPreparedManualRun(
133138
state: CronServiceState,
134139
prepared: ActivatedManualRun,
135-
mode?: "due" | "force",
140+
mode?: CronRunMode,
136141
): Promise<void> {
137142
const executionJob = prepared.executionJob;
138143
const startedAt = prepared.startedAt;
@@ -387,7 +392,7 @@ async function finishPreparedManualRun(
387392
publishCronRuntimeRows(state);
388393
const maintenance = recomputeUnownedCronSchedules(state, {
389394
recomputeExpired: true,
390-
...(mode === "force" ? { preserveExpiredPacedNextRunJobId: jobId } : {}),
395+
...(isImmediateCronRunMode(mode) ? { preserveExpiredPacedNextRunJobId: jobId } : {}),
391396
});
392397
runPostPersistCronNotifications(state, maintenance.notifications);
393398
applyCronRuntimeRowsToState(state, maintenance.jobs);
@@ -452,7 +457,7 @@ async function finishPreparedManualRun(
452457
export async function run(
453458
state: CronServiceState,
454459
id: string,
455-
mode?: "due" | "force",
460+
mode?: CronRunMode,
456461
opts?: ManualRunOptions,
457462
) {
458463
const prepared = await prepareManualRun(state, id, mode, opts);
@@ -495,7 +500,7 @@ export async function run(
495500
export async function enqueueRun(
496501
state: CronServiceState,
497502
id: string,
498-
mode?: "due" | "force",
503+
mode?: CronRunMode,
499504
opts?: { commitGuard?: () => void },
500505
) {
501506
const disposition = await inspectManualRunDisposition(state, id, mode);

0 commit comments

Comments
 (0)