Skip to content

fix(agents): heartbeats lose all conversation context on claude-cli chat↔heartbeat transitions - #121509

Merged
obviyus merged 7 commits into
openclaw:mainfrom
jtatum:fix/heartbeat-cli-session-pingpong
Aug 12, 2026
Merged

obviyus merged 7 commits into
openclaw:mainfrom
jtatum:fix/heartbeat-cli-session-pingpong

Conversation

@jtatum

@jtatum jtatum commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

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 direct getReplyFromConfig callers) bypass dispatch, resolved no mode, and computed no hash — and resolveCliSessionReuse treats 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 brought
under its session-stable-facts invariant (prepareAgentCommandExecution already honors it for inter-session announce turns).

The fix records the fact at the producer: the synthetic-turn stable-mode resolution that prepareAgentCommandExecution already used is extracted into resolveSessionStableReplyMode, and prepareReplyRunContext now 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-policy reset 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 omit messageToolPolicyHash; chat-persisted bindings carry sha256('{"sourceReplyDeliveryMode":"automatic","requireExplicitMessageTarget":false}').

Regression test: extended the #99595 stable-facts table test in get-reply-run.media-only.test.ts with 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/111
  • node 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 — clean

Live 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 exec lines):
every chat↔heartbeat transition invalidated, 13/13; heartbeat resets got no history at all:

21:51:12 heartbeat resume=true  reusable
21:52:49 user      resume=false invalidated:message-policy
22:21:14 heartbeat resume=false invalidated:message-policy   historyPrompt=none
22:45:51 user      resume=false invalidated:message-policy
22:51:12 heartbeat resume=false invalidated:message-policy   historyPrompt=none
23:11:16 user      resume=false invalidated:message-policy

After (post-restart):

01:23:01 cli session reset: provider=claude-cli reason=message-policy
01:23:01 cli exec: trigger=user      useResume=false reuse=invalidated:message-policy
01:23:30 cli exec: trigger=user      useResume=true  resumeSession=11171aec0e40 reuse=reusable
01:26:41 cli exec: trigger=user      useResume=true  resumeSession=11171aec0e40 reuse=reusable
01:30:49 cli exec: trigger=user      useResume=true  resumeSession=11171aec0e40 reuse=reusable
01:33:13 cli exec: trigger=heartbeat useResume=true  resumeSession=11171aec0e40 reuse=reusable
01:34:12 cli exec: trigger=heartbeat useResume=true  resumeSession=11171aec0e40 reuse=reusable
  • The single 01:23:01 invalidation is the expected one-time upgrade step: the stored binding was persisted by a pre-fix heartbeat and lacks the hash, so the first policied turn invalidates once and re-persists a complete binding.
  • Everything after shares one native CLI session (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).
  • Operator-visible behavior confirmed: heartbeats now see the conversation that just happened on the session.

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.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Aug 10, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Aug 10, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 10, 2026
@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 12, 2026, 5:07 AM ET / 09:07 UTC.

ClawSweeper review

What this changes

This PR makes direct synthetic reply turns, including heartbeats, compute the same session-stable delivery policy and CLI binding facts as dispatched chat turns.

Regression provenance

Possible regression — probable (reproduction; failure trace; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep 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
Reviewed head: 966d9bcb620f615df0d30c264ba06a1c17ef795e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The root-cause repair and real behavior trace are strong; landing remains gated on clean mergeability and completed exact-head checks.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The PR body contains an after-fix reporting-deployment trace where user and heartbeat turns reuse one Claude CLI session after the expected one-time upgrade reset.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The PR body contains an after-fix reporting-deployment trace where user and heartbeat turns reuse one Claude CLI session after the expected one-time upgrade reset.
Evidence reviewed 7 items Current-main failure path: Dispatched turns inject a stable mode, whereas the pre-PR direct reply path defaults the binding mode from effective options and can omit it; the CLI preparer then has no message-policy hash to compare.
Shared policy owner on PR head: The new synthetic-turn resolver passes the persisted entry, session key/store, and heartbeat override into the same visible-replies policy used by dispatch.
Persisted-model contract: The runtime selects a session’s actual override through providerOverride/modelOverride, and the PR’s shared policy uses that same resolver instead of cached runtime metadata.
Findings None None.
Security None None.

How this fits together

Chat 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]
Loading

Before merge

  • Resolve merge risk (P1) - This bug fix adds production +307/-67 (net +240); the new direct-turn owner is justified by the missing producer boundary, but maintainers should keep the shared resolver as the sole policy path rather than retain a second synthetic-policy implementation.
  • Resolve merge risk (P1) - The supplied GitHub state is dirty and exact-head checks are incomplete, so the branch still needs merge-state resolution and completed validation before landing.
Agent review details

Security

None.

PR surface

Source +240, Tests +179, Generated 0. Total +419 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 7 307 67 +240
Tests 2 179 0 +179
Docs 0 0 0 0
Config 0 0 0 0
Generated 16 16 16 0
Other 0 0 0 0
Total 25 502 83 +419

