Skip to content

fix: selective system event drain for heartbeat runs + suppress duplicate poll notifications - #53740

Closed
nxmxbbd wants to merge 26 commits into
openclaw:mainfrom
nxmxbbd:fix/heartbeat-system-event-drain
Closed

nxmxbbd wants to merge 26 commits into
openclaw:mainfrom
nxmxbbd:fix/heartbeat-system-event-drain

Conversation

@nxmxbbd

@nxmxbbd nxmxbbd commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two related issues with system event handling in heartbeat runs:

1. Periodic heartbeats destructively drain all system events

When heartbeat.session targets a shared session (e.g. whatsapp:direct:+1234), the heartbeat run and normal user turns share the same session. On each run, drainFormattedSystemEvents() calls drainSystemEventEntries() which destructively removes all queued system events (exec completions, inter-session messages, etc.).

Heartbeat runs don't persist their messages to the session transcript (JSONL). So when a heartbeat run drains system events, those events are silently lost --- the next normal turn never sees them. This causes the agent to "forget" completed background tasks (e.g. an az login that finished while the heartbeat was running).

2. process poll and maybeNotifyOnExit produce duplicate notifications

When an agent uses process poll to wait for a backgrounded command, the process exit triggers two notification paths simultaneously:

  1. poll wait loop detects session.exited → returns exit result directly to the agent
  2. child process exit event → maybeNotifyOnExit() → enqueueSystemEvent() + requestHeartbeatNow() → heartbeat fires with redundant "Exec completed" message

This causes every polled background exec to inject a duplicate "Exec completed (xxx, code 0)" into the next heartbeat turn --- pure noise that wastes tokens.

Fix

Part 1: Selective drain for periodic heartbeats

System events fall into two categories based on how they are enqueued:

  • Wake-paired events (wakeRequested: true): enqueued alongside requestHeartbeatNow() --- exec completions, cron results, hook events, notifications, restart sentinels. These have a dedicated event-driven wake to consume them.
  • Passive events (no wake): presence updates, model switches, fast-mode toggles. These are meant for the next user turn.

Heartbeat runs are handled differently based on their trigger:

  • Event-driven heartbeats (exec completion, cron, hook, wake): drain all events, since their prompt references the results.
  • Periodic heartbeats (interval timer, retry): selectively drain only wakeRequested events whose dedicated wake was missed (e.g. heartbeats were temporarily disabled when the event arrived). Passive events stay queued for the next user turn.

Part 2: Poll suppression for exec notifications

Two-layer approach to prevent duplicate notifications when an agent is actively polling:

Layer 1 --- Source suppression: A pollWaiting flag on ProcessSession is set to true while the poll wait loop is active. maybeNotifyOnExit() checks this flag and skips enqueuing + wake when set. This covers the primary case (process exits while poll is waiting).

Layer 2 --- Fallback cleanup: When poll returns an exit result, it sets exitNotified = true (preventing any late maybeNotifyOnExit call) and calls removeExecEventsForSession() to clean up any events that raced into the queue before pollWaiting was set. This covers the narrow window between consecutive poll calls.

Fire-and-forget processes are unaffected: pollWaiting is only set during active poll waits. Background processes that nobody polls still get full maybeNotifyOnExit → system event → heartbeat wake behavior.

Implementation

ProcessSession interface (bash-process-registry.ts): Add optional pollWaiting?: boolean field.

maybeNotifyOnExit() (bash-tools.exec-runtime.ts): Add session.pollWaiting to the early-return guard.

Poll handler (bash-tools.process.ts):

  • Set pollWaiting = true before entering the wait loop
  • Set pollWaiting = false after the wait loop completes
  • On exit: set exitNotified = true and call removeExecEventsForSession() to clean up any raced events

removeExecEventsForSession() (system-events.ts): New function that removes queued events matching a specific exec session's ID prefix (consistent with maybeNotifyOnExit's session.id.slice(0, 8) format). Cleans up empty queue entries.

SystemEvent type (system-events.ts): Add optional wakeRequested?: boolean field, propagated through enqueueSystemEvent() options.

