Skip to content

[ENG-22434] fix(heartbeat): agent never reports a background command's result in a chat after any heartbeat has run - #342

Merged
orswn merged 2 commits into
boonfrom
okka/ENG-22434/exec-completion-wake
Nov 23, 2026
Merged

orswn merged 2 commits into
boonfrom
okka/ENG-22434/exec-completion-wake

Conversation

@orswn

@orswn orswn commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: ENG-22434 (Linear). Persona counterpart: getboon/gandalf-manager#910 (merge after this PR).

What Problem This Solves

Fixes an issue where an agent that started a long background command in a chat (Teams or Slack DM, channel, thread, or Boon Web chat) never reported the result when the command finished, once any heartbeat had already run on that gateway. The agent ended its turn saying it would report back, the command finished or was killed, and then nothing happened until the user wrote again. A killed command, for example one stopped by the OOM killer, was also never reported.

Why This Change Was Made

When a background exec exits, OpenClaw queues an Exec completed/failed (...) event on the chat that started it and requests an exec-event heartbeat wake for that chat. That wake goes through the per-agent cooldown, which deferred every event wake while the next periodic heartbeat was not yet due. Every heartbeat run moves that due time a full interval ahead, so with an hourly heartbeat every completion wake after the first heartbeat was dropped as not-due: no retry and no log line. The periodic tick drains only the heartbeat session, and user turns leave exec completions queued, so the result was never reported.

Changes:

  • Chat completions skip only the interval check. A wake qualifies when it comes from an exec event, its run session is not the agent's heartbeat session (or its isolated variant) and not a cron session, and that session has a queued exec completion. The 30 s minimum spacing and the flood guard (5 runs per 60 s) still apply. Wakes for the heartbeat session keep the interval gate, so the self-wake loop protection from Heartbeat exec-event interval-bypass regression (re: #17797): runaway runs every ~10s instead of configured every:30m openclaw/openclaw#75436 is unchanged. Same idea as upstream openclaw/openclaw@2883684ffed, which depends on a larger refactor that is not on boon.
  • No silent drop. A qualifying wake deferred by spacing or flood is retried by a runner-owned timer when the guard clears. Every exec-event deferral logs one info line: heartbeat: exec event wake deferred with the reason and retryInMs or dropped: true.
  • Periodic cadence unchanged. A completion run records its start for spacing/flood but does not move the next periodic heartbeat.
  • Wake layer no longer spins during a long run. When a wake timer fired while a run was in flight, it re-armed at the same delay, which for exec wakes (delay 0) spins at about 1 ms for the whole run. It now waits for the in-flight batch, which already reschedules when it ends.
  • No duplicate answer after an in-turn poll. A command the model already followed to its exit with process poll or process log in the same turn left its exit event queued, so the new bypass would relay the same output again after the turn. Showing the exit through poll/log now removes that one queued event (same idea as upstream acknowledgeNotifyOnExit).
  • One sentence in docs/gateway/heartbeat.md.

Not changed: the broadcast (untargeted) wake path, cron and sub-agent sessions, config schema, delivery routing.

Known limits, not changed here:

  • Chats that share the heartbeat session keep the interval gate: Slack/Teams DMs under session.dmScope: "main", session.scope: "global", a heartbeat.session override. Boon Web chats have their own session keys under any dmScope.
  • A chain of completion turns that each start another background command can repeat at most once per 30 s per agent (same bound upstream accepts).
  • The system event queue is in memory, so a gateway restart between the exit and the wake still loses the event.
  • A pending spacing retry is cleared when the runner stops.
  • A completion run skipped for a non-retryable reason (for example outside heartbeat.activeHours) is not retried; the event stays queued until the next exec-event wake for that chat. Same as for any other targeted wake today.
  • On a channel from an external plugin, a successful command with no output posts no exit notification unless tools.exec.notifyOnExitEmptySuccess is set, so there is nothing to wake for (unchanged).
  • An acknowledged in-turn exit logs exec event wake deferred ... dropped: true; that line is expected.

User Impact

In a chat, when a background command the agent started finishes, fails, or is killed, the agent now gets a turn in that chat right away and reports the result, without waiting for the user to write again and without waiting for the next heartbeat. Commands the agent already watched to completion in the same turn are not reported twice. The periodic heartbeat behaves as before.

Evidence

