Repository navigation
Conversation
Greptile SummaryThis 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: Key points from the review:
Confidence Score: 5/5
Prompt To Fix All With AIThis 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 |
| 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([]); | ||
| }); |
There was a problem hiding this 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.
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.There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
| const queued = params.isHeartbeat | ||
| ? peekSystemEventEntries(params.sessionKey) | ||
| : drainSystemEventEntries(params.sessionKey); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
b660500 to
cb85757
Compare
|
Thanks for the thorough reviews! @chatgpt-codex-connector — Great catch on the P1 (exec-event heartbeats losing visibility). Fixed in 7e30d73: added @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 |
|
To use Codex here, create a Codex account and connect to github. |
There was a problem hiding this comment.
💡 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".
| const queued = params.isHeartbeat | ||
| ? [] | ||
| : drainSystemEventEntries(params.sessionKey); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| const queued = params.isHeartbeat | ||
| ? [] | ||
| : drainSystemEventEntries(params.sessionKey); |
There was a problem hiding this 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.
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.There was a problem hiding this comment.
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.
cb85757 to
7e30d73
Compare
There was a problem hiding this comment.
💡 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".
| // 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; |
There was a problem hiding this comment.
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 👍 / 👎.
|
Fixed in 297adcf: The full event-driven classification is now: |
297adcf to
db8f8a9
Compare
There was a problem hiding this comment.
💡 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".
| // 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; |
There was a problem hiding this comment.
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 👍 / 👎.
|
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 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. |
There was a problem hiding this comment.
💡 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".
| const isPeriodicHeartbeat = reasonKind === "interval" || reasonKind === "retry"; | ||
| const isEventDriven = !isPeriodicHeartbeat; |
There was a problem hiding this comment.
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 👍 / 👎.
|
Fixed in 6495803: An interval/retry heartbeat that discovers tagged cron or exec events in the queue now drains them. Both variables ( 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 |
9e799b3 to
def2bfa
Compare
There was a problem hiding this comment.
💡 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".
| // 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Good catch —
|
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Both P2s from 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 const hasQueuedEvents = preflight.pendingEventEntries.length > 0;
const isEventDriven = !isPeriodicHeartbeat || hasCronEvents || hasQueuedEvents;This subsumes the previous |
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
efd7529 to
9379402
Compare
There was a problem hiding this comment.
💡 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".
| const hasWakeRequestedEvents = pendingEventEntries.some((event) => event.wakeRequested); | ||
| const shouldInspectPendingEvents = | ||
| reasonFlags.isExecEventReason || reasonFlags.isCronEventReason || hasTaggedCronEvents; | ||
| reasonFlags.isExecEventReason || | ||
| reasonFlags.isCronEventReason || | ||
| hasTaggedCronEvents || | ||
| hasWakeRequestedEvents; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
To use Codex here, create a Codex account and connect to github.
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.
|
Superseded by #65757 — clean squash onto latest main with all review feedback incorporated. |
Problem
Two related issues with system event handling in heartbeat runs:
1. Periodic heartbeats destructively drain all system events
When
heartbeat.sessiontargets a shared session (e.g.whatsapp:direct:+1234), the heartbeat run and normal user turns share the same session. On each run,drainFormattedSystemEvents()callsdrainSystemEventEntries()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 loginthat finished while the heartbeat was running).2.
process pollandmaybeNotifyOnExitproduce duplicate notificationsWhen an agent uses
process pollto wait for a backgrounded command, the process exit triggers two notification paths simultaneously:session.exited→ returns exit result directly to the agentmaybeNotifyOnExit()→enqueueSystemEvent()+requestHeartbeatNow()→ heartbeat fires with redundant "Exec completed" messageThis 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:
wakeRequested: true): enqueued alongsiderequestHeartbeatNow()--- exec completions, cron results, hook events, notifications, restart sentinels. These have a dedicated event-driven wake to consume them.Heartbeat runs are handled differently based on their trigger:
wakeRequestedevents 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
pollWaitingflag onProcessSessionis set totruewhile 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 latemaybeNotifyOnExitcall) and callsremoveExecEventsForSession()to clean up any events that raced into the queue beforepollWaitingwas set. This covers the narrow window between consecutive poll calls.Fire-and-forget processes are unaffected:
pollWaitingis only set during active poll waits. Background processes that nobody polls still get fullmaybeNotifyOnExit→ system event → heartbeat wake behavior.Implementation
ProcessSessioninterface (bash-process-registry.ts): Add optionalpollWaiting?: booleanfield.maybeNotifyOnExit()(bash-tools.exec-runtime.ts): Addsession.pollWaitingto the early-return guard.Poll handler (
bash-tools.process.ts):pollWaiting = truebefore entering the wait looppollWaiting = falseafter the wait loop completesexitNotified = trueand callremoveExecEventsForSession()to clean up any raced eventsremoveExecEventsForSession()(system-events.ts): New function that removes queued events matching a specific exec session's ID prefix (consistent withmaybeNotifyOnExit'ssession.id.slice(0, 8)format). Cleans up empty queue entries.SystemEventtype (system-events.ts): Add optionalwakeRequested?: booleanfield, propagated throughenqueueSystemEvent()options.drainWakeRequestedEvents()(system-events.ts): New function that drains only events tagged withwakeRequested, leaving the rest queued.Enqueue call sites --- tagged
wakeRequested: truewhere paired withrequestHeartbeatNow():task-registry.ts: task completion + blocked followupserver-node-events.ts: notifications, exec completionsserver-restart-sentinel.ts: restart wake eventsserver/hooks.ts: hook events (conditional onwakeMode === "now")server-cron.ts: cron deps wrapper (passes through to cron service)cron/service/timer.ts: failure alerts, main-session jobs, wake eventscron/service/jobs.ts: auto-disabled notificationsDrain logic (
session-system-events.ts): Periodic heartbeats calldrainWakeRequestedEvents()instead of skipping entirely. Event-driven heartbeats and normal turns still calldrainSystemEventEntries()(drain all).isEventDrivenHeartbeatflag: 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: AddpollWaitingtoProcessSessioninterfacebash-tools.exec-runtime.ts: AddpollWaitingcheck tomaybeNotifyOnExitguardbash-tools.process.ts: Set/clearpollWaitingaround poll wait loop; setexitNotifiedand callremoveExecEventsForSessionon exitsystem-events.ts: AddwakeRequestedtoSystemEventtype and options; adddrainWakeRequestedEvents(); addremoveExecEventsForSession()session-system-events.ts: Periodic heartbeats usedrainWakeRequestedEvents()instead of empty arrayheartbeat-runner.ts: Updated comments to reflect selective drain behaviortask-registry.ts,server-node-events.ts,server-restart-sentinel.ts,server/hooks.ts,server-cron.ts: Tag enqueue calls withwakeRequested: truecron/service/state.ts: UpdateenqueueSystemEventdep type signaturecron/service/timer.ts,cron/service/jobs.ts: Tag enqueue calls withwakeRequestedsystem-events.test.ts: Add tests fordrainWakeRequestedEvents,removeExecEventsForSession, and periodic heartbeat wake-drain integrationBackward Compatibility
wakeRequestedandpollWaitingare optional fields --- existing code that does not set them defaults toundefined(falsy), which is the safe default.drainWakeRequestedEventsandremoveExecEventsForSessionare additive --- no existing function signatures change.Impact