Skip to content

fix(cron): required delivery failures no longer report success - #126164

Merged
steipete merged 3 commits into
mainfrom
steipete/youthful-yonath-24342a
Aug 19, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/youthful-yonath-24342a

Conversation

@steipete

@steipete steipete commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #126163

What Problem This Solves

Fixes an issue where an automation payload could complete successfully while explicitly required delivery failed, but one-shot cleanup, openclaw cron run --wait, and Gateway completion notifications still treated the whole run as successful. Delete-after-run one-shots could lose their inspectable job record, and adapter-specific handling could incorrectly charge delivery failure to payload execution retry counters.

Why This Change Was Made

Cron finalization now records one durable completionStatus (succeeded, failed, or unknown) from the admitted delivery contract after execution and delivery settle. Payload execution status remains independent, legacy rows fail safely from stored immutable facts, one-shots delete only after successful completion, and CLI/Gateway consumers read the recorded fact rather than mutable job configuration.

This is an additive run-history and plugin-hook field. It does not add a SQLite schema migration, change the Gateway protocol version, add a duplicate job-state field, or replay payload work after delivery failure.

User Impact

Operators can rely on openclaw cron run --wait to fail when explicitly required delivery fails. Default announce delivery remains best-effort. Required-failed one-shots remain disabled and inspectable with no next run, execution retry counters remain execution-only, and Gateway restart does not replay the payload.

AI-assisted implementation; maintainer-reviewed and understood.

Evidence

  • Pre-fix owner-boundary regression set: 18/82 assertions failed for the intended missing completion semantics.
  • Final focused local proof: 403/403 assertions passed across cron finalization, recovery, CLI, Gateway notifications, and adapter behavior.
  • Clean-machine broad cron suite: 178 files, 2,249/2,249 assertions passed.
  • Clean-machine build passed.
  • Exact-path changed gate passed: formatting, core/core-test typecheck, lint, import cycles, database/schema guards, and repository ratchets.
  • Exact-head CI follow-up: pnpm check:architecture, pnpm test:bundled, and pnpm protocol:check pass; generated Swift protocol models include the additive field.
  • Source-blind built CLI/Gateway validation with isolated state and a non-default port:
    • required failing webhook: CLI exit 1, execution ok, completion failed;
    • default failing webhook: CLI exit 0, completion succeeded;
    • required one-shot: one history row, one payload side effect, disabled and retained after restart.
  • Fresh Codex autoreview: no accepted/actionable findings.
  • Blacksmith Testbox: https://github.com/openclaw/openclaw/actions/runs/32197329907

Production LOC: +244/-64 (net +180). Tests: +577/-48. Docs: +6/-4. The production growth is the additive durable completion contract and required task/history/CLI/Gateway propagation; simplification removed divergent adapter policy, repeated delivery normalization, and mutable CLI inference.

Record durable completion independently from payload execution so required delivery failure cannot delete one-shots or report successful waits.\n\nCloses #126163
@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes labels Aug 19, 2026
@steipete
steipete marked this pull request as ready for review August 19, 2026 03:43
@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Aug 19, 2026
@steipete steipete self-assigned this Aug 19, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 19, 2026
@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 18, 2026, 11:52 PM ET / August 19, 2026, 03:52 UTC.

ClawSweeper review

What this changes

The PR adds a durable cron completion outcome so required delivery failures remain distinct from payload execution success across cleanup, CLI waits, task history, Gateway notifications, and plugin hooks.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

No blocking source defect was found in the reviewed head. Keep this active, maintainer-labeled PR open for normal exact-head CI handling and merge review; it is the linked candidate fix for the reported P1 cron completion bug.

Priority: P1
Reviewed head: 3c8c9d37ae59aca38ff8323419ef382f08ab6944

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation is coherent and well-covered, with merge confidence awaiting exact-head CI and current-main refresh.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external contributor proof gate; its body nevertheless records after-fix CLI/Gateway behavior and restart evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external contributor proof gate; its body nevertheless records after-fix CLI/Gateway behavior and restart evidence.
Evidence reviewed 10 items Completion is authored at the run owner: The finalizer derives completion from the admitted job snapshot and resolved delivery state before downstream persistence, preventing later job edits from changing the completed run's meaning.
Scheduled-run caller preserves the admitted snapshot: Queued execution clones the activated job before running it and carries the authored outcome into finalization.
One-shot cleanup consumes completion, not execution alone: Deletion now requires a succeeded completion outcome while execution retry accounting remains based on the execution status.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw cron run --help