Tests written first; the new behavior tests fail on boon and pass with this change:

  • src/infra/heartbeat-cooldown.test.ts: on boon, expected { defer: true, reason: 'not-due' } to deeply equal { defer: false }.
  • src/infra/heartbeat-runner.chat-completion-wake.test.ts (new): a killed (Exec failed (abcd1234, signal SIGKILL) :: Killed) and a successful DM completion run after a heartbeat already ran; group/thread keys run; the heartbeat session, cron keys, a DM with nothing queued, the isolated heartbeat key, a heartbeat.session override, a dmScope: "main" DM and scope: "global" stay gated; spacing and flood deferrals retry exactly once with one log line and no further runs over 10 min; the retry stops once the event is drained or the runner stops; busy retries still bypass the interval; the periodic tick fires at its original time; runHeartbeatOnce relays a killed DM command to the DM route when no target is set. On boon: 12 failed, 4 passed (the 4 gated cases).
  • src/infra/heartbeat-wake.test.ts: a wake requested during a long in-flight run. On boon: expected "setTimeout" to be called 1 times, but got 102 times.
  • src/agents/bash-tools.test.ts, bash-process-registry.test.ts: poll or log that shows a background exit (success or failure) removes only that session's queued exit event; unrelated events and other sessions' events stay; a command nobody polls keeps its event; running poll/log does not acknowledge.
  • Mutation checks: removing each gate condition, the cadence skip, the timer cleanup, the spin guard, or any of the three acknowledgement calls makes its test fail.

Local runs (Node 22.23.5): heartbeat and exec/process tests: unit-fast 140/140, infra 239/239, e2e 8/8, agents 520 passed + 2 failures that fail the same way on boon (exec-host-gateway allow-always shell-wrapper, script-preflight heredoc node, a local toolchain config error). oxfmt --check, oxlint, tsgo core and core test, format:docs:check, git diff --check: clean. pnpm check:loc fails repo-wide before and after (heartbeat-runner.ts is already 2,886 lines on boon).

Local smoke (before vs after)

Local gateway with fleet heartbeat and session settings (heartbeat.every: "1h", session.dmScope: "per-channel-peer", messages.queue.mode: "collect", empty HEARTBEAT.md), Boon Web chat through the anychat plugin, Claude Sonnet 5.5 on Bedrock. Before = boon at 5c32ab8 (2026.7.35-boon.3); after = this branch. In every scenario one heartbeat had already run.

Scenario Before: exit to reply After: exit to reply
Background command exits cleanly (75 s) no reply, watched 327 s 7.1 s
Background command killed by a real cgroup OOM kill (exit 137) no reply, watched 363 s 7.9 s, reports the kill
Two chats, exits 10-15 s apart no reply in either chat, watched 317-332 s 9.8 s and 25.0 s (second one retried once after the 30 s spacing)
About 4 min job, plain request ("run the script and give me the result") no reply, watched 312 s 9.2 s

Guards (after):

  • Heartbeat session keeps the interval gate: a background command in agent:main:main exits and the wake is dropped, no turn follows:
    {"sessionKey": "agent:main:main", "reason": "not-due", "dropped": true} heartbeat: exec event wake deferred
  • Spacing retry instead of a drop: {"reason": "min-spacing", "retryInMs": 19304} heartbeat: exec event wake deferred, then the reply.
  • No duplicate: a command the agent polled to its exit in the same turn produced exactly one answer; the exit wake was dropped (not-due) and no second message came in the next 210 s.

Before and after: clean exit, OOM kill, 4 min job

Not covered locally: Microsoft Teams and Slack delivery (no local channel), and the out-of-turn reply in Boon Web carries no suggested-reply chips (the heartbeat delivery path; not changed here).

…heartbeat ran

When a backgrounded exec exits, the exec runtime queues an
"Exec completed/failed (...)" system event on the session that started
it and requests an exec-event heartbeat wake for that session. The wake
goes through the per-agent cooldown, which defers every event wake while
now < nextDueMs. Every heartbeat run, including a skipped one, moves
nextDueMs a full interval ahead. With an hourly heartbeat, every
completion wake after the first heartbeat run is therefore deferred as
"not-due" and dropped: no retry, no log line. The periodic tick only
drains the heartbeat session and user turns leave exec completions
queued, so nothing ever reports the result. In a DM, channel, thread or
web chat the agent says it will report back and then stays silent, also
when the job was killed (for example by the OOM killer).

Let a command completion that belongs to a chat skip the "not-due"
check. A wake qualifies when it comes from an exec event, its run
session is not the agent's heartbeat session (nor its isolated variant)
and not a cron session, and that session has a queued exec completion.
The 30 s minimum spacing and the flood guard still apply, so a chain of
completions in one chat runs at most once per 30 s per agent, and wakes
for the heartbeat session keep the interval gate that prevents
self-wake loops. A completion that hits the spacing or flood guard is
retried by a runner-owned timer once the guard clears, instead of being
dropped. A completion run records bookkeeping but leaves the periodic
schedule alone. Every exec-event deferral now logs one info line with
the reason and whether it was retried or dropped.

Two follow-on fixes keep this bounded:

- The wake layer re-armed its timer at the same delay while a run was
  in flight, which spins at about 1 ms for exec wakes (delay 0) for the
  length of the run. It now marks the wake as scheduled and lets the
  in-flight batch reschedule it when the run ends.

