Skip to content

fix(cron): recover automations after plugin reloads - #146582

Merged
steipete merged 4 commits into
mainfrom
codex/automation-plugin-reload-recovery
Sep 13, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/automation-plugin-reload-recovery

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Script automations can keep a retired plugin runtime after a hot reload, fail before running, and repeatedly notify operators with an opaque internal-error message.

User Impact

Automations refresh stale plugin setup once before execution. If recovery fails, the alert explains that tools could not be refreshed and the script did not run. Repeated failures with the same cause and destination stay grouped into one incident across restarts; a changed cause or destination can alert after the existing cooldown, and confirmed success sends one recovery notice.

Unknown delivery outcomes and healthy trigger checks do not falsely clear failed payload work. The existing automatic-disable notification remains a separate material change. No new configuration, SQL schema version, permissions, or migration is required; existing jobs acquire incident metadata on their next failed check or run.

Why This Change Was Made

Script preparation now follows the plugin owner's lifecycle authority. Cache retirement and retirement during setup share one recovery budget, the original deadline, and the same admitted run. Script execution remains outside the retry path so tool effects are never replayed by setup recovery.

The scheduler owns incident state and notification settlement in the existing job record. Startup reconciles saved outcomes without replaying historical notifications, including when terminal task history survived a failed job-row write. Each notification has an internal identity so a delayed transport result cannot overwrite a newer failure or recovery, even when timestamps coincide. Raw errors remain in run history; chat alerts use closed failure facts.

Evidence

  • Reproduced retired cached tools, retirement during admission/setup, and failed cached-runtime refreshes before the fix; the new boundary regressions pass afterward.
  • Focused suites across script execution/admission, plugin lifecycle, alert routing, persistence, incident transitions, and public projection passed, including the affected reruns after review fixes (110 script/persistence tests plus the final 160 alert and startup-recovery tests).
  • Independent review is clean at P2 and above. A full build passed on the implementation commit. Final changed checks passed (format, core and test types, lint, schema and ownership guards, and zero runtime import cycles). The existing Gateway reload test now asserts the new retired-plugin class and unchanged literal message; all 67 Gateway reload cases passed. Required CI passed on d2bc98e: CI run.
  • Existing-install compatibility: the SQLite cron row codec and schema are byte-identical to v2026.9.4. Both fields are optional runtime metadata in existing state_json; the real SQLite tests begin with ordinary jobs lacking the fields, write them during failure handling, reopen the store, and verify recovery. Public job projection strips both fields. No migration or backfill is required.
  • Integration CI also exposed an upstream upgrade-fixture mismatch introduced by improve(msteams): reduce repeated reads during poll cleanup #146575. This branch reuses the existing one-line correction from commit 752e4ec on fix: speed up repeated visualization loads #146602; all 18 upgrade-registry tests passed. The automation commits are patch-identical after rebasing.
  • Validation uses isolated fixtures; no operator Gateway was restarted or modified.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L maintainer Maintainer-authored PR labels Sep 13, 2026
@steipete
steipete marked this pull request as ready for review September 13, 2026 00:09
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 9:18 PM ET / September 13, 2026, 01:18 UTC (Revision 4).

ClawSweeper review

What this changes

Refreshes retired plugin tools before automation scripts start, groups repeated failure alerts into persistent incidents, and sends recovery notices after confirmed success.

Merge readiness

⛔ Blocked before merge - 1 item remains

The fix remains useful on current main. The earlier startup-recovery finding is addressed, and the supplied compatibility evidence resolves the previous upgrade concern. No blocking defect was found in the pinned patch.

Priority: P2
Reviewed head: d2bc98e7cc633a1e23ee8195f3a7f8d1987b2403

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-level repair with meaningful regression coverage and the previous recovery and compatibility concerns addressed.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository context identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Inspected tests exercise the production script runner and SQLite incident owner with injected retirement and persistence failures; reported passes are supplemental evidence, not a claimed live deployment run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository context identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Inspected tests exercise the production script runner and SQLite incident owner with injected retirement and persistence failures; reported passes are supplemental evidence, not a claimed live deployment run.
Evidence reviewed 8 items Current main still needs the repair: Current main caches script preparation by configuration, agent, and tool policy without checking plugin lifecycle freshness. Its failure-alert owner still uses cooldown-only suppression.
Bounded setup recovery: The introduced loop checks the plugin owner's lifecycle, retains one admitted run and deadline, and retries preparation once. Script execution remains outside that loop; existing final tool-execution authority checks remain intact.
Earlier recovery finding addressed: Startup replay now reconciles incident state without historical notifications. The regression exercises successful task history surviving a rejected SQLite job-row update, restores that success, and verifies that the same subsequent failure can alert again.
Findings None None.
Security None None.

How this fits together

The automation scheduler runs configured scripts using tools supplied by the plugin runtime. It saves execution outcomes and incident state in SQLite, then sends notifications through the existing Gateway delivery service.

flowchart TD
  A[Scheduled automation] --> B[Prepare plugin tools]
  B --> C{Tools still current?}
  C -->|No| D[Refresh setup once]
  D --> C
  C -->|Yes| E[Run script within original deadline]
  E --> F[Persist outcome and incident]
  F --> G[Send failure or recovery notice]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +240, Tests +619, Docs +14. Total +873 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 10 327 87 +240
Tests 9 754 135 +619
Docs 3 16 2 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 1097 224 +873

Review metrics

Metric Value Why it matters
Production versus regression coverage production +240 net lines; tests and test support +619 net lines Production growth implements bounded preparation recovery, durable incidents, and settlement fencing; the larger test delta covers their failure and restart paths.
Stored compatibility surface 2 optional private state fields; 0 SQL schema changes; 0 new settings Existing jobs acquire metadata through the unchanged state_json codec without a migration or configuration rewrite.

Stored data model

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

Technical review

Best possible solution:

Keep preparation freshness with the plugin lifecycle owner and incident recovery with the existing scheduler, preserving one execution admission and durable notification settlement.

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

Yes, from source: retire a cached plugin runtime while configuration identity stays unchanged, then execute the automation again. Current main reuses the stale preparation; inspected regressions cover this trigger, but this review did not execute them.

Is this the best way to solve the issue?

Yes. The patch extends the existing lifecycle and scheduler owners, limits recovery to setup, and supplies focused persistence coverage for the additive incident metadata.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5a4be1fad6da.

Labels

Label changes:

  • add proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Automation alerts routed to Telegram gain recovery messages and changed failure text that are observable in chat.

Label justifications:

  • P2: Repairs automation failures after plugin reloads and repeated operator alerts within a bounded scheduler surface.
  • 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: The supplied repository context identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Inspected tests exercise the production script runner and SQLite incident owner with injected retirement and persistence failures; reported passes are supplemental evidence, not a claimed live deployment run.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Automation alerts routed to Telegram gain recovery messages and changed failure text that are observable in chat.

Evidence