Result: PASS (completed)

pnpm openclaw cron run --help
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-126164-6QPRbF/target$ pnpm openclaw cron run --help
$ node scripts/run-node.mjs cron run --help
pnpm openclaw cron run --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 400.66 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 83.34 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.5s
node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

[tsdown-build] invocation 2/2 finished in 11.8s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 3668ms (slowest: built plugin control-plane loads 2817ms)
│
◇

OpenClaw 2026.8.1 (3c8c9d3) — All your chats, one OpenClaw.

Usage: openclaw cron run [options] ‹id›

Run an automation now (debug)

Arguments:
  id                          Job id

Options:
  --due                       Run only when due (default behavior in older versions) (default: false)
  --expect-final              Wait for final response (agent) (default: false)
  -h, --help                  Display help for command
  --json             
… output truncated …

Assertions:

  • PASS expect_output: Run an automation now

How this fits together

Cron executes a payload and then optionally delivers its output. The finalized run record controls CLI exit status, task history, one-shot retention, Gateway notifications, and plugin events.

flowchart LR
A[Cron job] --> B[Payload execution]
B --> C[Delivery result]
C --> D[Durable completion outcome]
D --> E[Task and run history]
D --> F[CLI wait exit]
D --> G[One-shot retention]
D --> H[Gateway and plugin events]
Loading

Before merge

  • Resolve merge risk (P1) - The change adds a persisted and externally observable completion field across run history, Gateway protocol, and plugin hooks; it must remain optional and canonical rather than becoming a parallel mutable status.
  • Resolve merge risk (P1) - The supplied main revision and the failed exact-head check log were unavailable in this partial checkout, so merge should wait for a successful exact-head CI result and a normal base refresh.
  • Complete next step (P2) - This fresh maintainer-owned PR already implements the linked bug; the remaining action is exact-head CI and normal maintainer merge review, not a separate repair job.
Agent review details

Security

None.

PR surface

Source +166, Tests +529, Docs +2. Total +697 across 40 files.

View PR surface stats
Area Files Added Removed Net
Source 23 229 63 +166
Tests 15 577 48 +529
Docs 2 6 4 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 40 812 115 +697

Review metrics

Metric Value Why it matters
Production versus regression coverage production +229/-63 (net +166); tests +577/-48; docs +6/-4 The positive production growth implements one durable completion contract across several consumers and is paired with broad lifecycle regression coverage.
External completion contract 1 optional status field across Gateway run history and plugin hooks Existing protocol and plugin consumers must continue to accept records that lack completionStatus.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/cron/service/startup-run-repair.auto-disable.test.ts, migration/backfill/repair: src/cron/service/startup-run-repair.ts, serialized state: src/cron/service/state.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm the additive completion contract (recommended)
    Before merge, verify the exact head keeps completionStatus optional for legacy history, protocol clients, and plugin hook consumers.
  2. Pause for the failed check
    Hold the PR until the failed exact-head check is understood or rerun successfully, since its log was not available to this review.

Technical review

Best possible solution:

Retain one completion outcome authored from the admitted run snapshot, keep it optional on external contracts, and land after the exact PR head has a green required check set.

Do we have a high-confidence way to reproduce the issue?

Yes, from source and the supplied PR evidence: a successful payload with required delivery returning not-delivered reaches CLI, one-shot, and notification consumers; this read-only review did not execute the scenario.

Is this the best way to solve the issue?

Yes: authoring one durable outcome at the admitted execution boundary is safer than adapter-specific status rewriting or consumer-side inference from mutable job settings.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a441431896b4.

Labels

Label changes:

  • add P1: Required delivery failure can produce a false-success control-flow result and remove the only inspectable one-shot job record.
  • add merge-risk: 🚨 compatibility: The PR adds an optional persisted Gateway run-history and plugin-hook field consumed by existing clients.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external contributor proof gate; its body nevertheless records after-fix CLI/Gateway behavior and restart evidence.