drainWakeRequestedEvents() (system-events.ts): New function that drains only events tagged with wakeRequested, leaving the rest queued.

Enqueue call sites --- tagged wakeRequested: true where paired with requestHeartbeatNow():

  • task-registry.ts: task completion + blocked followup
  • server-node-events.ts: notifications, exec completions
  • server-restart-sentinel.ts: restart wake events
  • server/hooks.ts: hook events (conditional on wakeMode === "now")
  • server-cron.ts: cron deps wrapper (passes through to cron service)
  • cron/service/timer.ts: failure alerts, main-session jobs, wake events
  • cron/service/jobs.ts: auto-disabled notifications

Drain logic (session-system-events.ts): Periodic heartbeats call drainWakeRequestedEvents() instead of skipping entirely. Event-driven heartbeats and normal turns still call drainSystemEventEntries() (drain all).

isEventDrivenHeartbeat flag: Passed through the reply chain (heartbeat-runner.ts → types.ts → get-reply-run.ts → session-system-events.ts) to distinguish periodic from event-driven runs.

Changes

  • bash-process-registry.ts: Add pollWaiting to ProcessSession interface
  • bash-tools.exec-runtime.ts: Add pollWaiting check to maybeNotifyOnExit guard
  • bash-tools.process.ts: Set/clear pollWaiting around poll wait loop; set exitNotified and call removeExecEventsForSession on exit
  • system-events.ts: Add wakeRequested to SystemEvent type and options; add drainWakeRequestedEvents(); add removeExecEventsForSession()
  • session-system-events.ts: Periodic heartbeats use drainWakeRequestedEvents() instead of empty array
  • heartbeat-runner.ts: Updated comments to reflect selective drain behavior
  • task-registry.ts, server-node-events.ts, server-restart-sentinel.ts, server/hooks.ts, server-cron.ts: Tag enqueue calls with wakeRequested: true
  • cron/service/state.ts: Update enqueueSystemEvent dep type signature
  • cron/service/timer.ts, cron/service/jobs.ts: Tag enqueue calls with wakeRequested
  • system-events.test.ts: Add tests for drainWakeRequestedEvents, removeExecEventsForSession, and periodic heartbeat wake-drain integration

Backward Compatibility

  • wakeRequested and pollWaiting are optional fields --- existing code that does not set them defaults to undefined (falsy), which is the safe default.
  • drainWakeRequestedEvents and removeExecEventsForSession are additive --- no existing function signatures change.
  • No impact on other PRs or merged code.

Impact

  • Polled background execs: no longer produce duplicate "Exec completed" events in heartbeat turns
  • Fire-and-forget execs: notification behavior unchanged
  • Periodic heartbeats: selectively drain only missed-wake events, leaving passive events for user turns
  • Event-driven heartbeats: drain all events normally (unchanged)
  • Edge case fixed: events whose wake was skipped (heartbeats temporarily disabled) are now recovered by the next periodic run

@greptile-apps

greptile-apps Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a data-loss bug where heartbeat runs on shared sessions were silently consuming queued system events (exec completions, inter-session messages) before any normal user turn could see and persist them. The fix is targeted and clean: drainFormattedSystemEvents now accepts an optional isHeartbeat flag, and when set, returns an empty slice instead of calling drainSystemEventEntries — leaving the queue untouched for the next real turn to drain.

Key points from the review:

  • The implementation takes a more conservative approach than the PR description describes: rather than peeking (read-only), heartbeat runs skip events entirely (they neither see nor consume them). The code comment explains the deliberate reasoning — repeated peeks across multiple heartbeat cycles would waste tokens and risk duplicate side-effects.
  • The PR description's "Impact" bullet ("Heartbeat runs still see system events in their prompt (via peek)") is therefore no longer accurate — heartbeats are fully unaware of pending system events under the current implementation. This is not a bug, but the stale description could mislead future readers.
  • One subtle asymmetry worth being aware of: the isMainSession && isNewSession branch that calls buildChannelSummary is unguarded by isHeartbeat, so a heartbeat that initialises a brand-new main session would still inject a channel summary. This is likely intentional.
  • The new test in system-events.test.ts cleanly covers the peek-vs-drain invariant.