Review metrics

Metric Value Why it matters
Production versus regression-test delta production +307/-67 (net +240); tests +179/-0 (net +179); generated baselines +16/-16 The net production growth creates a new canonical synthetic-turn policy owner; the added tests exercise the policy-equivalence boundary across turn kinds.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/auto-reply/reply/session-stable-reply-mode.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #121485
Summary: This PR is the active candidate fix for the linked Claude CLI heartbeat context-loss regression.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Require clean exact-head validation (recommended)
    Resolve the reported dirty merge state and wait for the exact-head checks to complete before deciding whether to land this session-reuse change.

Technical review

Best 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.

Labels

Label justifications:

  • P1: Alternating normal and heartbeat turns can silently remove conversation context from an active Claude CLI session.
  • merge-risk: 🚨 compatibility: The PR changes established session-reuse policy selection across stored model overrides, channel defaults, and heartbeat overrides.
  • merge-risk: 🚨 session-state: Incorrect binding equivalence resets the provider-side conversation and makes the next synthetic turn context-blind.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body contains an after-fix reporting-deployment trace where user and heartbeat turns reuse one Claude CLI session after the expected one-time upgrade reset.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body contains an after-fix reporting-deployment trace where user and heartbeat turns reuse one Claude CLI session after the expected one-time upgrade reset.

Evidence

What I checked:

Likely related people:

  • obviyus: Merged the earlier session-stable CLI binding repair that established the invariant this PR extends. (role: prior feature owner; confidence: high; commits: 48e8965b1060; files: src/auto-reply/reply/source-reply-delivery-mode.ts, src/auto-reply/reply/get-reply-run.media-only.test.ts, src/agents/cli-runner/prepare.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Resolve the reported dirty merge state and let the current-head checks complete.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (8 earlier review cycles)
  • reviewed 2026-08-10T09:48:54.080Z sha 77c9f2186557e194e588e54072b68a4782f3a83e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T16:55:23.710Z sha 75080a6191f0d180f0f280abfddb89b97496c9fc :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T18:53:24.460Z sha 75080a6191f0d180f0f280abfddb89b97496c9fc :: needs changes before merge. :: [P1] Keep heartbeat response-tool mode out of binding facts | [P1] Reuse the full dispatch policy for synthetic binding facts
  • reviewed 2026-08-10T19:52:48.785Z sha 3986378506e8a47d4ff2bb5826cd332284beee75 :: needs changes before merge. :: [P1] Unify sender-independent stable policy calculation
  • reviewed 2026-08-10T21:08:18.768Z sha 2354c95e912a8fbfdcc9383d5f1fec97f41cc535 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-11T00:53:22.542Z sha 2354c95e912a8fbfdcc9383d5f1fec97f41cc535 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-12T08:06:19.622Z sha 2b9a8d4 :: needs changes before merge. :: [P1] Use the persisted session model for stable reply defaults
  • reviewed 2026-08-12T08:57:56.384Z sha 966d9bc :: needs changes before merge. :: [P1] Use the persisted session model for stable reply defaults

@marey-tatum
marey-tatum force-pushed the fix/heartbeat-cli-session-pingpong branch from 77c9f21 to 75080a6 Compare August 10, 2026 16:25
@jtatum

jtatum commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

@jtatum

jtatum commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

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

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 10, 2026
@marey-tatum
marey-tatum force-pushed the fix/heartbeat-cli-session-pingpong branch from 75080a6 to 6916d35 Compare August 10, 2026 19:18
@marey-tatum
marey-tatum force-pushed the fix/heartbeat-cli-session-pingpong branch from 6916d35 to 6794ecd Compare August 10, 2026 19:28
@jtatum

jtatum commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Does the larger scope change the priority? Context loss is a really unfortunate outcome for users.

@marey-tatum
marey-tatum force-pushed the fix/heartbeat-cli-session-pingpong branch from 6794ecd to 3986378 Compare August 10, 2026 19:46
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L and removed size: M labels Aug 10, 2026
jtatum and others added 5 commits August 12, 2026 01:14
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]>
@marey-tatum
marey-tatum force-pushed the fix/heartbeat-cli-session-pingpong branch 2 times, most recently from 6a65141 to 966d9bc Compare August 12, 2026 08:52
@jtatum

jtatum commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

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.

@jtatum

jtatum commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

See comment above re: P1

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 12, 2026
@obviyus obviyus self-assigned this Aug 12, 2026
# 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
@obviyus
obviyus merged commit 5235269 into openclaw:main Aug 12, 2026
119 checks passed
@obviyus

obviyus commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Merged via squash.

@jtatum
jtatum deleted the fix/heartbeat-cli-session-pingpong branch August 12, 2026 16:03
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: claude-cli does not get session context during heartbeats

2 participants