Label justifications:

  • P1: Required delivery failure can produce a false-success control-flow result and remove the only inspectable one-shot job record.
  • merge-risk: 🚨 compatibility: The PR adds an optional persisted Gateway run-history and plugin-hook field consumed by existing clients.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external contributor proof gate; its body nevertheless records after-fix CLI/Gateway behavior and restart evidence.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the linked bug report and the reviewed completion-boundary implementation; deeper pre-PR history was unavailable in this partial checkout. (role: current cron fix owner; confidence: low; commits: 3c8c9d37ae59; files: src/cron/service/timer-job-runner.ts, src/cron/service/timer-outcomes.ts, src/gateway/server-cron.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Resolve or rerun the failed exact-head check before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready verification is complete on head 21ef341f6e39b987aa6e8f80a6ea1fdfd562a6cd.

Proof:

  • Pre-fix focused regressions failed 18/82 for the intended missing completion behavior.
  • Final focused local proof passed 403/403 assertions.
  • Blacksmith Testbox tbx_01m0bk95k69m5wfnzqhnqds68r: broad cron suite passed 178 files / 2,249 assertions; build passed.
  • pnpm check:architecture: zero runtime and Madge cycles.
  • pnpm test:bundled: 205/205 assertions passed.
  • pnpm protocol:check: registry, Swift/Kotlin generation, since guard, and checked-in output passed.
  • Exact-path changed gate passed formatting, core/core-test typecheck, lint, dead-code, import-cycle, database/schema, and ratchet checks.
  • Source-blind built CLI/Gateway proof passed: required failing webhook exited 1 with execution ok / completion failed; default failing webhook exited 0 / completion succeeded; required one-shot retained one history row and one payload side effect across restart.
  • Final Codex autoreview reported no accepted/actionable findings.
  • Exact-head CI is green: https://github.com/openclaw/openclaw/actions/runs/32217379536

ClawSweeper rank-up moves on the completed review were applied: completionStatus remains optional and canonical on external contracts, generated protocol clients are refreshed, the base was refreshed through scripts/pr review-init, and exact-head CI is green. The newer ClawSweeper placeholder has not published a final verdict; per repository policy the queued publisher is not a merge blocker after actionable moves and exact-head gates are complete.

Known proof boundary: delivery failure is exercised with an unreachable loopback webhook rather than an authenticated external channel; this directly tests the cron-owned required-delivery and no-replay contract without external credentials.

@steipete
steipete merged commit 2bcc06c into main Aug 19, 2026
222 checks passed
@steipete
steipete deleted the steipete/youthful-yonath-24342a branch August 19, 2026 05:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 20, 2026
…law#126164)

* fix(cron): preserve required delivery completion

Record durable completion independently from payload execution so required delivery failure cannot delete one-shots or report successful waits.\n\nCloses openclaw#126163

* fix(cron): keep completion contracts acyclic

* fix(cron): keep delivery predicate private
obviyus added a commit that referenced this pull request Oct 1, 2026
## What Problem This Solves

Fixes: a scheduled agent run that could not do its task is recorded as `ok`, so run history, `--wait`, and the configured failure alerts treat it as a success.

In our setup, a monthly isolated job delivered nothing for two months and every receipt said `ok`. One month the turn knew it was blocked (no shell tool) and said so in plain text, but nothing structured recorded that.

## User Impact

- A run can now fail itself. A final reply whose first line is exactly `AUTOMATION_FAILED` records the run as `error`, with the lines that follow as the error text. The existing failure handling then applies: error backoff, plus failure alerts and owner-conversation repair for jobs that already have a failure route or `failureAlert` config.
- Announce jobs still deliver the agent's explanation, with the token removed.
- These stay ok: `NO_REPLY` runs, and replies that mention the token anywhere other than as the exact first line.
- **No change to notification contracts.** An unconfigured `delivery: none` job still sends nothing to chat (no alert, no repair request). It now records the error in run history and job status (`lastRunStatus`, `consecutiveErrors`).

**Not fixed here:**
- A delegated (spawn-only) `delivery: none` run still ends `ok` and drops its child's result. The parent never sees the child's reply, so it can't report that failure with the token. Since #135318, cron turns also can't `sessions_yield`. A separate PR fixes settlement at #117308's spawn-only path.
- Notifying owners of failing `delivery: none` jobs is a pending product decision and is not part of this PR.

## Why This Change Was Made

Provenance:
- #110949 added the unattended-run preamble. It tells the model "If something failed, state plainly what failed … the scheduler owns retries and failure alerts", but no structured fact carried that statement. The scheduler only fails runs on run-level errors, error payloads, or exec-denied tool errors (`failure-signal.ts`, `execution_denied`).
- #126164 and #131228 deliberately keep execution status separate from delivery outcome. This PR keeps that separation: the token is an execution outcome the agent reports. It is parsed in the existing cron outcome owner (`resolveCronPayloadOutcome`), next to `failureSignal`, and is never derived from delivery.

The token is a strict control line, like `NO_REPLY`. Only an exact first line counts, so ordinary prose is never classified. Hermes Agent uses the same mechanism for cron (`[CRON_FAILURE]` on the first line; `cron/scheduler_prompt.py`, `cron/scheduler.py`). The preamble sentence is reworded in place: similar length, still static for prompt caching.

## Bounded cost

New or changed paths that could lead to a model call or a job run:

- **The token parse.** No new turns, runs, or notifications. It only changes the recorded status of the run that produced the reply. It is parsed only in cron finalization for that run. The delivered explanation is outbound text, never inbound, so there is no self-trigger.
- **Error status → scheduler.**
  - One-shot jobs: an agent-reported failure carries `errorClassification: { kind: "permanent" }`, so it never enters the transient-retry path. This also means wording like "network timeout" in the explanation is never text-classified into a retry or an error reason. **Tested** in `run.meta-error-status.test.ts`.
  - Recurring jobs: the existing error backoff only delays the next run (natural schedule or later), and the existing auto-disable stops the job after 10 consecutive errors. Nothing runs sooner than scheduled.
- **Repair turns.** Unchanged. They still happen only for jobs with an existing chat failure route (#161007): at most one per failure incident, and the incident marker is persisted in job state. A repair turn can't start runs, because automation control is owner-only and the request carries no sender identity. It is an ordinary conversation turn, not a cron run, so its own failure can't open another repair.
- **The preamble text.** Static; it adds no turns.

## Evidence

Isolated Gateway, qa-lab mock-openai, new scenario `qa/scenarios/scheduling/cron-blocked-outcome.yaml`:

- **Before** (origin/main): a `delivery: none` job whose reply starts with `AUTOMATION_FAILED` → `status: "ok"`, `completionStatus: "succeeded"`, and the summary holds the blocker text.
- **After:** see the result comment below. The scenario checks:
  - An owned `delivery: none` job, run 3 times → each run is `error` with the reported reason; no repair request and no chat message.
  - An unowned announce job, run twice → `error`; the reason is delivered without the token, and the existing `failed 2 times` alert fires.
  - A mid-text quote, and `NO_REPLY` (with and without announce) → `ok`.

Focused tests (fail before, pass after): `src/cron/isolated-agent/run.meta-error-status.test.ts` covers token → `error` + permanent classification, and a mid-text quote → `ok` (two cases, about 1.7 s each in the shared harness). Also passing: `failure-alerts.{account-routing,persistence,recovery}`, `service.failure-repair`, and `run.message-tool-policy` (116 tests). `pnpm tsgo:core` and oxlint on the changed files are clean. `run.message-tool-policy.test.ts` no longer pins the full preamble wording; it keeps the ordering assertion.

LOC vs origin/main: production +36/−7, unit tests +24/−2, QA scenario and mock about +180, docs +1/−1.


## Upgrade compatibility

No migration is required. The diff touches no schema, store, codec or persisted type file. Run history keeps the existing `CronRunStatus` values (`ok | error | skipped`) and the existing error/permanent classification fields, so rows written before and after this change go through the same unchanged readers. The QA scenario's "repair" wording refers to the scheduler's automation repair request, not a data repair. Existing-state compatibility is verified by the unchanged `failure-alerts.persistence` and `service.failure-repair` suites passing on this head.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
## What Problem This Solves

Fixes: a scheduled agent run that could not do its task is recorded as `ok`, so run history, `--wait`, and the configured failure alerts treat it as a success.

In our setup, a monthly isolated job delivered nothing for two months and every receipt said `ok`. One month the turn knew it was blocked (no shell tool) and said so in plain text, but nothing structured recorded that.

## User Impact

- A run can now fail itself. A final reply whose first line is exactly `AUTOMATION_FAILED` records the run as `error`, with the lines that follow as the error text. The existing failure handling then applies: error backoff, plus failure alerts and owner-conversation repair for jobs that already have a failure route or `failureAlert` config.
- Announce jobs still deliver the agent's explanation, with the token removed.
- These stay ok: `NO_REPLY` runs, and replies that mention the token anywhere other than as the exact first line.
- **No change to notification contracts.** An unconfigured `delivery: none` job still sends nothing to chat (no alert, no repair request). It now records the error in run history and job status (`lastRunStatus`, `consecutiveErrors`).

**Not fixed here:**
- A delegated (spawn-only) `delivery: none` run still ends `ok` and drops its child's result. The parent never sees the child's reply, so it can't report that failure with the token. Since openclaw#135318, cron turns also can't `sessions_yield`. A separate PR fixes settlement at openclaw#117308's spawn-only path.
- Notifying owners of failing `delivery: none` jobs is a pending product decision and is not part of this PR.

## Why This Change Was Made

Provenance:
- openclaw#110949 added the unattended-run preamble. It tells the model "If something failed, state plainly what failed … the scheduler owns retries and failure alerts", but no structured fact carried that statement. The scheduler only fails runs on run-level errors, error payloads, or exec-denied tool errors (`failure-signal.ts`, `execution_denied`).
- openclaw#126164 and openclaw#131228 deliberately keep execution status separate from delivery outcome. This PR keeps that separation: the token is an execution outcome the agent reports. It is parsed in the existing cron outcome owner (`resolveCronPayloadOutcome`), next to `failureSignal`, and is never derived from delivery.

The token is a strict control line, like `NO_REPLY`. Only an exact first line counts, so ordinary prose is never classified. Hermes Agent uses the same mechanism for cron (`[CRON_FAILURE]` on the first line; `cron/scheduler_prompt.py`, `cron/scheduler.py`). The preamble sentence is reworded in place: similar length, still static for prompt caching.

## Bounded cost

New or changed paths that could lead to a model call or a job run:

- **The token parse.** No new turns, runs, or notifications. It only changes the recorded status of the run that produced the reply. It is parsed only in cron finalization for that run. The delivered explanation is outbound text, never inbound, so there is no self-trigger.
- **Error status → scheduler.**
  - One-shot jobs: an agent-reported failure carries `errorClassification: { kind: "permanent" }`, so it never enters the transient-retry path. This also means wording like "network timeout" in the explanation is never text-classified into a retry or an error reason. **Tested** in `run.meta-error-status.test.ts`.
  - Recurring jobs: the existing error backoff only delays the next run (natural schedule or later), and the existing auto-disable stops the job after 10 consecutive errors. Nothing runs sooner than scheduled.
- **Repair turns.** Unchanged. They still happen only for jobs with an existing chat failure route (openclaw#161007): at most one per failure incident, and the incident marker is persisted in job state. A repair turn can't start runs, because automation control is owner-only and the request carries no sender identity. It is an ordinary conversation turn, not a cron run, so its own failure can't open another repair.
- **The preamble text.** Static; it adds no turns.

## Evidence

Isolated Gateway, qa-lab mock-openai, new scenario `qa/scenarios/scheduling/cron-blocked-outcome.yaml`:

- **Before** (origin/main): a `delivery: none` job whose reply starts with `AUTOMATION_FAILED` → `status: "ok"`, `completionStatus: "succeeded"`, and the summary holds the blocker text.
- **After:** see the result comment below. The scenario checks:
  - An owned `delivery: none` job, run 3 times → each run is `error` with the reported reason; no repair request and no chat message.
  - An unowned announce job, run twice → `error`; the reason is delivered without the token, and the existing `failed 2 times` alert fires.
  - A mid-text quote, and `NO_REPLY` (with and without announce) → `ok`.

Focused tests (fail before, pass after): `src/cron/isolated-agent/run.meta-error-status.test.ts` covers token → `error` + permanent classification, and a mid-text quote → `ok` (two cases, about 1.7 s each in the shared harness). Also passing: `failure-alerts.{account-routing,persistence,recovery}`, `service.failure-repair`, and `run.message-tool-policy` (116 tests). `pnpm tsgo:core` and oxlint on the changed files are clean. `run.message-tool-policy.test.ts` no longer pins the full preamble wording; it keeps the ordering assertion.

LOC vs origin/main: production +36/−7, unit tests +24/−2, QA scenario and mock about +180, docs +1/−1.


## Upgrade compatibility

No migration is required. The diff touches no schema, store, codec or persisted type file. Run history keeps the existing `CronRunStatus` values (`ok | error | skipped`) and the existing error/permanent classification fields, so rows written before and after this change go through the same unchanged readers. The QA scenario's "repair" wording refers to the scheduler's automation repair request, not a data repair. Existing-state compatibility is verified by the unchanged `failure-alerts.persistence` and `service.failure-repair` suites passing on this head.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Required cron delivery failure can report successful completion

1 participant