Confidence Score: 5/5

  • Safe to merge — the fix is minimal, well-commented, and tested; it resolves a real data-loss bug with no regressions to normal-run event handling.
  • The change correctly addresses the root cause (heartbeat draining system events destructively), the only surviving note is a PR-description inaccuracy (peek vs skip), which is a documentation concern rather than a code defect. All four changed files are internally consistent, and the test validates the core invariant end-to-end.
  • No files require special attention.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/session-system-events.ts
Line: 88-90

Comment:
**PR description and implementation diverge on heartbeat visibility**

The PR description's "Fix" and "Impact" sections state heartbeat runs will _still see_ system events in their prompt (via `peekSystemEventEntries`), just without consuming them. The actual implementation returns an empty array `[]`, making heartbeat runs completely blind to queued events — they neither consume nor observe them.

The code comment explains the deliberate shift away from peek:
> "repeated peeks would re-trigger the same events on every heartbeat cycle, wasting tokens and risking duplicate side-effects."

That's a valid reason to prefer the "skip entirely" approach, and the test explicitly asserts "not consumed, not even visible". The implementation is internally consistent. But the PR description ("Heartbeat runs still **see** system events in their prompt (via peek)") is now misleading documentation — if someone refers back to this PR to understand the feature, they will come away with the wrong mental model.

This is not a bug, but it's worth noting so future readers of the PR description aren't misled about observable heartbeat behaviour.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (2): Last reviewed commit: "fix: prevent heartbeat runs from consumi..." | Re-trigger Greptile

