Repository navigation
fix(agents): heartbeats lose all conversation context on claude-cli chat↔heartbeat transitions - #121509
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 12, 2026, 5:07 AM ET / 09:07 UTC. ClawSweeper reviewWhat this changesThis PR makes direct synthetic reply turns, including heartbeats, compute the same session-stable delivery policy and CLI binding facts as dispatched chat turns. Regression provenancePossible regression — probable (reproduction; failure trace; reviewed change). No predecessor PR is attributed. Merge readinessKeep open. The refreshed branch resolves the prior persisted-model concern through the runtime’s canonical stored-override resolver and has no actionable code finding, but GitHub reports a dirty merge state and incomplete exact-head checks. Priority: P1 Review scores
Verification
How this fits togetherChat dispatch injects stable reply-policy facts, while heartbeats enter the reply runner directly. Both paths determine whether Claude CLI resumes the existing conversation or starts a fresh session. flowchart LR
A[Chat or heartbeat turn] --> B[Reply preparation]
B --> C[Session-stable reply policy]
C --> D[CLI binding facts]
D --> E{Binding policy matches}
E -->|yes| F[Resume conversation]
E -->|no| G[Reset CLI session]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +240, Tests +179, Generated 0. Total +419 across 25 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land only after the current head is cleanly mergeable and its checks finish; retain the shared visible-replies and stable-availability owners so synthetic and dispatched turns continue to derive identical binding facts. Do we have a high-confidence way to reproduce the issue? Yes—source establishes that direct heartbeats previously omitted the stable policy hash, and the PR includes an after-fix production trace plus a focused direct-heartbeat binding regression. Is this the best way to solve the issue? Yes—the shared policy now uses the same persisted-model authority as runtime and dispatch, avoiding the incorrect alternative of treating cached runtime metadata as the selected model. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against d44f70eb4bd5. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (8 earlier review cycles)
|
77c9f21 to
75080a6
Compare
|
Exact-head CI is red only where current main is red: every failing lane on this PR (check-lint, check-test-types, checks-node-compact-{small-2,small-9,small-11,small-12,large-6}) fails identically on main's own run at 8747575 — this PR's rebase base, which contains none of this change. The two check-test-types errors are in files byte-identical to main (managed-image-actions.e2e.test.ts, chat-message.test.ts, introduced around #77017). Will rebase for a green exact-head run once main recovers. |
|
A second (local, multi-agent) review pass on this branch surfaced that the new stable-mode fallback is a simplified parallel of dispatch's computation, with four config-dependent divergence vectors where the chat↔heartbeat ping-pong would persist: (1) no messageToolAvailable downgrade, (2) response-tool heartbeats (codex-harness default) bypass the fallback because their effective turn mode fills the stable slot, (3) persisted-entry vs live-ctx facts for stale/missing chatType, (4) missing ExplicitDeliverRoute on the internal-channel branch. None are regressions — those configs ping-pong on current main too — and the claude-cli/direct default path this PR targets is fixed and live-verified. Scope question for review: should this PR grow to unify the stable-mode computation into one canonical owner (reuse resolveHarnessSourceVisibleRepliesDefault, thread messageToolAvailable, enforce that synthetic turns can't write their effective mode into the stable fact), or land as-is with those vectors as a named follow-up issue? Happy to do either; the unification roughly doubles the PR's blast surface into dispatch internals. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
75080a6 to
6916d35
Compare
6916d35 to
6794ecd
Compare
|
Does the larger scope change the priority? Context loss is a really unfortunate outcome for users. |
6794ecd to
3986378
Compare
Heartbeat wakes and other direct getReplyFromConfig callers bypass dispatch, so no session-stable delivery mode reached their CLI binding facts and prepare computed no messageToolPolicyHash, while dispatched chat turns hashed the stable mode. resolveCliSessionReuse treats that one-sided hash as a policy change, hard-invalidating the binding on every chat<->heartbeat transition and leaving heartbeats to run in fresh CLI sessions with no conversation history (historyPrompt=none). Extract the synthetic-turn stable-mode resolution that prepareAgentCommandExecution already used into resolveSessionStableReplyMode, and apply it in prepareReplyRunContext whenever a synthetic turn arrives without dispatch's injected mode, so every turn kind on a session derives the same binding facts and hash. Fixes openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]>
…owner Consolidate the synthetic-turn stable-mode resolution onto dispatch's own policy pieces instead of a simplified parallel resolver: - resolveVisibleRepliesPolicy is extracted from dispatch prepare-context (configured visible-replies guard + harness default chain) and shared, so the fallback and dispatch cannot drift on harness defaults, live-vs-entry chat facts, or ExplicitDeliverRoute. - The stable fact now applies dispatch's messageToolAvailable downgrade via the canonical tool-policy resolvers: tool-only delivery with a policy-denied message tool records automatic, matching dispatch. - Synthetic turns no longer fall back to their effective turn mode: a response-tool heartbeat's message_tool_only is per-turn enforcement, not session policy, and previously bypassed the stable fallback entirely. Regression coverage: response-tool heartbeat facts match dispatched turns, and a message-tool-denied config downgrades the synthetic stable fact. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]>
Dispatch's stable-mode downgrade used the turn's sender-aware message-tool availability, so a sender-scoped message denial hashed the stable policy as automatic on chat turns while sender-less synthetic turns hashed tool-only — the same binding reset loop on another axis. resolveStableMessageToolAvailability becomes the one sender-independent owner: dispatch passes it as sessionStableMessageToolAvailable for the stable-mode resolution only (effective per-turn enforcement keeps the sender-aware verdict), and synthetic binding facts already consume it. Computed only when the visible-replies candidate is message_tool. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]>
…e plumbing Third-pass review fixes on the openclaw#121485 consolidation: - Strip system-event wake providers ("heartbeat", "cron-event") from the stable context and resolve origin-less entries as internal, so synthetic facts take the same internal-channel branch dispatch's live webchat turns do instead of falling through to harness defaults. - Fall back to persisted session facts (delivery channel/origin, groupId, groupChannel/subject, accountId) for the sender-independent availability stack, so bare-ctx callers like command prepare resolve the same group/account-scoped policies as dispatched turns; dispatch now passes its session entry too. - Collapse the redundant second mode resolution into the availability downgrade, surface dispatch's injected stable mode separately from resolvePromptSourceReplyMode so the synthetic slot has one owner, and reuse resolveTurnModelOverride instead of an inline copy. - Refresh docs/.generated/plugin-sdk-api-baseline.jsonl: closure hashes only (17 exports, zero declaration changes, verified) — plugin-sdk reply/meeting entrypoints transitively bundle the reply pipeline this branch refactors. Regression: origin-less entry heartbeat resolves internal-automatic facts. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]>
Mechanical rebase refresh onto d3696f8: subagent-capabilities moved to src/agents/subagents/spawn/, and the plugin-sdk API baseline is now per-entrypoint content hashes (openclaw#122082) — regenerated for the reply-pipeline closure this branch touches. Co-Authored-By: Claude Fable 5 <[email protected]>
6a65141 to
966d9bc
Compare
|
Re: "Use the persisted session model for stable reply defaults" — investigated, implemented, and reverted with evidence. I implemented the requested candidate (entry.modelProvider/model in the shared resolver) with a fail-pre-fix regression test. Exact-head CI then failed src/auto-reply/reply/dispatch-from-config.test.ts > "uses configured defaults before cached Codex runtime metadata" (send-policy-routing.test-utils.ts): main's design table explicitly pins that an unlocked session's cached runtime-model metadata does not outrank the configured default. The same table already covers this finding's scenarios: locked sessions keep their harness ("keeps locked supervised Codex delivery defaults across outer model overrides", via modelSelectionLocked, which resolveVisibleRepliesPolicy pins), and model-switched sessions follow their stored override ("honors model overrides before cached Codex direct source delivery defaults" — asserting lt). The replaced command path's entry.modelProviderread predated that design and was the divergent side; unifying it onto the dispatch-owned resolver is this PR's fix. Because dispatch and synthetic turns share one resolver witputs, every turn kind derives the same stable mode andhash in all of these session states — there is no synthetic-turn hash divergence to repair. Merge-risk items: exact-head CI is green on 966d9bc (run 31577582977). On production LOC (+240): the growth is the single policy owner (session-stable-reply-mode.ts, +182) replacintions and one missing one; it reuses the existingdispatch model-candidate selection rather than adding a parallel one. A further consolidation (dispatch's inline sender-aware message-tool stack delegating to the shared sender-sible as a follow-up but touches the same testedsurface, so I kept it out of this PR. |
|
See comment above re: P1 @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
# Conflicts: # docs/.generated/plugin-sdk-api-baseline/agent-harness-runtime.json # docs/.generated/plugin-sdk-api-baseline/agent-harness.json # docs/.generated/plugin-sdk-api-baseline/channel-core.json # docs/.generated/plugin-sdk-api-baseline/channel-entry-contract.json # docs/.generated/plugin-sdk-api-baseline/channel-message.json # docs/.generated/plugin-sdk-api-baseline/channel-outbound.json # docs/.generated/plugin-sdk-api-baseline/channel-plugin-common.json # docs/.generated/plugin-sdk-api-baseline/core.json # docs/.generated/plugin-sdk-api-baseline/discord.json # docs/.generated/plugin-sdk-api-baseline/inbound-reply-dispatch.json # docs/.generated/plugin-sdk-api-baseline/meeting-runtime.json # docs/.generated/plugin-sdk-api-baseline/plugin-entry.json # docs/.generated/plugin-sdk-api-baseline/plugin-runtime.json # docs/.generated/plugin-sdk-api-baseline/provider-catalog-runtime.json # docs/.generated/plugin-sdk-api-baseline/tool-plugin.json # docs/.generated/plugin-sdk-api-baseline/webhook-ingress.json
# Conflicts: # docs/.generated/plugin-sdk-api-baseline/agent-harness-runtime.json # docs/.generated/plugin-sdk-api-baseline/agent-harness.json # docs/.generated/plugin-sdk-api-baseline/channel-core.json # docs/.generated/plugin-sdk-api-baseline/channel-entry-contract.json # docs/.generated/plugin-sdk-api-baseline/channel-message.json # docs/.generated/plugin-sdk-api-baseline/channel-outbound.json # docs/.generated/plugin-sdk-api-baseline/channel-plugin-common.json # docs/.generated/plugin-sdk-api-baseline/core.json # docs/.generated/plugin-sdk-api-baseline/discord.json # docs/.generated/plugin-sdk-api-baseline/inbound-reply-dispatch.json # docs/.generated/plugin-sdk-api-baseline/meeting-runtime.json # docs/.generated/plugin-sdk-api-baseline/plugin-entry.json # docs/.generated/plugin-sdk-api-baseline/plugin-runtime.json # docs/.generated/plugin-sdk-api-baseline/provider-catalog-runtime.json # docs/.generated/plugin-sdk-api-baseline/tool-plugin.json # docs/.generated/plugin-sdk-api-baseline/webhook-ingress.json
|
Merged via squash.
|
…hat↔heartbeat transitions (openclaw#121509) * fix(agents): resolve session-stable reply mode for direct resolver turns Heartbeat wakes and other direct getReplyFromConfig callers bypass dispatch, so no session-stable delivery mode reached their CLI binding facts and prepare computed no messageToolPolicyHash, while dispatched chat turns hashed the stable mode. resolveCliSessionReuse treats that one-sided hash as a policy change, hard-invalidating the binding on every chat<->heartbeat transition and leaving heartbeats to run in fresh CLI sessions with no conversation history (historyPrompt=none). Extract the synthetic-turn stable-mode resolution that prepareAgentCommandExecution already used into resolveSessionStableReplyMode, and apply it in prepareReplyRunContext whenever a synthetic turn arrives without dispatch's injected mode, so every turn kind on a session derives the same binding facts and hash. Fixes openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(agents): derive synthetic binding facts from the dispatch policy owner Consolidate the synthetic-turn stable-mode resolution onto dispatch's own policy pieces instead of a simplified parallel resolver: - resolveVisibleRepliesPolicy is extracted from dispatch prepare-context (configured visible-replies guard + harness default chain) and shared, so the fallback and dispatch cannot drift on harness defaults, live-vs-entry chat facts, or ExplicitDeliverRoute. - The stable fact now applies dispatch's messageToolAvailable downgrade via the canonical tool-policy resolvers: tool-only delivery with a policy-denied message tool records automatic, matching dispatch. - Synthetic turns no longer fall back to their effective turn mode: a response-tool heartbeat's message_tool_only is per-turn enforcement, not session policy, and previously bypassed the stable fallback entirely. Regression coverage: response-tool heartbeat facts match dispatched turns, and a message-tool-denied config downgrades the synthetic stable fact. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(agents): keep the session-stable reply mode sender-independent Dispatch's stable-mode downgrade used the turn's sender-aware message-tool availability, so a sender-scoped message denial hashed the stable policy as automatic on chat turns while sender-less synthetic turns hashed tool-only — the same binding reset loop on another axis. resolveStableMessageToolAvailability becomes the one sender-independent owner: dispatch passes it as sessionStableMessageToolAvailable for the stable-mode resolution only (effective per-turn enforcement keeps the sender-aware verdict), and synthetic binding facts already consume it. Computed only when the visible-replies candidate is message_tool. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(agents): derive stable reply facts from session surfaces, not wake plumbing Third-pass review fixes on the openclaw#121485 consolidation: - Strip system-event wake providers ("heartbeat", "cron-event") from the stable context and resolve origin-less entries as internal, so synthetic facts take the same internal-channel branch dispatch's live webchat turns do instead of falling through to harness defaults. - Fall back to persisted session facts (delivery channel/origin, groupId, groupChannel/subject, accountId) for the sender-independent availability stack, so bare-ctx callers like command prepare resolve the same group/account-scoped policies as dispatched turns; dispatch now passes its session entry too. - Collapse the redundant second mode resolution into the availability downgrade, surface dispatch's injected stable mode separately from resolvePromptSourceReplyMode so the synthetic slot has one owner, and reuse resolveTurnModelOverride instead of an inline copy. - Refresh docs/.generated/plugin-sdk-api-baseline.jsonl: closure hashes only (17 exports, zero declaration changes, verified) — plugin-sdk reply/meeting entrypoints transitively bundle the reply pipeline this branch refactors. Regression: origin-less entry heartbeat resolves internal-automatic facts. Refs openclaw#121485 Co-Authored-By: Claude Fable 5 <[email protected]> * chore: adapt to main module moves and split API baseline Mechanical rebase refresh onto 7866366: subagent-capabilities moved to src/agents/subagents/spawn/, and the plugin-sdk API baseline is now per-entrypoint content hashes (openclaw#122082) — regenerated for the reply-pipeline closure this branch touches. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #121485
What Problem This Solves
Fixes an issue where operators running a claude-cli-backed agent with heartbeats enabled would get heartbeat turns that are blind to the conversation happening on the same session. Every transition between a chat turn and a heartbeat turn
hard-invalidated the CLI session binding (
cli session reset: reason=message-policy— 13×/day in the reporting deployment, at every chat↔heartbeat boundary and never inside same-kind stretches), and the replacement heartbeat session started with no history at all (historyPrompt=none). Observed symptom: heartbeats don't have context from chat messages that happened prior.Why This Change Was Made
Dispatched chat turns get the session-stable delivery mode injected into their binding facts, so prepare computes a
messageToolPolicyHash; heartbeat wakes (and other directgetReplyFromConfigcallers) bypass dispatch, resolved no mode, and computed no hash — andresolveCliSessionReusetreats a one-sided hash as a policy change. This is the same turn-kind ping-pong #99595 fixed for room-event vs addressed turns; heartbeats were the one turn kind never broughtunder its session-stable-facts invariant (
prepareAgentCommandExecutionalready honors it for inter-session announce turns).The fix records the fact at the producer: the synthetic-turn stable-mode resolution that
prepareAgentCommandExecutionalready used is extracted intoresolveSessionStableReplyMode, andprepareReplyRunContextnow applies it whenever a synthetic turn arrives without dispatch's injected mode — so every turn kind on a session derives the same binding facts and hash. No change to the reuse comparison itself. Bindings persisted by pre-fix heartbeat turns lack the hash, so the first policied turn after upgrade invalidates once, then the binding is stable.User Impact
Heartbeats on claude-cli deployments now resume the same CLI session as chat turns: they see the conversation that just happened and act on it. Prompt-cache reuse survives chat↔heartbeat transitions instead of being discarded up to dozens of times per day. No config changes needed; this is the default path (
dmScope: main+ heartbeats).Evidence
Gateway log from the reporting deployment (full day): every
invalidated:message-policyreset sits exactly at a chat↔heartbeat boundary; heartbeat→heartbeat stretches (7 turns, 18:51–21:51) and user→user stretches reuse cleanly. Binding dumps show the mechanism: heartbeat-persisted bindings omitmessageToolPolicyHash; chat-persisted bindings carrysha256('{"sourceReplyDeliveryMode":"automatic","requireExplicitMessageTarget":false}').Regression test: extended the #99595 stable-facts table test in
get-reply-run.media-only.test.tswith a fourth run shaped like a production heartbeat wake (isHeartbeat: true, no injected delivery modes) asserting its binding facts equal the dispatched turns' facts — red without the fix (both table cases), green with it.Validation (local, Crabbox routing unavailable in this environment):
node scripts/run-vitest.mjs src/auto-reply/reply/get-reply-run.media-only.test.ts— 111/111node scripts/run-vitest.mjs src/commands/agent.test.ts— 43/43 (rewired caller)node scripts/run-vitest.mjs src/agents/cli-session.test.ts src/agents/cli-runner/prepare.test.ts— green (untouched vs main)pnpm check:import-cycles— 0 cycles (new module)pnpm tsgo,scripts/run-oxlint.mjs,pnpm format— cleanLive verification (reporting deployment, 2026-08-10)
Gateway restarted onto this fix at 01:22:52. Heartbeat interval temporarily set to 1m to exercise chat↔heartbeat transitions quickly.
Before (2026-08-09, pre-fix — same deployment, one day of
cli execlines):every chat↔heartbeat transition invalidated, 13/13; heartbeat resets got no history at all:
After (post-restart):
11171aec0e40) across user turns and heartbeat turns — the chat→heartbeat transition at 01:33:13 resumes instead of resetting, which never happened pre-fix (0 occurrences in the full prior day's log).Upgrade behavior (accepted tradeoff)
Bindings persisted before this fix lack a messageToolPolicyHash, so the first policied turn after upgrade invalidates once and re-persists a complete stable binding — that's the single 01:23:01 reset visible in the trace above. CLI session bindings are reuse-cache, not persistent user state, so a bounded one-time rebuild is preferred over a backfill migration per the repo's storage doctrine; steady state afterward is zero transition resets.