What I checked:

  • Current main still needs the repair: Current main caches script preparation by configuration, agent, and tool policy without checking plugin lifecycle freshness. Its failure-alert owner still uses cooldown-only suppression. (src/cron/trigger-script.ts:283, 5a4be1fad6da)
  • Bounded setup recovery: The introduced loop checks the plugin owner's lifecycle, retains one admitted run and deadline, and retries preparation once. Script execution remains outside that loop; existing final tool-execution authority checks remain intact. (src/cron/trigger-script.ts:408, d2bc98e7cc63)
  • Earlier recovery finding addressed: Startup replay now reconciles incident state without historical notifications. The regression exercises successful task history surviving a rejected SQLite job-row update, restores that success, and verifies that the same subsequent failure can alert again. (src/cron/service/failure-alerts.recovery.test.ts:63, d2bc98e7cc63)
  • Existing-install compatibility: The release and PR trees contain identical row-codec and schema blobs: 884e05427978db3ae610c3a4cc3cbddf707c0fc0 and a94abc4e33ea9e466a375ba4bdb11aff3ba4d0e0. The existing state_json codec preserves optional metadata, and public projection removes both private fields. (src/cron/store/row-codec.ts, d2bc98e7cc63)
  • Persistence and notification coverage: Inspected tests begin with jobs lacking incident metadata, persist failures, reload the store past cooldown, and verify suppression and recovery. Additional cases preserve unresolved payload failures through quiet trigger checks and reject stale notification settlement. (src/cron/service/failure-alerts.persistence.test.ts:441, d2bc98e7cc63)
  • Production entrypoint and implementation boundary: Gateway construction supplies the prepared plugin registry to the cron script runtime, and runScriptJob calls its payload executor. The script runner imports OpenClaw's own headless Code Mode implementation; the changed behavior does not depend on the Codex harness. (src/gateway/server-cron.ts:587, d2bc98e7cc63)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-13T00:16:40.580Z sha 41d9c8926906ca562af63fb9173f391767256c4d :: blocked before merge. :: [P2] Reconcile incident state when replaying finalized runs
  • reviewed 2026-09-13T00:37:46.888Z sha 4353203792291f542d5e9b5a0c43bf9a9b02fca4 :: blocked before merge. :: none
  • reviewed 2026-09-13T00:58:34.085Z sha 17370acaf84ac6582e970ba82742434b3d5eafbc :: blocked before merge. :: none

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed startup incident reconciliation in 4353203792291f542d5e9b5a0c43bf9a9b02fca4. Saved success clears the incident without replaying notifications; quiet trigger replay is also silent, and incomplete historical failures retain conservative recovery scope. The regression reproduces terminal success surviving a failed SQLite job-row write, startup restoration, and immediate recurrence of the same failure. All 160 alert and recovery tests passed. The lint failures are fixed as well.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Sep 13, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The remaining CI assertion now checks the intentional retired-plugin error type and the unchanged literal message. All 67 Gateway reload tests passed; the final focused memory cases and independent review passed too. Local changed checks are green.

Existing-install compatibility is covered by the SQLite persistence/recovery tests: they start with ordinary jobs without incident metadata, write the optional fields, reopen the store, and verify suppression and recovery, including interrupted row persistence. The cron row codec and SQL schema are byte-identical to v2026.9.4 (git diff --exit-code v2026.9.4 -- src/cron/store/row-codec.ts src/cron/store/schema.ts passes). The codec reads and writes the existing state_json object, and public projection strips the two private fields. No SQL migration or backfill is needed. The PR body now records this evidence.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Refresh retired script preparation once before execution, preserving the admitted run and deadline. Report failed setup recovery with a closed actionable cause. Group repeated failures into durable incidents and announce only verified recovery, preserving unresolved payload failures across quiet trigger checks.
Restore incident state from durable completed runs without replaying historical notifications, including quiet trigger checks. Keep recovered notification traces from reopening the failure cooldown. Cover failed job-row writes followed by restart and recurrence. Extract existing fixtures and event helpers to retain lint limits.
@steipete
steipete force-pushed the codex/automation-plugin-reload-recovery branch from 17370ac to d2bc98e Compare September 13, 2026 01:09
@clawsweeper clawsweeper Bot added the proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. label Sep 13, 2026
@steipete
steipete merged commit 5c81503 into main Sep 13, 2026
195 checks passed
@steipete
steipete deleted the codex/automation-plugin-reload-recovery branch September 13, 2026 01:29
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
* fix(cron): recover automations after plugin reloads

Refresh retired script preparation once before execution, preserving the admitted run and deadline. Report failed setup recovery with a closed actionable cause. Group repeated failures into durable incidents and announce only verified recovery, preserving unresolved payload failures across quiet trigger checks.

* fix(cron): reconcile alert incidents during restart recovery

Restore incident state from durable completed runs without replaying historical notifications, including quiet trigger checks. Keep recovered notification traces from reopening the failure cooldown. Cover failed job-row writes followed by restart and recurrence. Extract existing fixtures and event helpers to retain lint limits.

* test(gateway): expect typed plugin retirement errors