Comment thread src/infra/system-events.test.ts Outdated
Comment on lines +173 to +199
it("peeks instead of draining when isHeartbeat is true", async () => {
const key = "agent:main:whatsapp:direct:+1234";
enqueueSystemEvent("Exec completed (session abc, code 0)", { sessionKey: key });

// Heartbeat run: events should be visible but NOT consumed
const heartbeatResult = await drainFormattedSystemEvents({
cfg,
sessionKey: key,
isMainSession: false,
isNewSession: false,
isHeartbeat: true,
});
expect(heartbeatResult).toMatch(/Exec completed/);
// Events still in queue after heartbeat peek
expect(peekSystemEvents(key)).toEqual(["Exec completed (session abc, code 0)"]);

// Normal run: events should be drained (consumed)
const normalResult = await drainFormattedSystemEvents({
cfg,
sessionKey: key,
isMainSession: false,
isNewSession: false,
});
expect(normalResult).toMatch(/Exec completed/);
// Events now gone after normal drain
expect(peekSystemEvents(key)).toEqual([]);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Test covers test-only duplicate, not production path

The new test imports drainFormattedSystemEvents from session-updates.ts (the file the PR description calls the "duplicate copy used by tests"), but the production call-site in get-reply-run.ts imports it from session-system-events.ts. Both files received identical changes in this PR, so the behavioural risk is negligible — but if the two files ever diverge in the future, the test won't catch a regression in the production path.

Consider adding at least a smoke-import or a parallel assertion against session-system-events.ts, or add a note explaining the intentional split, so the next reader doesn't have to wonder whether the test gap is deliberate.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/system-events.test.ts
Line: 173-199

Comment:
**Test covers test-only duplicate, not production path**

The new test imports `drainFormattedSystemEvents` from `session-updates.ts` (the file the PR description calls the "duplicate copy used by tests"), but the production call-site in `get-reply-run.ts` imports it from `session-system-events.ts`. Both files received identical changes in this PR, so the behavioural risk is negligible — but if the two files ever diverge in the future, the test won't catch a regression in the production path.

Consider adding at least a smoke-import or a parallel assertion against `session-system-events.ts`, or add a note explaining the intentional split, so the next reader doesn't have to wonder whether the test gap is deliberate.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 0873dec — added an explanatory comment at the import site. The test imports from session-updates.ts (test-facing re-export) rather than session-system-events.ts (production path) due to transitive dependency weight. Both files carry identical isHeartbeat/isEventDrivenHeartbeat changes, and the shared types ensure they can't silently diverge.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b660500ad6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +88 to +90
const queued = params.isHeartbeat
? peekSystemEventEntries(params.sessionKey)
: drainSystemEventEntries(params.sessionKey);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Avoid leaving heartbeat event queues permanently undrained

Using peekSystemEventEntries for every heartbeat run means heartbeat-only sessions never consume queued system events, because get-reply-run now always passes isHeartbeat for heartbeat executions and there is no later drain in that flow. In deployments where a session mostly/only receives heartbeat turns (no regular user turn to drain), the same cron/exec events will be re-processed on each heartbeat and can repeatedly trigger duplicate alerts while the 20-item queue retains stale entries and may evict newer events before they are ever consumed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No longer applicable after 7e30d73 — event-driven heartbeats (exec/cron triggered) now drain events normally. Only periodic heartbeats skip. So exec completions and cron results get consumed by the very heartbeat run that was triggered to handle them.

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-system-event-drain branch from b660500 to cb85757 Compare March 24, 2026 14:40
@nxmxbbd

nxmxbbd commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough reviews!

@chatgpt-codex-connector — Great catch on the P1 (exec-event heartbeats losing visibility). Fixed in 7e30d73: added isEventDrivenHeartbeat flag so event-driven heartbeats (exec completion, cron) drain system events normally, while periodic heartbeats still skip. The P2 (permanently undrained queues) is also resolved by this — events get consumed by the heartbeat run that was triggered to handle them.

@greptile-apps — PR title and description updated to accurately reflect the periodic-vs-event-driven distinction. Title is now "fix: skip system event drain for periodic heartbeat runs". The test file import concern (P2) is noted — both files received identical changes and the test suite convention imports from session-updates.ts.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

To use Codex here, create a Codex account and connect to github.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb85757604

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +88 to +90
const queued = params.isHeartbeat
? []
: drainSystemEventEntries(params.sessionKey);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Expose exec event details during heartbeat runs

Returning an empty queue for isHeartbeat removes all System: event lines from heartbeat prompts, but exec-triggered heartbeats still use buildExecEventPrompt, which explicitly tells the model that command results are “shown in the system messages above” (src/infra/heartbeat-events-filter.ts:40-51, selected in src/infra/heartbeat-runner.ts:511-515). In exec-event runs this now leaves the model without the actual exit/output details, so it can only send generic or incorrect completion updates until a later non-heartbeat turn drains the queue.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — this was a real bug. Fixed in 7e30d73: event-driven heartbeats (exec completion, cron) now drain system events normally via a new isEventDrivenHeartbeat flag. Only periodic (timer-based) heartbeats skip the drain. The prompt that says "The result is shown in the system messages above" now has actual data to reference.

Comment on lines +88 to +90
const queued = params.isHeartbeat
? []
: drainSystemEventEntries(params.sessionKey);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 PR description and implementation diverge on heartbeat visibility

The PR description's "Fix" and "Impact" sections state heartbeat runs will still see system events in their prompt (via peekSystemEventEntries), just without consuming them. The actual implementation returns an empty array [], making heartbeat runs completely blind to queued events — they neither consume nor observe them.

The code comment explains the deliberate shift away from peek:

"repeated peeks would re-trigger the same events on every heartbeat cycle, wasting tokens and risking duplicate side-effects."

That's a valid reason to prefer the "skip entirely" approach, and the test explicitly asserts "not consumed, not even visible". The implementation is internally consistent. But the PR description ("Heartbeat runs still see system events in their prompt (via peek)") is now misleading documentation — if someone refers back to this PR to understand the feature, they will come away with the wrong mental model.

This is not a bug, but it's worth noting so future readers of the PR description aren't misled about observable heartbeat behaviour.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/session-system-events.ts
Line: 88-90

Comment:
**PR description and implementation diverge on heartbeat visibility**

The PR description's "Fix" and "Impact" sections state heartbeat runs will _still see_ system events in their prompt (via `peekSystemEventEntries`), just without consuming them. The actual implementation returns an empty array `[]`, making heartbeat runs completely blind to queued events — they neither consume nor observe them.

The code comment explains the deliberate shift away from peek:
> "repeated peeks would re-trigger the same events on every heartbeat cycle, wasting tokens and risking duplicate side-effects."

That's a valid reason to prefer the "skip entirely" approach, and the test explicitly asserts "not consumed, not even visible". The implementation is internally consistent. But the PR description ("Heartbeat runs still **see** system events in their prompt (via peek)") is now misleading documentation — if someone refers back to this PR to understand the feature, they will come away with the wrong mental model.

This is not a bug, but it's worth noting so future readers of the PR description aren't misled about observable heartbeat behaviour.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 7e30d73 — PR title updated to "fix: skip system event drain for periodic heartbeat runs" and the description now accurately reflects the skip-vs-drain distinction between periodic and event-driven heartbeats. No more peek/skip mismatch.

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-system-event-drain branch from cb85757 to 7e30d73 Compare March 24, 2026 14:58
@nxmxbbd nxmxbbd changed the title fix: prevent heartbeat runs from consuming system events fix: skip system event drain for periodic heartbeat runs Mar 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: S docs Improvements or additions to documentation and removed size: XS labels Mar 24, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c97dc61ef

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/heartbeat-runner.ts Outdated
// so the agent can see the results referenced by their prompt. Periodic
// heartbeats skip the drain to avoid silently consuming events that won't
// be persisted to the session transcript.
const isEventDriven = hasExecCompletion || hasCronEvents;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Classify hook/wake heartbeats as event-driven drains

This commit only sets isEventDrivenHeartbeat from hasExecCompletion || hasCronEvents, so heartbeats triggered for other event reasons (for example hook:wake) are treated as periodic runs and skip drainFormattedSystemEvents. createGatewayHooksRequestHandler enqueues hook text and immediately calls requestHeartbeatNow({ reason: "hook:wake" }), and resolveHeartbeatReasonKind already classifies hook:*/wake as event-driven, so this mismatch causes those queued events to be omitted from the heartbeat prompt and left undelivered until a later non-heartbeat turn.

Useful? React with 👍 / 👎.

@nxmxbbd

nxmxbbd commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 297adcf: isEventDriven now includes preflight.isWakeReason, covering hook:* and wake heartbeat reasons. resolveHeartbeatReasonFlags already classified these correctly — we just were not piping that signal into the drain decision.

The full event-driven classification is now: hasExecCompletion || hasCronEvents || preflight.isWakeReason

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-system-event-drain branch from 297adcf to db8f8a9 Compare March 24, 2026 15:41

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db8f8a9a63

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/heartbeat-runner.ts Outdated
// system events so the agent can see the results referenced by their
// prompt. Periodic heartbeats skip the drain to avoid silently consuming
// events that won't be persisted to the session transcript.
const isEventDriven = hasExecCompletion || hasCronEvents || preflight.isWakeReason;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Classify all queued-event wakes as event-driven

isEventDriven is now limited to hasExecCompletion || hasCronEvents || preflight.isWakeReason, which misses heartbeat wakes that are triggered by queued events but use other reason strings. For example, src/gateway/server-node-events.ts enqueues notification events and wakes with reason: "notifications-event", and src/agents/bash-tools.exec-runtime.ts wakes with reason: \exec:${session.id}:exit`; both evaluate to false here, so the run is treated as periodic and drainFormattedSystemEvents` skips the queue. That prevents those event details from reaching the heartbeat prompt and can delay/drop alerts until an unrelated non-heartbeat turn drains the queue.

Useful? React with 👍 / 👎.

@nxmxbbd

nxmxbbd commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in c384aaf: inverted the logic entirely. Instead of enumerating every event-driven reason (and inevitably missing some), we now treat everything as event-driven by default — only interval and retry are periodic. This closes the gap for notifications-event, exec:${id}:exit, and any future event sources.

const reasonKind = resolveHeartbeatReasonKind(opts.reason);
const isPeriodicHeartbeat = reasonKind === "interval" || reasonKind === "retry";
const isEventDriven = !isPeriodicHeartbeat;

Safer default: new event sources get drain behavior without needing explicit opt-in.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c384aafbcb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/heartbeat-runner.ts Outdated
Comment on lines +722 to +723
const isPeriodicHeartbeat = reasonKind === "interval" || reasonKind === "retry";
const isEventDriven = !isPeriodicHeartbeat;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Treat queued cron interval runs as event-driven drains

isEventDriven is derived only from opts.reason, so interval/retry runs are always marked non-event-driven here. That breaks the existing fallback path where resolveHeartbeatPreflight intentionally processes tagged cron events even on reason: "interval" (see src/infra/heartbeat-runner.ts:430-435 and related tests): the run builds a cron prompt from queued entries, but drainFormattedSystemEvents skips draining when isHeartbeat && !isEventDrivenHeartbeat (src/auto-reply/reply/session-system-events.ts:94). In that scenario, the same cron event remains in the queue and can be re-sent on every interval heartbeat instead of being consumed once.

Useful? React with 👍 / 👎.

@nxmxbbd

nxmxbbd commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 6495803: isEventDriven = !isPeriodicHeartbeat || hasExecCompletion || hasCronEvents

An interval/retry heartbeat that discovers tagged cron or exec events in the queue now drains them. Both variables (hasExecCompletion, hasCronEvents) are already resolved from resolveHeartbeatRunPrompt in the same scope, so this is a one-line addition to the condition.

This closes the edge case where cron events arrive between heartbeat cycles and get picked up by the next interval run — the prompt references them via buildCronEventPrompt, so they must be drained.

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-system-event-drain branch 2 times, most recently from 9e799b3 to def2bfa Compare March 25, 2026 22:58

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: def2bfa800

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/heartbeat-runner.ts Outdated
// The prompt already references those events, so we must drain them too.
const reasonKind = resolveHeartbeatReasonKind(opts.reason);
const isPeriodicHeartbeat = reasonKind === "interval" || reasonKind === "retry";
const isEventDriven = !isPeriodicHeartbeat || hasExecCompletion || hasCronEvents;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Preserve queued exec events on interval fallback heartbeats

The new isEventDriven check treats interval/retry runs as non-event-driven unless hasExecCompletion/hasCronEvents is true, but hasExecCompletion is never computed for interval/retry unless preflight is already inspecting pending events. This means queued exec events can get stuck indefinitely after an event wake is missed (for example, when heartbeats were temporarily disabled via set-heartbeats and later re-enabled): the next interval run is marked periodic, drainFormattedSystemEvents skips the drain, and the exec completion remains queued until some unrelated non-periodic run occurs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 190755d — periodic runs now check preflight.pendingEventEntries.length > 0 as a safety net. If a wake was missed, the next interval run picks up queued events instead of leaving them stuck.

@nxmxbbd

nxmxbbd commented Mar 25, 2026

Copy link
Copy Markdown
Contributor Author

Good catch — hasExecCompletion was indeed always false for interval/retry runs (derived from pendingEvents which is [] when shouldInspectPendingEvents is false). Removed the dead branch in 1c80ed2 and updated the comment to explain why exec completions are safe: they trigger their own heartbeat wake with reason exec:<id>:exit, which resolves to reasonKind "other" → !isPeriodicHeartbeat → drain fires normally.

hasCronEvents does work for periodic runs (computed from raw pendingEventEntries via contextKey tag, not gated by shouldInspectPendingEvents), so that fallback is kept.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c80ed21bf

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// "exec:<id>:exit" → reasonKind "other" → !isPeriodicHeartbeat → drain).
const reasonKind = resolveHeartbeatReasonKind(opts.reason);
const isPeriodicHeartbeat = reasonKind === "interval" || reasonKind === "retry";
const isEventDriven = !isPeriodicHeartbeat || hasCronEvents;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Drain queued non-cron events on interval fallback runs

The new isEventDriven gate only treats interval/retry heartbeats as drainable when hasCronEvents is true, so any queued non-cron system events (for example notifications-event entries with contextKey: "notification:*") are never drained on interval runs after an event wake is missed. This is reachable when an event wake is consumed while heartbeats are disabled (runHeartbeatOnce returns skipped: "disabled", and heartbeat-wake only retries requests-in-flight), after which only periodic interval wakes fire; those runs set isEventDrivenHeartbeat false and drainFormattedSystemEvents skips the queue, so alerts can remain stuck indefinitely and eventually be evicted by the 20-item cap.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same fix as above (190755d). hasQueuedEvents = preflight.pendingEventEntries.length > 0 catches all event types — notifications, exec completions, anything queued — not just cron. If the wake was missed, the interval fallback picks them up.

@nxmxbbd

nxmxbbd commented Mar 26, 2026

Copy link
Copy Markdown
Contributor Author

Both P2s from @chatgpt-codex-connector on commit def2bfa and 1c80ed2 describe the same underlying edge case: if a wake is missed (e.g. heartbeats were temporarily disabled when the event arrived), the next periodic interval run would skip the drain — leaving non-cron events stuck until a user message or another event-driven wake came along.

My take: the trigger conditions are narrow (disable → re-enable heartbeats, with no user messages in between), and in practice every event type fires its own event-driven wake that handles drain on the happy path. But the fix is one line and adds zero complexity, so it is worth closing the gap as a defensive safety net rather than leaving a known hole.

Fixed in 190755d: periodic runs now check preflight.pendingEventEntries.length > 0. If any events are queued, the run is promoted to event-driven so they get drained. preflight.pendingEventEntries is already peeked earlier in resolveHeartbeatPreflight, so there is no extra queue access.

const hasQueuedEvents = preflight.pendingEventEntries.length > 0;
const isEventDriven = !isPeriodicHeartbeat || hasCronEvents || hasQueuedEvents;

This subsumes the previous hasCronEvents fallback (cron entries are a subset of queued entries), but I kept it explicit for readability — it documents the intent that tagged cron events are the primary periodic-run case, with hasQueuedEvents as the catch-all safety net.

nxmxbbd added 12 commits April 11, 2026 04:01
executeMainSessionCronJob previously set wakeRequested only for
wakeMode=now.  next-heartbeat cron events were enqueued without the
flag, so if the requestHeartbeatNow wake was missed (e.g. heartbeats
temporarily disabled), periodic runs could only discover them via the
isCronSystemEvent text filter — which excludes payloads containing
'exec finished'.  Mark all cron events as wakeRequested so periodic
heartbeats always drain them regardless of payload text content.
Heartbeat runs execute synchronous commands (systemctl, node scripts, etc.)
that fire maybeNotifyOnExit on completion, which calls requestHeartbeatNow
and causes the heartbeat to re-trigger itself in a loop.

The existing pollWaiting guard only covers 'process poll' scenarios where
the agent is actively waiting for a background process. Synchronous execs
in heartbeat checks don't go through poll, so they bypass that guard.

Fix: when trigger is 'heartbeat', pass notifyOnExit: false to the exec
tool defaults, preventing maybeNotifyOnExit from firing for any exec
spawned during the heartbeat run.
The previous fix was too broad and broke background exec completion
notifications in heartbeat workflows. The !session.backgrounded guard
in maybeNotifyOnExit already excludes synchronous execs from triggering
heartbeat wakes, so background execs should continue to notify normally.

Fixes P1 issue raised by @chatgpt-codex-connector[bot].
…events

- Update bash-tools.exec-runtime.test.ts assertions to expect wakeRequested: true
- Update cron/service/timer.test.ts assertions to expect wakeRequested: true
- These changes align with our fix for RC2 (hook/cron events not tagged as wake-requested)
When removeExecEventsForSession removes entries but leaves others in the queue,
update lastText/lastContextKey to point to the new tail to prevent legitimate
subsequent events from being incorrectly rejected as consecutive duplicates.

Follows the same pattern as drainWakeRequestedEvents.
Ensures restart sentinel fallback for missing sessionKey uses wakeRequested: true
and triggers requestHeartbeatNow, so the notice gets drained properly in
heartbeat-only sessions instead of remaining stuck in the queue.

Fixes inline comment from @chatgpt-codex-connector[bot] on server-restart-sentinel.ts:40
- Replace broad substring matching in removeExecEventsForSession with specific regex pattern for exec events
- Fix poll suppression race condition by using counter instead of boolean flag for concurrent poll operations
- Add hasWakeRequestedEvents check to shouldInspectPendingEvents logic
- Ensures wake events are considered when determining event-driven heartbeats
- Prevents wake events from being drained but ignored on periodic heartbeats
- Adds peekWakeRequestedEvents utility function

Fixes bot comment: avoid draining wake events on generic periodic prompts
…trust tests

- Update exec denied test to expect wakeRequested: true parameter
- Update hook agent trust tests to expect wakeRequested: true parameter
- Fixes CI test failures for PR openclaw#53740
… tag wake-paired producers

- Add hasWakeRequestedEvents to shouldBypassFileGates in heartbeat-runner.ts
  Ensures wake-requested events can execute even with empty HEARTBEAT.md files
- Add wakeRequested: true to enqueueSystemEvent calls in cli-runner/execute.ts and acp-spawn-parent-stream.ts
  Ensures events paired with requestHeartbeatNow are recoverable by periodic heartbeats
@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-system-event-drain branch from efd7529 to 9379402 Compare April 10, 2026 20:01

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9379402917

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/heartbeat-runner.ts Outdated
Comment on lines +513 to +518
const hasWakeRequestedEvents = pendingEventEntries.some((event) => event.wakeRequested);
const shouldInspectPendingEvents =
reasonFlags.isExecEventReason || reasonFlags.isCronEventReason || hasTaggedCronEvents;
reasonFlags.isExecEventReason ||
reasonFlags.isCronEventReason ||
hasTaggedCronEvents ||
hasWakeRequestedEvents;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Avoid scanning base wake queues in isolated heartbeat runs

Including hasWakeRequestedEvents in preflight inspection/bypass makes interval/retry heartbeats treat base-session wake entries as runnable work, but runHeartbeatOnce executes isolated heartbeats on a different :heartbeat session key. In isolated mode those base-session events are never drained by the run, so the same queued wake events remain visible on every periodic tick and can repeatedly trigger duplicate heartbeat handling/alerts. Limit this wakeRequested preflight path to non-isolated runs (or move the events into the isolated queue before running).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@chatgpt-codex-connector Good catch — fixed in fd9ee8e.

The issue was that resolveHeartbeatPreflight scanned base-session wake events to determine shouldBypassFileGates and shouldInspectPendingEvents, but isolated heartbeats run on :heartbeat session keys and cannot drain those base-session events. This caused the same queued wake events to be repeatedly detected as runnable work on every periodic tick.

Now excludes base-session wake events from preflight inspection when heartbeat.isolatedSession=true.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Addressed P1 bot feedback: when heartbeat.isolatedSession=true, isolated
sessions run on :heartbeat keys and cannot drain base-session wake events.
Including hasWakeRequestedEvents in preflight inspection made periodic
heartbeats repeatedly detect the same base-session wake events as runnable
work, causing duplicate heartbeat handling.

Now excludes base-session wake events from shouldInspectPendingEvents and
shouldBypassFileGates when useIsolatedSession=true.
Resolved merge conflict in src/infra/heartbeat-runner.ts by combining:
- Our selective drain logic (isEventDrivenHeartbeat field)
- Upstream timeout handling (timeoutOverrideSeconds field)
- Modern object construction pattern with spread syntax

The merge preserves the core functionality of selective system event
drain for heartbeat runs while incorporating upstream improvements
to timeout configuration.
@nxmxbbd

nxmxbbd commented Apr 13, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #65757 — clean squash onto latest main with all review feedback incorporated.

@nxmxbbd nxmxbbd closed this Apr 13, 2026
@nxmxbbd
nxmxbbd deleted the fix/heartbeat-system-event-drain branch October 27, 2026 07:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant