Skip to content

Commit 13125bf

Browse files
authored
fix(cron): record real delivery outcomes and stop false-success completions (#131228)
* fix(cron): record real delivery outcomes and stop false-success completions Record delivery outcomes at their owners and derive whole-run completion, delivery failure alerts, and one-shot retention from those facts. Keep execution status separate from delivery failure, and retain undelivered jobs and transcripts for inspection. Requested delivery is required unless explicitly best-effort. Existing alternate-route alert policy and duplicate-send protection remain unchanged. * fix(cron): preserve cleanup ownership and record-only replay Transfer transcript cleanup ownership before awaiting delivery dispatch so exceptions retain the diagnostic session while runtime resources still retire. Remove the returned cleanup flag and exercise actual dispatch in deletion and admission-release tests. Keep delivery-failure notification recovery record-only, preserving the historical receipt without scheduling another alert. Absorb the single-use alert helper into finalization and strengthen canonical delivery-state coverage. * fix(cron): retain one-shots only for failed or unknown delivery * fix(cron): treat empty webhook summaries as intentional silence * fix(cron): throttle delivery failure alerts with cooldown * docs(cron): align cleanup and bestEffort text * fix(cron): align cleanup and replay with run outcomes Release quiet and best-effort successful one-shot sessions through the existing dispatch cleanup owner. Carry the finalizer's undelivered execution status so fatal errors and unrecovered presentation warnings retain evidence. Restore replay cooldown only from recorded notification intent, without recomputing alert requests through current policy. Consolidate target-error results and clarify the shared cooldown and successful-execution contracts. * fix(cron): extract reply skip-reason leaf to break import cycle and refresh prompt snapshots
1 parent 812350e commit 13125bf

54 files changed

Lines changed: 1353 additions & 656 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/automation/cron-jobs.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ Manage automations with the `openclaw automations` CLI; `openclaw cron` remains
4545
- Automations run **inside the Gateway process**, not inside the model. The Gateway must be running for schedules to fire.
4646
- Job definitions, runtime state, and run history persist in OpenClaw's shared SQLite state database, so restarts do not lose schedules.
4747
- Every automation run creates a [background task](/automation/tasks) record.
48-
- One-shot jobs (`--at`) auto-delete only when run `completionStatus` is `succeeded`; pass `--keep-after-run` to keep successful jobs. A required-delivery failure or unknown completion keeps the job disabled for inspection and restart recovery without replaying the payload.
48+
- One-shot jobs (`--at`) auto-delete after successful completion: delivery is confirmed, not requested, intentionally suppressed, or explicitly best-effort. Failed or unknown required delivery retains the job disabled for inspection without replaying the payload. Pass `--keep-after-run` to keep successful jobs too.
4949
- Per-run wall-clock budget: `--timeout-seconds` when set. Otherwise, isolated/detached agent-turn jobs are bounded by the scheduler's own 60-minute watchdog before the underlying agent-turn timeout (`agents.defaults.timeoutSeconds`, default 48 hours) would ever apply; command jobs default to 10 minutes, and script payloads default to 5 minutes.
5050
- On Gateway startup, overdue isolated agent-turn jobs are rescheduled instead of replayed immediately, keeping model/tool bootstrap work out of the channel-connect window. Startup catch-up delays survive label or payload-content reconciliation and another restart; changing the schedule starts a new scheduling decision.
5151
- If you drive `openclaw agent` from system cron or another external scheduler, wrap it with a hard-kill escalation even though the CLI already handles `SIGTERM`/`SIGINT`. Gateway-backed runs ask the Gateway to abort accepted runs; `--local` runs get the same abort signal. For GNU `timeout`, prefer `timeout -k 60 600 openclaw agent ...` over plain `timeout 600 ...` — the `-k` value is the backstop if the process cannot drain in time. For systemd units, use a `SIGTERM` stop signal with a grace window (`TimeoutStopSec`) before the final kill. Reusing a `--run-id` while the original Gateway run is still active reports the duplicate as in-flight instead of starting a second run.
@@ -397,6 +397,8 @@ Agent-turn jobs default to the creating conversation when the create request car
397397
| `webhook` | POST finished event payload to a URL |
398398
| `none` | No runner fallback delivery |
399399

400+
A successful primary webhook run with no nonblank summary intentionally skips the POST and records `deliverySuppressionReason: "empty"`, matching announce delivery's optional-output contract. Execution errors still send the error event even without a summary.
401+
400402
When `gateway.publicOrigin` is configured and the Control UI is enabled, chat
401403
notifications include an `Inspect` link into the Control UI. Command and script
402404
completion announcements open the automation run; isolated agent announcements
@@ -463,7 +465,7 @@ Failure notification routes resolve in this order:
463465
- `failureAlert.includeSkipped: true` opts a job or global automation alert policy into repeated skipped-run alerts. Skipped runs keep a separate consecutive-skip counter, so they do not affect execution-error backoff.
464466
- `openclaw automations edit` exposes per-job alert tuning: `--failure-alert`/`--no-failure-alert`, `--failure-alert-after <n>`, `--failure-alert-channel`, `--failure-alert-to`, `--failure-alert-cooldown`, `--failure-alert-include-skipped`/`--failure-alert-exclude-skipped`, `--failure-alert-mode`, and `--failure-alert-account-id`.
465467

466-
A required completion-delivery failure is distinct from an execution failure: a run can record `status: "ok"` with `completionStatus: "failed"`. It does not increment the execution-failure streak or backoff. The scheduler may notify immediately only through a resolved alternate failure destination; it never retries the already-failed primary route.
468+
A required completion-delivery failure is distinct from an execution failure: a run can record `status: "ok"` with `completionStatus: "failed"`. It does not increment the execution-failure streak or backoff. A delivery-failure alert can notify through a resolved alternate failure destination without waiting for `failureAlert.after`. All such alerts, including the first delivery failure after an execution alert, honor the shared job/global `failureAlert.cooldownMs` (default 1 hour); suppressed alerts still leave the delivery failure in run history. Skipped runs and quiet trigger checks do not clear the cooldown; successful completion does. The scheduler never retries the already-failed primary route for an alert.
467469

468470
Chat failure notifications include the run start time in the agent's configured user timezone. When `gateway.publicOrigin` is configured and the Control UI is enabled, they also include an `Inspect` link to the automation run. Webhook message text stays stable; integrations can read the same instant from the structured `runAtMs` field and construct their own links.
469471
Chat notifications show normalized failure causes or allowlisted producer facts for known command and script failures. Arbitrary commands, paths, provider bodies, secrets, delivery errors, skip reasons, diagnostics, and stack/error text remain in automation history. Failure webhooks retain the structured raw error for diagnostic integrations.
@@ -589,7 +591,9 @@ Archiving a session (Control UI, or `sessions.patch { key, archived: true, expec
589591

590592
`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` only for `completionStatus: "succeeded"`. Failed or unknown completion and wait timeouts exit non-zero.
591593

592-
Run history keeps payload execution in `status` (`ok`, `error`, or `skipped`) and whole-run completion in `completionStatus` (`succeeded`, `failed`, or `unknown`). Delivery is required only when the admitted job explicitly sets `delivery.bestEffort: false`; delivery-only failure leaves execution `status: "ok"`, does not increment execution error counters or enter retry backoff, and records `completionStatus: "failed"`.
594+
Run history keeps payload execution in `status` (`ok`, `error`, or `skipped`) and whole-run completion in `completionStatus` (`succeeded`, `failed`, or `unknown`). Requested delivery is required unless the admitted job explicitly sets `delivery.bestEffort: true`; delivery-only failure leaves execution `status: "ok"`, does not increment execution error counters or enter retry backoff, and records `completionStatus: "failed"`. An adapter send without a delivery identity stays `unknown`, without an automatic resend that could duplicate the message.
595+
596+
Intentional silence (`NO_REPLY`), intentionally empty output, heartbeat acknowledgments, and channel reply transforms record `deliverySuppressionReason` without claiming delivery or triggering delivery-failure alerts. These successful non-outcomes and successful executions with explicit `delivery.bestEffort: true` delete one-shots normally. A transport hook veto instead records a delivery error without an intentional-suppression reason. Active descendants without a final reply, stale interim output, and output emptied by TTS instead record a delivery error. Retained one-shot jobs do not automatically rerun; inspect their history and delivery outcome before retrying or removing them.
593597

594598
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`.
595599

‎docs/cli/cron.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ Isolated automation runs treat run-level agent failures as job errors even when
130130

131131
Command jobs do not start an isolated agent turn. A zero exit code records `ok`; non-zero exit, signal, timeout, or no-output timeout records `error` and can trigger the same failure notification path.
132132

133-
Required completion delivery is separate: `status: "ok"` with `completionStatus: "failed"` does not increment the execution streak or backoff. It can notify immediately only through a resolved alternate failure destination, never the primary route that just failed.
133+
Required completion delivery is separate: `status: "ok"` with `completionStatus: "failed"` does not increment the execution streak or backoff. Delivery-failure alerts use a resolved alternate failure destination without the `after` threshold. Every alert, including the first delivery failure after an execution alert, honors the shared job/global `failureAlert.cooldownMs` (default 1 hour), never retrying the primary route that just failed.
134134

135135
If an isolated run times out before the first model request, `openclaw automations show` and `openclaw automations runs` include a phase-specific error such as `setup timed out before runner start` or a stall message naming the last-known startup phase (for example `context-engine`). For CLI-backed providers, the pre-model watchdog stays active until the external CLI turn starts, so session lookup, hook, auth, prompt, and CLI setup stalls are reported as pre-model automation failures.
136136

@@ -141,7 +141,7 @@ If an isolated run times out before the first model request, `openclaw automatio
141141
`--at <datetime>` schedules a one-shot run. Offset-less datetimes are treated as UTC unless you also pass `--tz <iana>`, which interprets the wall-clock time in the given timezone.
142142

143143
<Note>
144-
One-shot jobs delete only after `completionStatus: "succeeded"`. Required-delivery failure or unknown completion keeps the job disabled, with no next run, so restarts do not replay payload side effects. Use `--keep-after-run` to preserve successful jobs too.
144+
One-shot jobs delete only after `completionStatus: "succeeded"`. Required-delivery failure or unknown completion keeps the job disabled, with no next run, so restarts do not replay payload side effects. Intentional silence and successful executions with explicit `delivery.bestEffort: true` complete and delete normally. Use `--keep-after-run` to preserve successful jobs too.
145145
</Note>
146146

147147
### Recurring jobs

‎src/agents/tools/cron-tool-schema.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,12 +235,17 @@ function createCronDeliverySchema(): TSchema {
235235
description: "Thread/topic id",
236236
}),
237237
),
238-
bestEffort: Type.Optional(Type.Boolean()),
238+
bestEffort: Type.Optional(
239+
Type.Boolean({
240+
description:
241+
"Omitted/false requires requested delivery for successful completion; true lets successful execution complete and delete a one-shot despite failed/unknown delivery. Intentional silence succeeds in either mode.",
242+
}),
243+
),
239244
accountId: deliveryStringSchema("Delivery account"),
240245
failureDestination: Type.Optional(
241246
Type.Union([failureDestinationObject, Type.Null()], {
242247
description:
243-
"Failure-alert route override and alternate for immediate required-delivery failure; null clears.",
248+
"Failure-alert route override; required-delivery failures bypass after but share the execution-alert cooldown; null clears.",
244249
}),
245250
),
246251
completionDestination: Type.Optional(
@@ -264,7 +269,10 @@ function createCronFailureAlertSchema(): TSchema {
264269
Type.Unsafe<Record<string, unknown> | false>({
265270
type: "object",
266271
properties: {
267-
after: optionalPositiveIntegerSchema({ description: "Failures before alert" }),
272+
after: optionalPositiveIntegerSchema({
273+
description:
274+
"Consecutive execution failures before alert; delivery failures bypass this threshold",
275+
}),
268276
channel: Type.Optional(Type.String({ description: "Alert channel" })),
269277
to: Type.Optional(Type.String({ description: "Alert target" })),
270278
cooldownMs: optionalNonNegativeIntegerSchema({ description: "Alert cooldown ms" }),
@@ -274,7 +282,7 @@ function createCronFailureAlertSchema(): TSchema {
274282
},
275283
additionalProperties: true,
276284
description:
277-
"Failure alert policy/route override. Route-backed jobs default to after=2 and cooldownMs=3600000; false disables execution/delivery alerts but not the auto-disable safety notice.",
285+
"Failure alert policy/route override. Route-backed jobs default to after=2 for execution failures and cooldownMs=3600000 for all failure alerts; false disables execution/delivery alerts but not the auto-disable safety notice.",
278286
}),
279287
);
280288
}
@@ -324,7 +332,12 @@ export function createCronToolSchema(options?: CronToolSchemaOptions): TSchema {
324332
: {}),
325333
description: Type.Optional(Type.String({ description: "Human description" })),
326334
enabled: Type.Optional(Type.Boolean()),
327-
deleteAfterRun: Type.Optional(Type.Boolean({ description: "Delete after first run" })),
335+
deleteAfterRun: Type.Optional(
336+
Type.Boolean({
337+
description:
338+
"Delete one-shot after successful completion: delivery confirmed, not requested, intentionally silent, or explicitly bestEffort. Failed/unknown required delivery retains it disabled.",
339+
}),
340+
),
328341
sessionKey: nullableStringSchema("Explicit session key, or null to clear it"),
329342
failureAlert: createCronFailureAlertSchema(),
330343
},

‎src/agents/tools/cron-tool.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ ACTIONS: status | list [includeDisabled,limit?,offset?] (use nextOffset for the
187187
ADD: ${addFields}. Required: schedule+payload.
188188
189189
SCHEDULE:
190-
- {kind:"at",at:"ISO-8601"} one-shot; no tz=UTC; auto-deletes after run.
190+
- {kind:"at",at:"ISO-8601"} one-shot; no tz=UTC; auto-deletes after successful completion: delivery confirmed, not requested, intentionally silent, or explicitly bestEffort. Failed/unknown required delivery retains it disabled.
191191
- {kind:"every",everyMs}.
192192
- {kind:"cron",expr,tz?:"IANA"}: expr is wall time in tz; never pre-convert to UTC; no tz=gateway host local. 18:00 Shanghai => {expr:"0 18 * * *",tz:"Asia/Shanghai"}.${streamScheduleLine}
193193
@@ -203,11 +203,11 @@ PACED LOOP: recurring job + pacing{min?,max?} durations ("15m","4h"; at least on
203203
204204
${triggerSection}
205205
206-
DELIVERY {mode:"none"|"announce"|"webhook",channel?,to?,threadId?,bestEffort?,completionDestination?}: where detached run output goes. Omitted=announce (current=>canonical session commit, plus one normal channel send for external chats; isolated=>last route; set channel/to for a specific chat — no messaging tool inside the run). A current announce succeeds only after its history commit; WebChat observes that commit live and after reconnect without another user message.${silentWatcherCue} webhook posts finished-run event to URL in \`to\`. To keep announce delivery and also POST completion, use mode:"announce" with completionDestination:{mode:"webhook",to:"https://..."}.
206+
DELIVERY {mode:"none"|"announce"|"webhook",channel?,to?,threadId?,bestEffort?,completionDestination?}: where detached run output goes. Omitted=announce (current=>canonical session commit, plus one normal channel send for external chats; isolated=>last route; set channel/to for a specific chat — no messaging tool inside the run). A current announce succeeds only after its history commit; WebChat observes that commit live and after reconnect without another user message.${silentWatcherCue} webhook posts finished-run event (successful empty summary is intentional silence, no POST) to URL in \`to\`. To keep announce delivery and also POST completion, use mode:"announce" with completionDestination:{mode:"webhook",to:"https://..."}.
207207
208-
FAILURE ALERTS: jobs with a failure route default to alerting after 2 consecutive execution failures with a 1h cooldown. Route order: job failureAlert fields, delivery.failureDestination over global cron.failureAlert destination fields, then primary announce. failureAlert:false disables execution/delivery alerts, not the auto-disable safety notice; a failureAlert object activates/tunes. bestEffort suppresses inherited execution alerts. Required completion-delivery failure uses only an alternate route immediately and does not increment the execution streak.
208+
FAILURE ALERTS: jobs with a failure route default to alerting after 2 consecutive execution failures with a 1h cooldown. Route order: job failureAlert fields, delivery.failureDestination over global cron.failureAlert destination fields, then primary announce. failureAlert:false disables execution/delivery alerts, not the auto-disable safety notice; a failureAlert object activates/tunes. bestEffort suppresses inherited execution alerts. Required completion-delivery failure uses only an alternate route, bypasses after, and shares the execution-alert cooldown from the first failure; it does not increment the execution streak.
209209
210-
Job wakeMode (main jobs): "now"(default)|"next-heartbeat". Restricted automation-run sessions: self status/list/get/runs/remove + own next_check only. failureAlert {...}|false disables. jobId canonical (id=compat). contextMessages 0-10 embeds recent chat lines into reminder text.`;
210+
Job wakeMode (main jobs): "now"(default)|"next-heartbeat". Restricted automation-run sessions: self status/list/get/runs/remove + own next_check only. jobId canonical (id=compat). contextMessages 0-10 embeds recent chat lines into reminder text.`;
211211
}
212212

213213
export function createCronTool(opts?: CronToolOptions, deps?: CronToolDeps): AnyAgentTool {

‎src/auto-reply/reply/dispatch-acp-delivery.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
import type { FinalizedMsgContext } from "../templating.js";
3131
import type { ReplyPayload } from "../types.js";
3232
import { prepareAcpDeliveryPayload } from "./dispatch-acp-payload.js";
33-
import type { NormalizeReplySkipReason } from "./normalize-reply.js";
33+
import type { NormalizeReplySkipReason } from "./normalize-reply-skip-reason.js";
3434
import {
3535
attachReplyDispatchUndeliveredFallback,
3636
captureReplyDispatchDeliveryOutcome,
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Leaf contract for the reply-suppression reason union. Kept import-free so
2+
// downstream owners (cron completion status, command delivery) can reference the
3+
// reason without pulling the heavy normalize-reply module into their type graph
4+
// and forming an import cycle.
5+
export type NormalizeReplySkipReason = "empty" | "silent" | "heartbeat" | "channel_transform";

‎src/auto-reply/reply/normalize-reply.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ import {
2020
stripSilentToken,
2121
} from "../tokens.js";
2222
import type { ReplyPayload } from "../types.js";
23+
import type { NormalizeReplySkipReason } from "./normalize-reply-skip-reason.js";
2324
import {
2425
resolveResponsePrefixTemplate,
2526
type ResponsePrefixContext,
2627
} from "./response-prefix-template.js";
2728

28-
export type NormalizeReplySkipReason = "empty" | "silent" | "heartbeat" | "channel_transform";
29+
export type { NormalizeReplySkipReason } from "./normalize-reply-skip-reason.js";
2930

3031
export type NormalizeReplyOutcome<T = ReplyPayload> =
3132
| { kind: "deliver"; payload: T }

‎src/cli/cron-cli/register.cron-options.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ export function registerCronMutationOptions(command: Command, mode: "add" | "edi
88
.option("--name <name>", "Job name")
99
.option("--display-name <name>", "Human-readable job label")
1010
.option("--description <text>", "Job description")
11-
.option("--delete-after-run", "Delete one-shot job after it succeeds", false)
11+
.option(
12+
"--delete-after-run",
13+
"Delete one-shot after successful completion (confirmed/no delivery, intentional silence, or best effort); failed/unknown required delivery retains it disabled",
14+
false,
15+
)
1216
.option("--keep-after-run", "Keep one-shot job after it succeeds", false)
1317
.option("--agent <id>", "Agent id for this job")
1418
.option("--session <target>", "Session target (main|isolated|current|session:<id>)")

0 commit comments

Comments
 (0)