* test: match explicit plugin argument in upgrade fixture
obviyus added a commit that referenced this pull request Sep 30, 2026
…efore alerting (#161007)

## What Problem This Solves

When a scheduled automation keeps failing, OpenClaw posts "Automation X failed N times" to the chat and waits for the user to ask for a fix, even when the fix is something the agent in the conversation that created the job could make itself.

## User Impact

When a job created from a conversation (it has an owner session) reaches its failure-alert threshold (default: 2 failures in a row, same cooldown and incident dedupe), OpenClaw sends one repair request to that owner conversation instead of the first chat alert. The conversation handles it as an ordinary agent turn, as if it had received a message: its own session and transcript, its workspace, its normal tool policy, and its reply goes to that conversation's own route (chat, thread or forum topic). The request tells it to:

- fix the problem in the workspace if it can (for example the helper script or instructions file the job follows) and say what it fixed in one line;
- otherwise ask the user for exactly what it needs;
- say nothing if the failure was transient.

Heartbeat settings do not apply to the repair: `heartbeat.target: "none"`, `isolatedSession`, `lightContext` and `activeHours` do not route, isolate, trim or hold it, and it carries no first-heartbeat notice.

The normal alert is still sent when the job has no owner conversation, for operator-only jobs (command payloads, on-exit and stream schedules), for webhook alert routes, and when the job fails again after the repair request (once, noting that a repair was requested). A successful run clears the streak silently.

**Upgrade behavior change (intentional):** repair is on by default. Opt-out is per job: `failureAlert: false` disables both the repair request and the alert. No config key is added. The chat "Automation … recovered" notice is removed; recovery stays in automation history. This reverses the notice added in #146582.

## Why This Change Was Made

The owner conversation is where these jobs get fixed in practice: in our setup a user had to reply "just fix it" to a failure notice, and the agent in that conversation then repaired the job. This change starts that step automatically.

The repair is dispatched through the Gateway's existing `agent` method on the instance's lifecycle principal (`dispatchGatewayLifecycleMethod`, the same owner restart-sentinel continuations and exec-approval follow-ups use), with the owner `sessionKey` and `deliver: true`, so the agent method resolves the reply route from that session's stored delivery context, thread included. The cron service reaches it through one injected dependency (`runCronFailureRepair`, wired in `server-cron.ts`), so `src/cron` does not import Gateway code. Nothing in the `sessions_send` tool needed extracting: its default path also calls `agent`, but with `deliver: false` plus its own announce flow, which is what this does not want.

An earlier revision carried the request on a heartbeat wake (system event plus `requestHeartbeat`) and patched the result with a `heartbeat: { target: "last" }` override. That made the repair inherit heartbeat behavior it should not have: an isolated `:heartbeat` side session without the conversation's transcript, light context, the internal-handling prompt, and heartbeat routing. This revision removes that path (system event, heartbeat wake, override, and their docs and tests); heartbeat behavior is unchanged for everything else.

**Tradeoffs (maintainer decisions):**
- The request is scheduler-authored, not a user message: it runs on the Gateway's system principal with `internal_system` provenance (`sourceTool: "cron_failure_repair"`), so it carries no sender-owner identity. Under the existing trust model the turn gets the conversation's normal non-owner tool policy (workspace and exec tools, not owner-only control tools such as `automations`); a change to the job itself goes through the user's reply turn. No new authority plumbing.
- The job's name, payload and last error are wrapped as untrusted data in the request.
- The request goes to the job's owner at dispatch time. If it is lost (the job was removed in between, or the `agent` dispatch rejects), nothing extra is sent at that moment; the job's next failure sends the normal alert naming the repair.
- A repair reply is posted at any hour, like the failure alert it replaces.

Persisted state: the incident gains an optional `repair: { atMs }` marker. It means "this incident's first alert became a repair request". It survives restarts, and the next alert of that incident clears it.

## Evidence

- **Size vs `origin/main`** (merge base `accde9e31a9`, head `435e097ee7c`): production +233/−85 (net +148), docs +14/−4, tests/QA +649/−49; 21 files. To stay within the line-cap ratchet, the Gateway dispatch lives in `server-cron-notifications.ts` next to the failure-alert transport (2 lines of wiring in `server-cron.ts`), `reconcileCronExitWatchers` moved to `cron-exit-watchers.ts`, and two input helpers moved from the qa-lab mock server to `mock-openai-input.ts`.
- **Our production shape, Telegram Test Server forum topic, live OpenAI model** (`telegram-e2e-userbot`, Convex-leased credential, the lease's forum supergroup with a run-owned topic created before recording and deleted after; fresh isolated gateway from this checkout via `--source-gateway` on ports 19951/19952; provider slot = logging proxy to the OpenAI API). Config mirrors ours: `agents.defaults.heartbeat = { every: "1h", activeHours: 08:00–23:00 Asia/Kolkata, target: "none", directPolicy: "allow", to: <the tester's DM>, lightContext: true, isolatedSession: true }`, `cron.failureAlert` and `messages` unset. The QA user posts in the topic, which creates the owner conversation `agent:main:telegram:group:<forum>:topic:<n>`. A command action seeds `scripts/meeting-sync.md` (step 1: `sleep 150`), adds an isolated agentTurn job "Meeting sync" owned by that topic and announcing to it (`timeoutSeconds: 45`), and force-runs it twice: both time out (`consecutiveErrors: 2`, notification status `not-requested`).
  - Command (secrets omitted): `E2E_MOCK_SERVER_PATH=<logging proxy to the OpenAI API> E2E_ROOT_CONFIG_PATCH=<live model + the heartbeat block above, messages: null> node <runner with forum-topic setup hooks> --backend mock --source-gateway --gateway-port 19951 --mock-port 19952 --chat <lease forum> --scenario <scenario> --timeout-ms 1000000 --record events.ndjson --output summary.json` → exit 0.
  - Topic timeline (all messages):
    | Elapsed | Topic message (SUT unless noted) |
    |---|---|
    | 0.8 s | user: `Hi! This topic owns our hourly sync automations. Reply with one short sentence confirming you are here.` |
    | 61 s | `I’m here in this topic for your hourly sync automations.` |
    | 272 s | `Fixed scripts/meeting-sync.md by removing the 150-second wait that exceeded the automation’s 45-second timeout.` (the repair turn) |
    | 393 s | `Sync: 3 new meetings.` (third run, `ok`, `consecutiveErrors: 0`) |
    | 514 s | `Automation "Calendar sync" failed 2 times` / `Cause: timeout` / `Run started: …` (the unowned control's alert) |
    | 620 s | user: `What did you change in the meeting sync automation earlier? One sentence.` |
    | 651 s | `I updated scripts/meeting-sync.md to read the CSV immediately instead of waiting 150 seconds, which exceeded the automation’s 45-second timeout; the schedule stayed unchanged.` |
  - The repair ran in the topic session itself: `chat.history` of `agent:main:telegram:group:<forum>:topic:<n>` holds, in order, the owner-ready exchange, the repair request (user role, `internal_system`), `read` → `exec` → `exec` → `edit scripts/meeting-sync.md` → `exec`, the one-line reply, the next run's result, and the follow-up exchange. No `…:topic:<n>:heartbeat` session exists (sessions list). Its 6 main-model requests carried the brief with the topic's ordinary tool surface. The step file changed about 30 s after the second failure.
  - No `Automation "Meeting sync" failed …` alert and no `First heartbeat alert` text anywhere (7 SUT messages). Control: an unowned job "Calendar sync" with the same broken step fails twice and alerts (delivery status `delivered`); its step file stays unchanged. The provider log also shows one `NO_REPLY` turn without the brief right after the repair's `exec` calls that sent nothing.
- **Telegram Test Server DM owner, live OpenAI model, `activeHours` excluding now** (same harness with `--dm`, window 06:00–07:00 Asia/Kolkata at 21:06 IST, otherwise the same heartbeat block). The DM creates the owner conversation `agent:main:main`; the same owned job fails twice (timeouts). DM timeline: 29.5 s `I’m here in the chat that owns your hourly meeting sync automation.`, 310.8 s `Fixed meeting sync’s timeout by replacing its 150-second blocking wait with a nonblocking export-readiness check.` (the repair turn; it chose to delegate the edit to a subagent via `sessions_spawn`/`sessions_yield`), 339.1 s `Sync: 3 new meetings.` (third run `ok`). The repair request and reply are in `agent:main:main`'s transcript; no alert, no onboarding notice, 3 SUT messages.
- **Regression test** (`src/gateway/server.cron-failure-repair.test.ts`, new file, "repairs an owned job with an ordinary owner-topic turn whatever the heartbeat config"; 4.3–5.8 s): a real Gateway with its real cron service and `agent` method (agent command mocked at the runtime boundary), heartbeat `target: "none"`, `isolatedSession`, `lightContext` and an `activeHours` window that excludes now; an owned job owned by a Telegram topic session fails twice; the agent command runs once in `agent:main:telegram:group:<g>:topic:42` with `deliver: true`, `channel: "telegram"`, `to: <g>`, `threadId: 42` and the repair request as its message, and no announce is sent. Fails on the previous head (no agent run).
- **qa-lab end to end** (`cron-failure-repair-owner-conversation`, real gateway child, qa-channel, mock-openai, isolated state): `OPENCLAW_BUILD_PRIVATE_QA=1 OPENCLAW_ENABLE_PRIVATE_QA_CLI=1 pnpm openclaw --profile <isolated> qa suite --provider-mode mock-openai --scenario cron-failure-repair-owner-conversation` → `passed=1 failed=0`. An owned job fails twice and no alert is sent; the owner conversation receives the repair request, its ordinary turn fixes the workspace step file (`write`), the reply lands in that conversation, and the request and reply are in the owner session's own `chat.history`. Control: an unowned job with the same failures alerts, and the repaired job never does.
- **Service tests** (`src/cron/service.failure-repair.test.ts`, 11 tests): threshold → one `runCronFailureRepair` request to the owner session (no system event, no heartbeat wake) and no alert; the job's name, payload and error sit only inside `<untrusted-text>`; the next failure sends one alert naming the repair, later failures nothing more and never a second repair; a rejected repair request alerts on the next failure; success clears the incident silently; no owner → the old alert; agentTurn, systemEvent and script jobs repair, command jobs and on-exit or stream schedules alert. The heartbeat-route case in `src/cron/service.wake-now-real-heartbeat.test.ts` is removed (the file is back to `main`).
- On `435e097ee7c`: `node scripts/check-changed.mjs` exit 0 (line-cap ratchet, all tsgo shards, lint, import cycles, dead exports); cron repair/alert/persistence/real-heartbeat, gateway cron, cron-exit-watchers, server-cron, notifications and qa-lab mock-openai suites pass (30 files, 538 tests); `pnpm config:docs:check` is clean.
- **Existing-state upgrade (recorded on an earlier head, harness not kept):** published `[email protected]` created an owner session, an owned and an unowned agentTurn job with an announce failure route and each job's first failure; its own `openclaw update --tag <candidate tarball>` succeeded and both streaks and owners survived; one more failure each reached the threshold: the owned job's incident gained `repair: {atMs}` with delivery status `not-requested` and its repair request reached the model; the unowned job alerted. The persisted state is unchanged by this rework.
- **Config compatibility:** no config key is added or changed (`config:docs:check` OK). The behavior change is the default for owned chat-alerting jobs, documented above; per-job `failureAlert: false` opts out.
  - Downgrade: a persisted `repair` marker is an extra field older releases ignore; an incident that was mid-repair at downgrade keeps its signature there, so the older release dedupes that same-cause failure (no new alert until the cause changes or the job recovers), as it does for any already-alerted incident.
- **Owner boundary:** `owner` is fixed at creation (`CronJobPatch` omits it), so it cannot be reassigned; dispatch reads the live job and sends nothing if the job is gone.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 1, 2026
…efore alerting (openclaw#161007)

## What Problem This Solves

When a scheduled automation keeps failing, OpenClaw posts "Automation X failed N times" to the chat and waits for the user to ask for a fix, even when the fix is something the agent in the conversation that created the job could make itself.

## User Impact

When a job created from a conversation (it has an owner session) reaches its failure-alert threshold (default: 2 failures in a row, same cooldown and incident dedupe), OpenClaw sends one repair request to that owner conversation instead of the first chat alert. The conversation handles it as an ordinary agent turn, as if it had received a message: its own session and transcript, its workspace, its normal tool policy, and its reply goes to that conversation's own route (chat, thread or forum topic). The request tells it to:

- fix the problem in the workspace if it can (for example the helper script or instructions file the job follows) and say what it fixed in one line;
- otherwise ask the user for exactly what it needs;
- say nothing if the failure was transient.

Heartbeat settings do not apply to the repair: `heartbeat.target: "none"`, `isolatedSession`, `lightContext` and `activeHours` do not route, isolate, trim or hold it, and it carries no first-heartbeat notice.

The normal alert is still sent when the job has no owner conversation, for operator-only jobs (command payloads, on-exit and stream schedules), for webhook alert routes, and when the job fails again after the repair request (once, noting that a repair was requested). A successful run clears the streak silently.

**Upgrade behavior change (intentional):** repair is on by default. Opt-out is per job: `failureAlert: false` disables both the repair request and the alert. No config key is added. The chat "Automation … recovered" notice is removed; recovery stays in automation history. This reverses the notice added in openclaw#146582.

## Why This Change Was Made

The owner conversation is where these jobs get fixed in practice: in our setup a user had to reply "just fix it" to a failure notice, and the agent in that conversation then repaired the job. This change starts that step automatically.

The repair is dispatched through the Gateway's existing `agent` method on the instance's lifecycle principal (`dispatchGatewayLifecycleMethod`, the same owner restart-sentinel continuations and exec-approval follow-ups use), with the owner `sessionKey` and `deliver: true`, so the agent method resolves the reply route from that session's stored delivery context, thread included. The cron service reaches it through one injected dependency (`runCronFailureRepair`, wired in `server-cron.ts`), so `src/cron` does not import Gateway code. Nothing in the `sessions_send` tool needed extracting: its default path also calls `agent`, but with `deliver: false` plus its own announce flow, which is what this does not want.

An earlier revision carried the request on a heartbeat wake (system event plus `requestHeartbeat`) and patched the result with a `heartbeat: { target: "last" }` override. That made the repair inherit heartbeat behavior it should not have: an isolated `:heartbeat` side session without the conversation's transcript, light context, the internal-handling prompt, and heartbeat routing. This revision removes that path (system event, heartbeat wake, override, and their docs and tests); heartbeat behavior is unchanged for everything else.

**Tradeoffs (maintainer decisions):**
- The request is scheduler-authored, not a user message: it runs on the Gateway's system principal with `internal_system` provenance (`sourceTool: "cron_failure_repair"`), so it carries no sender-owner identity. Under the existing trust model the turn gets the conversation's normal non-owner tool policy (workspace and exec tools, not owner-only control tools such as `automations`); a change to the job itself goes through the user's reply turn. No new authority plumbing.
- The job's name, payload and last error are wrapped as untrusted data in the request.
- The request goes to the job's owner at dispatch time. If it is lost (the job was removed in between, or the `agent` dispatch rejects), nothing extra is sent at that moment; the job's next failure sends the normal alert naming the repair.
- A repair reply is posted at any hour, like the failure alert it replaces.

Persisted state: the incident gains an optional `repair: { atMs }` marker. It means "this incident's first alert became a repair request". It survives restarts, and the next alert of that incident clears it.

## Evidence

- **Size vs `origin/main`** (merge base `76d4f2b9c08`, head `435e097ee7c`): production +233/−85 (net +148), docs +14/−4, tests/QA +649/−49; 21 files. To stay within the line-cap ratchet, the Gateway dispatch lives in `server-cron-notifications.ts` next to the failure-alert transport (2 lines of wiring in `server-cron.ts`), `reconcileCronExitWatchers` moved to `cron-exit-watchers.ts`, and two input helpers moved from the qa-lab mock server to `mock-openai-input.ts`.
- **Our production shape, Telegram Test Server forum topic, live OpenAI model** (`telegram-e2e-userbot`, Convex-leased credential, the lease's forum supergroup with a run-owned topic created before recording and deleted after; fresh isolated gateway from this checkout via `--source-gateway` on ports 19951/19952; provider slot = logging proxy to the OpenAI API). Config mirrors ours: `agents.defaults.heartbeat = { every: "1h", activeHours: 08:00–23:00 Asia/Kolkata, target: "none", directPolicy: "allow", to: <the tester's DM>, lightContext: true, isolatedSession: true }`, `cron.failureAlert` and `messages` unset. The QA user posts in the topic, which creates the owner conversation `agent:main:telegram:group:<forum>:topic:<n>`. A command action seeds `scripts/meeting-sync.md` (step 1: `sleep 150`), adds an isolated agentTurn job "Meeting sync" owned by that topic and announcing to it (`timeoutSeconds: 45`), and force-runs it twice: both time out (`consecutiveErrors: 2`, notification status `not-requested`).
  - Command (secrets omitted): `E2E_MOCK_SERVER_PATH=<logging proxy to the OpenAI API> E2E_ROOT_CONFIG_PATCH=<live model + the heartbeat block above, messages: null> node <runner with forum-topic setup hooks> --backend mock --source-gateway --gateway-port 19951 --mock-port 19952 --chat <lease forum> --scenario <scenario> --timeout-ms 1000000 --record events.ndjson --output summary.json` → exit 0.
  - Topic timeline (all messages):
    | Elapsed | Topic message (SUT unless noted) |
    |---|---|
    | 0.8 s | user: `Hi! This topic owns our hourly sync automations. Reply with one short sentence confirming you are here.` |
    | 61 s | `I’m here in this topic for your hourly sync automations.` |
    | 272 s | `Fixed scripts/meeting-sync.md by removing the 150-second wait that exceeded the automation’s 45-second timeout.` (the repair turn) |
    | 393 s | `Sync: 3 new meetings.` (third run, `ok`, `consecutiveErrors: 0`) |
    | 514 s | `Automation "Calendar sync" failed 2 times` / `Cause: timeout` / `Run started: …` (the unowned control's alert) |
    | 620 s | user: `What did you change in the meeting sync automation earlier? One sentence.` |
    | 651 s | `I updated scripts/meeting-sync.md to read the CSV immediately instead of waiting 150 seconds, which exceeded the automation’s 45-second timeout; the schedule stayed unchanged.` |
  - The repair ran in the topic session itself: `chat.history` of `agent:main:telegram:group:<forum>:topic:<n>` holds, in order, the owner-ready exchange, the repair request (user role, `internal_system`), `read` → `exec` → `exec` → `edit scripts/meeting-sync.md` → `exec`, the one-line reply, the next run's result, and the follow-up exchange. No `…:topic:<n>:heartbeat` session exists (sessions list). Its 6 main-model requests carried the brief with the topic's ordinary tool surface. The step file changed about 30 s after the second failure.
  - No `Automation "Meeting sync" failed …` alert and no `First heartbeat alert` text anywhere (7 SUT messages). Control: an unowned job "Calendar sync" with the same broken step fails twice and alerts (delivery status `delivered`); its step file stays unchanged. The provider log also shows one `NO_REPLY` turn without the brief right after the repair's `exec` calls that sent nothing.
- **Telegram Test Server DM owner, live OpenAI model, `activeHours` excluding now** (same harness with `--dm`, window 06:00–07:00 Asia/Kolkata at 21:06 IST, otherwise the same heartbeat block). The DM creates the owner conversation `agent:main:main`; the same owned job fails twice (timeouts). DM timeline: 29.5 s `I’m here in the chat that owns your hourly meeting sync automation.`, 310.8 s `Fixed meeting sync’s timeout by replacing its 150-second blocking wait with a nonblocking export-readiness check.` (the repair turn; it chose to delegate the edit to a subagent via `sessions_spawn`/`sessions_yield`), 339.1 s `Sync: 3 new meetings.` (third run `ok`). The repair request and reply are in `agent:main:main`'s transcript; no alert, no onboarding notice, 3 SUT messages.
- **Regression test** (`src/gateway/server.cron-failure-repair.test.ts`, new file, "repairs an owned job with an ordinary owner-topic turn whatever the heartbeat config"; 4.3–5.8 s): a real Gateway with its real cron service and `agent` method (agent command mocked at the runtime boundary), heartbeat `target: "none"`, `isolatedSession`, `lightContext` and an `activeHours` window that excludes now; an owned job owned by a Telegram topic session fails twice; the agent command runs once in `agent:main:telegram:group:<g>:topic:42` with `deliver: true`, `channel: "telegram"`, `to: <g>`, `threadId: 42` and the repair request as its message, and no announce is sent. Fails on the previous head (no agent run).
- **qa-lab end to end** (`cron-failure-repair-owner-conversation`, real gateway child, qa-channel, mock-openai, isolated state): `OPENCLAW_BUILD_PRIVATE_QA=1 OPENCLAW_ENABLE_PRIVATE_QA_CLI=1 pnpm openclaw --profile <isolated> qa suite --provider-mode mock-openai --scenario cron-failure-repair-owner-conversation` → `passed=1 failed=0`. An owned job fails twice and no alert is sent; the owner conversation receives the repair request, its ordinary turn fixes the workspace step file (`write`), the reply lands in that conversation, and the request and reply are in the owner session's own `chat.history`. Control: an unowned job with the same failures alerts, and the repaired job never does.
- **Service tests** (`src/cron/service.failure-repair.test.ts`, 11 tests): threshold → one `runCronFailureRepair` request to the owner session (no system event, no heartbeat wake) and no alert; the job's name, payload and error sit only inside `<untrusted-text>`; the next failure sends one alert naming the repair, later failures nothing more and never a second repair; a rejected repair request alerts on the next failure; success clears the incident silently; no owner → the old alert; agentTurn, systemEvent and script jobs repair, command jobs and on-exit or stream schedules alert. The heartbeat-route case in `src/cron/service.wake-now-real-heartbeat.test.ts` is removed (the file is back to `main`).
- On `435e097ee7c`: `node scripts/check-changed.mjs` exit 0 (line-cap ratchet, all tsgo shards, lint, import cycles, dead exports); cron repair/alert/persistence/real-heartbeat, gateway cron, cron-exit-watchers, server-cron, notifications and qa-lab mock-openai suites pass (30 files, 538 tests); `pnpm config:docs:check` is clean.
- **Existing-state upgrade (recorded on an earlier head, harness not kept):** published `[email protected]` created an owner session, an owned and an unowned agentTurn job with an announce failure route and each job's first failure; its own `openclaw update --tag <candidate tarball>` succeeded and both streaks and owners survived; one more failure each reached the threshold: the owned job's incident gained `repair: {atMs}` with delivery status `not-requested` and its repair request reached the model; the unowned job alerted. The persisted state is unchanged by this rework.
- **Config compatibility:** no config key is added or changed (`config:docs:check` OK). The behavior change is the default for owned chat-alerting jobs, documented above; per-job `failureAlert: false` opts out.
  - Downgrade: a persisted `repair` marker is an extra field older releases ignore; an incident that was mid-repair at downgrade keeps its signature there, so the older release dedupes that same-cause failure (no new alert until the cause changes or the job recovers), as it does for any already-alerted incident.
- **Owner boundary:** `owner` is fixed at creation (`CronJobPatch` omits it), so it cannot be reassigned; dispatch reads the live job and sends nothing if the job is gone.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…r changes, or a repair instead of the final alert (#162702)

## What Problem This Solves

Fixes two gaps in the owner-conversation repair from #161007: a job that keeps failing can get a second repair turn when its error changes, and a one-shot job that has used up its retries gets a repair request instead of its alert.

## User Impact

- Each failure streak gets one repair request, even if its cause changes later. The next failure sends the normal alert once, naming the repair, as before. Later alerts in the streak follow the usual dedupe and cooldown. Only a successful run starts a new streak, which can be repaired again.
- A job that will not run again keeps the existing failure alert and gets no repair request. This covers a disabled job and an `at` job with no retry scheduled, for example one whose retries ran out or whose error is permanent.

## Why This Change Was Made

**Provenance.** #161007 (fb2052a) added `failureAlertIncident.repair`. The repair request takes the incident's alert and cooldown slot, and the next failure skips dedupe and cooldown once to send the fallback alert. That fallback goes through `startFailureAlertCycle` (#146582, 5c81503), which rebuilds the incident from the new signature and so dropped `repair`. After that, a later failure with a different cause, once the cooldown had passed, looked like a new streak and got a second repair turn, which #161007 meant to prevent ("the streak is never repaired twice"). Separately, the one-shot retry policy (#24355) disables an `at` job when its retries run out. With `failureAlert.after` equal to that attempt, the repair replaced the job's final alert, and no later run could send the fallback.

**Fix (`failure-alerts.ts`, `startup-run-repair.ts`):**
- `startFailureAlertCycle` keeps `repair` and marks it `alerted: true`. Any alert after a repair request is its fallback. The marker lasts until `resolveFailureIncident` (success) deletes the incident. A repair is only requested when the incident has no `repair`, and the fallback bypass only runs while `alerted` is unset. Everything else from #161007 is unchanged: the repair still takes the alert and cooldown slot, and the fallback still fires once. A persisted marker from #161007 without `alerted` gets its pending fallback.
- Repair also requires `isJobEnabled(job)`, checked after scheduling settles. `applyJobResult` already finalizes notifications after a one-shot is disabled or a retry is scheduled. On restart, `markInterruptedStartupRun` disabled a retired one-shot only after finalizing notifications. It now does that first (#131473 logic, unchanged otherwise), so an interrupted one-shot that will be replayed is still repaired and a retired one alerts. Recurring jobs whose next run is recomputed later in recovery also stay eligible.

Persisted state: `repair: { atMs }` gains an optional `alerted: true`, and its lifetime becomes the streak.

**Bounded cost.** At most one repair turn per failure streak. The number of messages does not increase: a repair turn replaces an alert, the fallback is the single alert it was before, and terminal one-shots send the same single alert as before #161007. No new config, warnings, or message types.

Hermes check: Hermes kanban's `failure_limit` auto-block also keeps streak-scoped state that only a success resets. This PR follows the same approach.

## Evidence

- `src/cron/service.failure-repair.test.ts` (real `CronService`):
  - error A ×2 → repair; A → alert; cooldown passes; error B → alert, not a second repair; success; A ×2 → repair again. On origin/main, B started a second repair.
  - an `at` job with `failureAlert.after: 4`, run on schedule (`due`) until its retries are exhausted → disabled, one alert, no repair. On origin/main: one repair, no alert.
  - restart-interrupted owned jobs at the threshold (real `markInterruptedStartupRun`): recurring → repair; replayed one-shot → repair; retired one-shot → alert. It fails without the reorder (the retired one-shot is repaired) and with a `nextRunAtMs` gate (the replayed one-shot alerts).
- Related suites pass: failure-repair, failure-alert, failure-alerts persistence/recovery, startup-run-repair, run-recovery, Gateway `server.cron-failure-repair`.
- **Live Telegram Test Server, live model (`openai/gpt-6-astra`), DM owner conversation.** Each run uses an isolated source Gateway with a fresh state dir. A proxy in front of the real OpenAI API injects provider rejections only into the automation's own model calls: cause A is a 400 `invalid_value` (classified `format`), and cause B is a 404 `model_not_found`. The owner chat and the repair turns go to the live model. Scenario: owned hourly job, `failureAlert {after: 2, cooldownMs: 60s}`. Runs A, A, A; wait 65s; B. Then an owned `at` job (`after: 1`) whose single scheduled run fails with A.

  | Step | origin/main cron files (unchanged since `b2fc927`) | PR head `f064aed` |
  |---|---|---|
  | A ×2 | repair turn → *"Inbox sync is failing because the provider rejects its request format… Please provide the provider's detailed invalid_value error…"* | same repair turn and reply |
  | A (3rd) | alert *"failed 3 times / An automatic repair was requested…"* | same alert |
  | B after cooldown | **second repair turn** (model saw a brief for failure 4) → *"Inbox sync now fails because the provider cannot find openai/gpt-6-astra. Which available provider/model should I use…?"* and no alert | alert *"Automation "Inbox sync" failed 4 times / An automatic repair was requested… / Cause: model_not_found…"* and no repair turn |
  | terminal one-shot (disabled after the run) | **repair turn** → *"Report export failed because the provider rejected the request format. Please provide…"* for a job that will never run again | alert *"Automation "Report export" failed 1 times / Cause: format"* and no repair turn |

  Repair briefs the live model received: origin/main `[1, 2, 4]` (failure counts), PR head `[2]`. The runner completed on the PR head (lease released, scratch removed, no listeners left). The origin/main run hit the scenario command's 540s timeout at the very end, after it had recorded every step.
- **Store reopen (throwaway, real SQLite cron store, not committed).** A seeded #161007-shape incident `{signature, repair: {atMs}}` reloads as-is. The next failure sends the pending fallback (alerts 1, repairs 0) and persists `repair: {atMs, alerted: true}`. After a second `CronService` reopens the store, the marker still has `alerted: true`. A same-cause failure and a new-cause failure within the cooldown send nothing. A new cause after the cooldown sends one alert and no repair.
- Changed suite runtime: `pnpm vitest run src/cron/service.failure-repair.test.ts --maxWorkers=1` → 15 tests, 30.7s total (about 16s of it test time, the rest transform and import warmup).
- Throwaway real-Gateway smoke over WS (`cron.add`/`cron.run`, real cron service and `agent` dispatch, mocked isolated run; not committed): A,A → repair (`agent` dispatch 1); A → alert; A → deduped; B after cooldown → alert `delivered`, dispatch still 1; ok, then A,A → repair (dispatch 2); terminal `at` job with a permanent error → `enabled:false`, alert `delivered`, dispatch still 2. On origin/main, B after cooldown dispatched a second repair.

LOC vs origin/main: prod +31/−23 (`failure-alerts.ts`, `startup-run-repair.ts`, `types.ts`), test +98/−1, docs +1/−1.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…r changes, or a repair instead of the final alert (openclaw#162702)

## What Problem This Solves

Fixes two gaps in the owner-conversation repair from openclaw#161007: a job that keeps failing can get a second repair turn when its error changes, and a one-shot job that has used up its retries gets a repair request instead of its alert.

## User Impact

- Each failure streak gets one repair request, even if its cause changes later. The next failure sends the normal alert once, naming the repair, as before. Later alerts in the streak follow the usual dedupe and cooldown. Only a successful run starts a new streak, which can be repaired again.
- A job that will not run again keeps the existing failure alert and gets no repair request. This covers a disabled job and an `at` job with no retry scheduled, for example one whose retries ran out or whose error is permanent.

## Why This Change Was Made

**Provenance.** openclaw#161007 (fc14fc8) added `failureAlertIncident.repair`. The repair request takes the incident's alert and cooldown slot, and the next failure skips dedupe and cooldown once to send the fallback alert. That fallback goes through `startFailureAlertCycle` (openclaw#146582, e80c552), which rebuilds the incident from the new signature and so dropped `repair`. After that, a later failure with a different cause, once the cooldown had passed, looked like a new streak and got a second repair turn, which openclaw#161007 meant to prevent ("the streak is never repaired twice"). Separately, the one-shot retry policy (openclaw#24355) disables an `at` job when its retries run out. With `failureAlert.after` equal to that attempt, the repair replaced the job's final alert, and no later run could send the fallback.

**Fix (`failure-alerts.ts`, `startup-run-repair.ts`):**
- `startFailureAlertCycle` keeps `repair` and marks it `alerted: true`. Any alert after a repair request is its fallback. The marker lasts until `resolveFailureIncident` (success) deletes the incident. A repair is only requested when the incident has no `repair`, and the fallback bypass only runs while `alerted` is unset. Everything else from openclaw#161007 is unchanged: the repair still takes the alert and cooldown slot, and the fallback still fires once. A persisted marker from openclaw#161007 without `alerted` gets its pending fallback.
- Repair also requires `isJobEnabled(job)`, checked after scheduling settles. `applyJobResult` already finalizes notifications after a one-shot is disabled or a retry is scheduled. On restart, `markInterruptedStartupRun` disabled a retired one-shot only after finalizing notifications. It now does that first (openclaw#131473 logic, unchanged otherwise), so an interrupted one-shot that will be replayed is still repaired and a retired one alerts. Recurring jobs whose next run is recomputed later in recovery also stay eligible.

Persisted state: `repair: { atMs }` gains an optional `alerted: true`, and its lifetime becomes the streak.

**Bounded cost.** At most one repair turn per failure streak. The number of messages does not increase: a repair turn replaces an alert, the fallback is the single alert it was before, and terminal one-shots send the same single alert as before openclaw#161007. No new config, warnings, or message types.

Hermes check: Hermes kanban's `failure_limit` auto-block also keeps streak-scoped state that only a success resets. This PR follows the same approach.

## Evidence

- `src/cron/service.failure-repair.test.ts` (real `CronService`):
  - error A ×2 → repair; A → alert; cooldown passes; error B → alert, not a second repair; success; A ×2 → repair again. On origin/main, B started a second repair.
  - an `at` job with `failureAlert.after: 4`, run on schedule (`due`) until its retries are exhausted → disabled, one alert, no repair. On origin/main: one repair, no alert.
  - restart-interrupted owned jobs at the threshold (real `markInterruptedStartupRun`): recurring → repair; replayed one-shot → repair; retired one-shot → alert. It fails without the reorder (the retired one-shot is repaired) and with a `nextRunAtMs` gate (the replayed one-shot alerts).
- Related suites pass: failure-repair, failure-alert, failure-alerts persistence/recovery, startup-run-repair, run-recovery, Gateway `server.cron-failure-repair`.
- **Live Telegram Test Server, live model (`openai/gpt-6-astra`), DM owner conversation.** Each run uses an isolated source Gateway with a fresh state dir. A proxy in front of the real OpenAI API injects provider rejections only into the automation's own model calls: cause A is a 400 `invalid_value` (classified `format`), and cause B is a 404 `model_not_found`. The owner chat and the repair turns go to the live model. Scenario: owned hourly job, `failureAlert {after: 2, cooldownMs: 60s}`. Runs A, A, A; wait 65s; B. Then an owned `at` job (`after: 1`) whose single scheduled run fails with A.

  | Step | origin/main cron files (unchanged since `e95c66b`) | PR head `f064aed` |
  |---|---|---|
  | A ×2 | repair turn → *"Inbox sync is failing because the provider rejects its request format… Please provide the provider's detailed invalid_value error…"* | same repair turn and reply |
  | A (3rd) | alert *"failed 3 times / An automatic repair was requested…"* | same alert |
  | B after cooldown | **second repair turn** (model saw a brief for failure 4) → *"Inbox sync now fails because the provider cannot find openai/gpt-6-astra. Which available provider/model should I use…?"* and no alert | alert *"Automation "Inbox sync" failed 4 times / An automatic repair was requested… / Cause: model_not_found…"* and no repair turn |
  | terminal one-shot (disabled after the run) | **repair turn** → *"Report export failed because the provider rejected the request format. Please provide…"* for a job that will never run again | alert *"Automation "Report export" failed 1 times / Cause: format"* and no repair turn |

  Repair briefs the live model received: origin/main `[1, 2, 4]` (failure counts), PR head `[2]`. The runner completed on the PR head (lease released, scratch removed, no listeners left). The origin/main run hit the scenario command's 540s timeout at the very end, after it had recorded every step.
- **Store reopen (throwaway, real SQLite cron store, not committed).** A seeded openclaw#161007-shape incident `{signature, repair: {atMs}}` reloads as-is. The next failure sends the pending fallback (alerts 1, repairs 0) and persists `repair: {atMs, alerted: true}`. After a second `CronService` reopens the store, the marker still has `alerted: true`. A same-cause failure and a new-cause failure within the cooldown send nothing. A new cause after the cooldown sends one alert and no repair.
- Changed suite runtime: `pnpm vitest run src/cron/service.failure-repair.test.ts --maxWorkers=1` → 15 tests, 30.7s total (about 16s of it test time, the rest transform and import warmup).
- Throwaway real-Gateway smoke over WS (`cron.add`/`cron.run`, real cron service and `agent` dispatch, mocked isolated run; not committed): A,A → repair (`agent` dispatch 1); A → alert; A → deduped; B after cooldown → alert `delivered`, dispatch still 1; ok, then A,A → repair (dispatch 2); terminal `at` job with a permanent error → `enabled:false`, alert `delivered`, dispatch still 2. On origin/main, B after cooldown dispatched a second repair.

LOC vs origin/main: prod +31/−23 (`failure-alerts.ts`, `startup-run-repair.ts`, `types.ts`), test +98/−1, docs +1/−1.

Co-authored-by: Ayaan Zaidi <[email protected]>
steipete added a commit that referenced this pull request Oct 15, 2026
* refactor: consolidate command and cron preparation paths

Keep one sub-CLI metadata/registration catalog, common cron payload updates,
canonical agent migration visitors, and shared account-state projection.
Trust typed internal adapters while retaining external validation, effect
authority, cancellation settlement, supported migrations and path containment.

Wave-5 y10: BELOW-500, 353 net production lines removed (+440/-793 in 19 files).
Branch-only handoff for the coordinator's bundle; no standalone PR.

Best-effort tradeoffs accepted:
- Cron mid-setup reload recovery (#146582): synthetic retirement, no human
  incident. Setup may fail; the next invocation refreshes the cache.
- Recursive shared preparation retry (#102494/#138337): synthetic concurrent
  callers; production serializes same-job work. Duplicate direct callers may
  share cancellation. Failed-owner eviction preserves the next sequential run.
- Progress publication generation (#143621): synthetic held update/reset.
  Presentation dedupe may briefly be stale until a subsequent render/reset.
- Doctor adapter schema mirror (#69919): malformed synthetic hooks. Invalid
  executable adapters fail visibly; missing-hook fallbacks and config checks stay.
- Setup adapter schema mirror (#165492): typed internal union. Invalid internal
  adapters fail when used; both supported wizard forms remain.
- Injected process schema mirror (#84381): malformed injection was not human
  SIGTERM report #71710. Invalid adapters fail registration; cancellation stays.
- Loaded registry row revalidation/copy (#114942/#158830/#114476): rows already
  admitted/normalized. Corrupt trusted rows can fail; first-wins authority stays.
- Custom compatibility duplicate check (#14223): all callers parse/type it.
  Hand-crafted invalid JS uses the default branch; external flags still reject it.
- Log probe identity matching (#88159, superseded by #168587): abort now joins
  the sole probe, so replacement cannot race its result. Recovery/settlement stay.
- Whole-config deep copy (#71218): no detached-copy incident. Structural copy
  updates agents/defaults; unrelated future mutation must respect config ownership.
- Repeated plugin-root probes (#70012): no disappearing-root incident. Resolve
  roots once; root replacement can fail discovery. Symlink containment stays.
- Second payload getter read (#135319): synthetic review/corpus, not a human
  report. Ordinary decoded records are read once; stateful accessors may differ.

Proof: fresh independent review clean; core types, targeted lint/format, runtime
and static cycles, assertion/line-cap ratchets, and suppression suite passed.
Focused CLI cohort: 8 files / 41 tests passed. Earlier unchanged account/setup
and cold-import checks passed. Cron and commands cohorts were interrupted after
partial results; complete owner tests, payload merging, test-graph types, broad
check-changed and build/smoke remain unproved at commit preparation.

Unattributed local 120-second timeouts retained: two root-command-descriptions
catalog cases and agent-via-gateway's Gateway attempt-budget case. No timeout,
retry, skip or kept-behavior expectation changes. Env-name budget mismatch
(455 vs 454) also exists at original HEAD and pinned main 7dccff5.
All runtime proof used isolated HOME/OpenClaw/XDG state; Phase E untouched.

* refactor: consolidate cron payload and lazy CLI paths

Share daemon and cron method forwarding through the existing lazy binder,
remove the cron CLI reexport shim, and consolidate normalization and merge
handling without changing public fields, explicit clears, or effect authority.
Remove the obsolete bundled discovery reentry mechanism and impossible Doctor
issue helper. The full lane now removes 475 net production lines.

Best-effort tradeoffs accepted:
- Unknown Doctor issue variants supplied by hand-crafted JavaScript return the
  invalid value rather than a custom error. Typed local producers and exhaustive
  switches remain; reporting feature #95979 cites no human unknown-kind incident.
- Synchronous bundled-module self-discovery may fail through the existing loader
  diagnostic instead of returning empty inventory. Commit 65f18d6 only pins
  injected Jiti reentry, not a human incident; ordinary caches remain.
- Cron defaults trust staggerMs normalized earlier in the same synchronous call.
  No await or mutation boundary intervenes; externally supplied invalid values
  remain rejected by the normalizer.

* fix(channels): retain replacement preview deduplication

Withdraw the progress compositor generation removal after the Mattermost
retiring-publication case failed CI and bounded serial head/base replays
remained inconclusive under load. Restore that file exactly to the branch
base and keep all Mattermost tests unchanged, following the campaign fallback.

Prune the single obsolete mock-export allowance left by the removed bundled
discovery reentry fixture. The local mock ratchet passes with 9586 factories.
The remaining lane reduction is 471 net production lines across 25 paths.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…#173036)

* refactor: consolidate command and cron preparation paths

Keep one sub-CLI metadata/registration catalog, common cron payload updates,
canonical agent migration visitors, and shared account-state projection.
Trust typed internal adapters while retaining external validation, effect
authority, cancellation settlement, supported migrations and path containment.

Wave-5 y10: BELOW-500, 353 net production lines removed (+440/-793 in 19 files).
Branch-only handoff for the coordinator's bundle; no standalone PR.

Best-effort tradeoffs accepted:
- Cron mid-setup reload recovery (openclaw#146582): synthetic retirement, no human
  incident. Setup may fail; the next invocation refreshes the cache.
- Recursive shared preparation retry (openclaw#102494/openclaw#138337): synthetic concurrent
  callers; production serializes same-job work. Duplicate direct callers may
  share cancellation. Failed-owner eviction preserves the next sequential run.
- Progress publication generation (openclaw#143621): synthetic held update/reset.
  Presentation dedupe may briefly be stale until a subsequent render/reset.
- Doctor adapter schema mirror (openclaw#69919): malformed synthetic hooks. Invalid
  executable adapters fail visibly; missing-hook fallbacks and config checks stay.
- Setup adapter schema mirror (openclaw#165492): typed internal union. Invalid internal
  adapters fail when used; both supported wizard forms remain.
- Injected process schema mirror (openclaw#84381): malformed injection was not human
  SIGTERM report openclaw#71710. Invalid adapters fail registration; cancellation stays.
- Loaded registry row revalidation/copy (openclaw#114942/openclaw#158830/openclaw#114476): rows already
  admitted/normalized. Corrupt trusted rows can fail; first-wins authority stays.
- Custom compatibility duplicate check (openclaw#14223): all callers parse/type it.
  Hand-crafted invalid JS uses the default branch; external flags still reject it.
- Log probe identity matching (openclaw#88159, superseded by openclaw#168587): abort now joins
  the sole probe, so replacement cannot race its result. Recovery/settlement stay.
- Whole-config deep copy (openclaw#71218): no detached-copy incident. Structural copy
  updates agents/defaults; unrelated future mutation must respect config ownership.
- Repeated plugin-root probes (openclaw#70012): no disappearing-root incident. Resolve
  roots once; root replacement can fail discovery. Symlink containment stays.
- Second payload getter read (openclaw#135319): synthetic review/corpus, not a human
  report. Ordinary decoded records are read once; stateful accessors may differ.

Proof: fresh independent review clean; core types, targeted lint/format, runtime
and static cycles, assertion/line-cap ratchets, and suppression suite passed.
Focused CLI cohort: 8 files / 41 tests passed. Earlier unchanged account/setup
and cold-import checks passed. Cron and commands cohorts were interrupted after
partial results; complete owner tests, payload merging, test-graph types, broad
check-changed and build/smoke remain unproved at commit preparation.

Unattributed local 120-second timeouts retained: two root-command-descriptions
catalog cases and agent-via-gateway's Gateway attempt-budget case. No timeout,
retry, skip or kept-behavior expectation changes. Env-name budget mismatch
(455 vs 454) also exists at original HEAD and pinned main 89f8219.
All runtime proof used isolated HOME/OpenClaw/XDG state; Phase E untouched.

* refactor: consolidate cron payload and lazy CLI paths

Share daemon and cron method forwarding through the existing lazy binder,
remove the cron CLI reexport shim, and consolidate normalization and merge
handling without changing public fields, explicit clears, or effect authority.
Remove the obsolete bundled discovery reentry mechanism and impossible Doctor
issue helper. The full lane now removes 475 net production lines.

Best-effort tradeoffs accepted:
- Unknown Doctor issue variants supplied by hand-crafted JavaScript return the
  invalid value rather than a custom error. Typed local producers and exhaustive
  switches remain; reporting feature openclaw#95979 cites no human unknown-kind incident.
- Synchronous bundled-module self-discovery may fail through the existing loader
  diagnostic instead of returning empty inventory. Commit ca10460 only pins
  injected Jiti reentry, not a human incident; ordinary caches remain.
- Cron defaults trust staggerMs normalized earlier in the same synchronous call.
  No await or mutation boundary intervenes; externally supplied invalid values
  remain rejected by the normalizer.

* fix(channels): retain replacement preview deduplication

Withdraw the progress compositor generation removal after the Mattermost
retiring-publication case failed CI and bounded serial head/base replays
remained inconclusive under load. Restore that file exactly to the branch
base and keep all Mattermost tests unchanged, following the campaign fallback.

Prune the single obsolete mock-export allowance left by the removed bundled
discovery reentry fixture. The local mock ratchet passes with 9586 factories.
The remaining lane reduction is 471 net production lines across 25 paths.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

1 participant