- A command the model already polled to its exit in the same turn
  still left its exit event queued, so the new bypass would relay the
  same output a second time after the turn. When process poll or
  process log shows that a backgrounded session has exited, its queued
  exit event is now removed.

Refs: ENG-22434

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 14 files

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread docs/gateway/heartbeat.md Resolved
Comment thread src/infra/heartbeat-runner.ts Resolved
The cases that must keep the not-due gate (dmScope main DM, global
scope, heartbeat.session override, isolated heartbeat session) queued
the completion only under the raw wake key. Those wakes run in the
resolved session, so the gate check saw an empty queue and the test
passed by absence. Queue the completion under the resolved key too.

Also narrow the docs line: the wake needs a queued exit notification
(tools.exec.notifyOnExit), and a quiet successful exit may not notify
on every channel.

Refs: ENG-22434

@boon-hermes-bot boon-hermes-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved

Approve covers ab4ff94fbed32a989b71c26537f336c80e7a9613 specifically.

Fixes background command exit notifications in chat sessions being dropped after any periodic heartbeat runs on the gateway (ENG-22434).

Strengths

  • Precise cooldown gating: Chat command completion wakes bypass only the not-due interval check, while strictly retaining the 30s minimum spacing floor and the flood guard (5 runs per 60s).
  • Self-wake loop protection intact: Heartbeat sessions, isolated heartbeat sessions, cron sessions, and chats resolving to global or main scope retain the periodic interval gate.
  • No silent drops: Qualifying wakes deferred by min-spacing or flood are retried via runner-owned timers when guards clear, emitting structured info logs with retryInMs or dropped: true.
  • Cadence preservation: Command completion runs update bookkeeping for spacing and flood accounting without advancing nextDueMs, preserving the periodic heartbeat schedule.
  • Spin guard fix: Wake scheduling during in-flight runs now marks the wake as scheduled rather than re-arming immediate 0ms timers repeatedly during long runs.
  • Duplicate suppression: Acknowledging background process exits via process poll or process log removes queued exit notifications so output is not relayed a second time.

Technical Review

  • Logic Correctness: isChatCommandCompletion correctly validates that the wake is an exec-event, resolves the session key, excludes cron and periodic/isolated heartbeat sessions, and verifies that a completion event is queued via isExecCompletionEvent.
  • Retry and Cooldown Timing: resolveDeferralRetryInMs accurately calculates remaining time for min-spacing (lastRunStartedAtMs + 30s - now) and flood recovery (recentRunStarts[length - threshold] + 60s + 1 - now), with timers unref'd and cleared upon runner shutdown.
  • In-turn Acknowledgment: recordNotifyOnExitRemoval and acknowledgeNotifyOnExit cleanly decouple exit consumption from process polling and logging, ensuring exit events are removed atomically when inspected in-turn.
  • Addressed Feedback: Resolved Cubic review comments by documenting notification prerequisites in docs/gateway/heartbeat.md and ensuring gated test cases queue completions under resolved session keys.

Verification

  • Local testing: Ran targeted Vitest suites across heartbeat-runner.chat-completion-wake.test.ts, heartbeat-cooldown.test.ts, heartbeat-wake.test.ts, bash-process-registry.test.ts, bash-process-abort.test.ts, bash-tools.exec-runtime.test.ts, and bash-tools.test.ts (136/136 tests passed).
  • Static analysis: oxlint and oxfmt format check passed with 0 errors or warnings.
  • CI Checks: All 65 CI check runs completed successfully (including ci-gate, check-shrinkwrap, check-lint, check-prod-types, check-test-types, check-guards, CodeQL, and OpenGrep).
  • GPG Signatures: Cryptographic verification confirmed valid for commits 1386d3a5 and ab4ff94f.

Verdict: APPROVE (ready-to-release)

@orswn
orswn merged commit 1a21679 into boon Nov 23, 2026
155 of 161 checks passed
@orswn
orswn deleted the okka/ENG-22434/exec-completion-wake branch November 23, 2026 14:42
orswn added a commit that referenced this pull request Nov 24, 2026
Cuts the fork release carrying #342 (ENG-22434), merged to boon after
the v2026.7.35-boon.3 tag. Without a tagged release the fix cannot be
pinned in the fleet, so chats on running hosts still drop the result of
a background command once any heartbeat has run.

Version-only bump, same pattern as #341: upstream base stays 2026.7.35;
fork increment moves boon.3 -> boon.4. Bumps root
package.json/npm-shrinkwrap.json, packages/ai, all 142 bundled plugin
manifests (pnpm plugins:sync, which also adds the matrix changelog
entry), and every extension npm-shrinkwrap.json, version strings only.
Adds the 2026.7.35-boon.4 CHANGELOG.md section.

Refs: ENG-22434
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant