Skip to content

fix: keep optional heartbeat finalization silent - #145343

Merged
obviyus merged 1 commit into
openclaw:mainfrom
PollyBot13:fix/heartbeat-finalizer-context
Sep 13, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
PollyBot13:fix/heartbeat-finalizer-context

Conversation

@PollyBot13

@PollyBot13 PollyBot13 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Related: #143580

What Problem This Solves

Fixes an issue where users receive an unnecessary missing-summary warning after a heartbeat's tool-free finalizer explicitly chooses NO_REPLY, even though the run permits silence.

Why This Change Was Made

The host retains the authored silent token through finalizer projection and accepts it under the existing optional/allowed-silence contract. Required replies, genuinely blank output, original tool failures, original timeouts, and cancellation cannot use this exception. No new API or policy flag is introduced.

This is a narrow unwanted-chatter repair, not a claim to fix the reported transcript loss, prolonged wedge, or duplicate delivery. The separate timeout-retention change in #141072 is complementary; combined execution has not been tested.

User Impact

Quiet heartbeat results stay quiet without a second finalizer request or a synthetic fallback warning. Legitimate alerts and HEARTBEAT_OK behavior remain unchanged.

Evidence

  • Real loopback HTTP proof traverses the built-in restricted finalizer and actual persisted history assembly. Before the fix, authored NO_REPLY makes two requests and emits a missing-summary warning; after the fix, it makes one request, offers no tools, and produces no payload. HEARTBEAT_OK and alert controls pass.
  • Rebased targeted verification: 53 tests across five files passed. Independent review reran 31 tests and found no blocking defect. The requested original-timeout + optional-NO_REPLY regression was added afterward; the focused suite passes 32/32.
  • Focused core lint, formatting, and diff checks pass. Tests use artifact-only aliases to existing dependency bytes; full build/typecheck is not claimed because the local dependency graph has pre-existing missing links/types.
  • Proof is synthetic HTTP transport and local terminal assembly, not production provider/channel delivery or browser rendering.

AI-assisted

Inspectable loopback execution output

Head: 953c3fbf55f099944acd41e5dc2fd2b9304280f2. The excerpts below are copied from the existing exact-head run (September 12, 00:13 CEST), not a new run or inferred source behavior. The task-only test uses real SQLite transcript persistence, built-in restricted finalization, history assembly and HTTP/SSE transport to a local synthetic responder. Auth availability is supplied by a synthetic registry; the responder emits a fixed assistant text and finish_reason=stop. No real credentials, external provider or live channel is involved.

Invocation: node node_modules/vitest/vitest.mjs run --config <artifact-dir>/fix.config.mts. The artifact config extends the repository Vitest config and aliases missing workspace links to existing installed package bytes; it is not a standard clean-install run.

Captured NO_REPLY request and resulting terminal payloads

The responder's assistant text is NO_REPLY. This is the complete saved request/outcome JSON: one HTTP request, no offered tools, retained synthetic completed-tool history and no emitted payload. answered is the internal finalization classification that ends retries, not a visible answer.

{
  "finalizationOutcome": "answered",
  "payloads": [],
  "requests": [
    {
      "model": "synthetic",
      "messages": [
        {
          "role": "user",
          "content": "Heartbeat monitor: check the synthetic inbox. If nothing needs attention reply HEARTBEAT_OK."
        },
        {
          "role": "assistant",
          "content": null,
          "tool_calls": [
            {
              "id": "inbox",
              "type": "function",
              "function": {
                "name": "exec",
                "arguments": "{\"command\":\"synthetic-inbox\"}"
              }
            }
          ]
        },
        {
          "role": "tool",
          "content": "[] (synthetic inbox empty)",
          "tool_call_id": "inbox"
        },
        {
          "role": "user",
          "content": "The previous assistant turn completed its tool calls but did not produce a user-visible answer. Continue from the current transcript and produce the final user-visible answer now. Do not repeat completed tool calls or restart from scratch. Tools are unavailable in this step: it is a text-only pass, so reply with plain text and do not attempt any tool call."
        }
      ],
      "stream": true,
      "stream_options": {
        "include_usage": true
      },
      "max_completion_tokens": 2048
    }
  ]
}
Acknowledgment/alert controls and exact-head terminal output

Projected from the saved control request/outcome JSON (only request count, payloads and outcome shown):

{
  "ok": {
    "requestCount": 1,
    "payloads": [
      {
        "text": "HEARTBEAT_OK",
        "replyToTag": false
      }
    ],
    "finalizationOutcome": "answered"
  },
  "alert": {
    "requestCount": 1,
    "payloads": [
      {
        "text": "Synthetic alert: inbox needs attention",
        "replyToTag": false
      }
    ],
    "finalizationOutcome": "answered"
  }
}

Copied terminal output; local checkout prefix removed:

 ✓ |agents-embedded-agent-run| src/agents/embedded-agent-runner/run/heartbeat-finalization.proof.test.ts > captures heartbeat finalization for HEARTBEAT_OK 547ms
 ✓ |agents-embedded-agent-run| src/agents/embedded-agent-runner/run/heartbeat-finalization.proof.test.ts > captures heartbeat finalization for Synthetic alert: inbox needs attention 257ms
 ✓ |agents-embedded-agent-run| src/agents/embedded-agent-runner/run/heartbeat-finalization.proof.test.ts > captures heartbeat finalization for NO_REPLY 242ms
 Test Files  5 passed (5)
      Tests  53 passed (53)
   Start at  00:13:32
   Duration  20.03s (transform 48%, tests 35%, import 14%, worker 2%, setup 1%)

Earlier red run against the unfixed implementation (before rebase; not exact-head):

FAIL captures heartbeat finalization for NO_REPLY
AssertionError: expected 'completed-empty' to be 'answered'
Expected: "answered"
Received: "completed-empty"
Test Files  1 failed (1)
Tests  1 failed | 2 passed (3)

The earlier pre-fix raw request snapshot was overwritten by successful captures; the retained red assertion above is the directly inspectable pre-fix evidence. The exact-head capture and passing assertions establish one request and zero payloads after the fix. This does not establish the reporter's transcript-loss, wedge or duplicate-delivery scenario.

Hosted verification at this checkpoint: CI run, including openclaw/ci-gate, production/test typechecks and lint, passed. Local full build/typecheck limitations above remain disclosed.


What Problem This Solves

A quiet heartbeat can send “The tool run finished, but no final summary was produced” after its finalizer deliberately returns NO_REPLY.

Why This Change Was Made

The built-in runtime now retains that authored token and accepts it through the existing optional-reply policy. The host finalization owner makes this decision; no new setting or state store is added.

User Impact

Quiet heartbeats stay quiet with one finalizer request. Alerts still arrive. Required replies, blank output, tool failures, original timeouts, and cancellation retain their existing checks.

Evidence

Independently executed head 953c3fbf55f099944acd41e5dc2fd2b9304280f2 through a real Gateway heartbeat and leased Discord bots:

Synthetic capture Finalizer requests Heartbeat message
Main, NO_REPLY 2 Missing-summary warning
Candidate, NO_REPLY 1 None
Candidate, alert 1 “Synthetic alert: inbox needs attention.”
Candidate, HEARTBEAT_OK 1 None, as configured

The quiet run completed successfully and retained one NO_REPLY in history. Each recording lasted three minutes. Ordinary retries before finalization are separate and unchanged.

Candidate owner checks: 69 passed. Fresh-merge checks: 401 passed; one fallback-notice assertion failed identically on plain main and the relevant prior-merge parent. Test routing, changed-file lint, and formatting passed. Hosted CI gate passed.

Consumers

Optional finalizers, reply shaping, heartbeat delivery, background completion, and terminal snapshots retain the same silence contract. Writer authority and failure handling remain intact; derived output is rebuilt per attempt.

This proof covers the built-in runtime. A separate plugin still erases silent tokens before host finalization; that pre-existing limit remains. This does not fix lost history, long stalls, or duplicate delivery in the linked report.

AI-assisted.

Latest exact-head hosted verification: CI run 34786156188, successful at 953c3fbf55f099944acd41e5dc2fd2b9304280f2.

@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 6:39 PM ET / 22:39 UTC (Revision 4).

ClawSweeper review

What this changes

Preserves an explicit NO_REPLY from optional heartbeat finalization so the run finishes silently without another finalizer request or a missing-summary warning.

Merge readiness

✅ Ready for maintainer review

Keep open: this is a useful, bounded repair that current main and the latest release still lack. The supplied runtime evidence supports the fix, and no blocking introduced defect was found.

Priority: P2
Reviewed head: 953c3fbf55f099944acd41e5dc2fd2b9304280f2

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful boundary coverage and sufficient runtime evidence; no blocking defect was found.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The captured head-specific HTTP/SSE trace exercises the built-in finalizer and persisted history assembly, showing one request and zero payloads for NO_REPLY with successful alert controls; the later Gateway/Discord observations corroborate the result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured head-specific HTTP/SSE trace exercises the built-in finalizer and persisted history assembly, showing one request and zero payloads for NO_REPLY with successful alert controls; the later Gateway/Discord observations corroborate the result.
Evidence reviewed 9 items Pinned change and clean checkout: Host introduction evidence identifies only the finalization owner and its tests as introduced changes. The local checkout matches the pinned head; git status remained clean and the introduced diff passed the whitespace check.
Current main still needs the repair: The current-main finalization owner still replaces every empty result's projected text with an empty string and lacks the optional explicit-silence acceptance branch. The inspected shared classifier and result validator have no changes between the PR merge base and fetched main.
Latest release lacks this behavior: The v2026.9.4 source contains the same unconditional empty-result projection and retry path, so this repair is not already present in the supplied latest release.
Findings None None.
Security None None.

How this fits together

After tools finish without a final answer, OpenClaw can request a tool-free summary. The finalization owner converts that result into terminal state and reply payloads for heartbeat delivery.

flowchart TD
  A[Completed tool work] --> B[Tool-free finalizer]
  B --> C[Validate assistant result]
  C --> D{Explicit silence allowed?}
  D -->|Yes| E[Finish without a payload]
  D -->|No| F[Existing answer or recovery handling]
  F --> G[Heartbeat delivery]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +30, Tests +101. Total +131 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 32 2 +30
Tests 1 101 0 +101
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 133 2 +131

Review metrics

Metric Value Why it matters
Finalizer requests 2 → 1 for permitted NO_REPLY The supplied before/after evidence shows the quiet outcome avoids an unnecessary model request as well as the warning.

Technical review

Best possible solution:

Keep deliberate silence within the existing finalization owner while preserving normal alerts, required replies, and failure handling.

Do we have a high-confidence way to reproduce the issue?

Yes: an optional, silence-enabled run whose isolated finalizer returns NO_REPLY reaches the retry/fallback path on current main. Source inspection and the supplied pre-fix failure support this mechanism; this read-only review did not execute tests.

Is this the best way to solve the issue?

Yes: preserving the authored token and applying the existing silence classifier at finalization is a narrow repair that avoids another policy or delivery path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c92ce0278f4a.

Labels

Label justifications:

  • P2: This fixes unwanted heartbeat warnings and an unnecessary finalizer request without changing broader delivery policy.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The captured head-specific HTTP/SSE trace exercises the built-in finalizer and persisted history assembly, showing one request and zero payloads for NO_REPLY with successful alert controls; the later Gateway/Discord observations corroborate the result.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured head-specific HTTP/SSE trace exercises the built-in finalizer and persisted history assembly, showing one request and zero payloads for NO_REPLY with successful alert controls; the later Gateway/Discord observations corroborate the result.

Evidence

What I checked:

  • Pinned change and clean checkout: Host introduction evidence identifies only the finalization owner and its tests as introduced changes. The local checkout matches the pinned head; git status remained clean and the introduced diff passed the whitespace check. (src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:185, 953c3fbf55f0)
  • Current main still needs the repair: The current-main finalization owner still replaces every empty result's projected text with an empty string and lacks the optional explicit-silence acceptance branch. The inspected shared classifier and result validator have no changes between the PR merge base and fetched main. (src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:432, c92ce0278f4a)
  • Latest release lacks this behavior: The v2026.9.4 source contains the same unconditional empty-result projection and retry path, so this repair is not already present in the supplied latest release. (src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:432, 3a9d69db306c)
  • Existing silence policy and safety guards: The patch reuses shouldTreatEmptyAssistantReplyAsSilent, requires an optional reply and explicit silent text, rejects an original tool error or timeout, and retains the active-run assertion after finalization. Added cases cover optional silence, required replies, disabled silence, blank output, tool failure, and original timeout. (src/agents/embedded-agent-runner/run/settled-turn-finalization.test.ts:509, 953c3fbf55f0)
  • Built-in runtime boundary: The built-in harness runs a restricted OpenClaw embedded attempt and projects it through the existing finalization validator. That validator rejects unsuccessful stops and capability activity before classifying NO_REPLY as empty. The changed behavior and supplied proof depend on this OpenClaw implementation, not on the separate Codex runtime. (src/agents/harness/builtin-openclaw.ts:92, 953c3fbf55f0)
  • Inspectable after-fix transport proof: The supplied PR-body snapshot records head 953c3fb using real SQLite history assembly, the built-in restricted finalizer, and HTTP/SSE to a synthetic responder. Its request includes completed-tool history and no offered tools; NO_REPLY produces one request, finalizationOutcome answered, and zero payloads. Alert and HEARTBEAT_OK controls produce their expected terminal payloads. A retained pre-fix assertion reports completed-empty instead of answered. The later Gateway/Discord result table corroborates this scope; no recording files were available in the supplied scratch directory for independent media inspection. (953c3fbf55f0)

Likely related people:

  • altaywtf: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Razvan Girgiz: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (3 earlier review cycles)
  • reviewed 2026-09-11T22:19:58.456Z sha 953c3fb :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-11T23:08:16.367Z sha 953c3fb :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T22:28:59.806Z sha 953c3fb :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@obviyus obviyus closed this Sep 13, 2026
@obviyus obviyus reopened this Sep 13, 2026
@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

landpr-approve-admin-merge
pr: 145343
head: 953c3fb
scope: owner-review

@obviyus
obviyus merged commit a668ab9 into openclaw:main Sep 13, 2026
451 checks passed
@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

Thanks @PollyBot13!

Proof: A real Gateway heartbeat completed silently in the Discord QA channel. Alert and acknowledgment controls retained their expected behavior.

  • Bug: A quiet heartbeat sent a missing-summary warning after an explicit NO_REPLY.
  • Fix: The built-in finalization owner retains authored silence and applies the existing optional-reply policy before retrying.
Before After
Two finalizer requests and an unwanted warning One finalizer request and no heartbeat message

obviyus added a commit that referenced this pull request Sep 13, 2026
Related: #146331. Supersedes #146595 by @MasterSwords1. Thanks @fray-ai for reporting it.

## What Problem This Solves

After replay cleanup removes old messages, an assistant can lose the current task and successful tool results from later requests, even though chat history still shows them.

## Why This Change Was Made

Normalize replay before prompt preparation records the history boundary. Session setup seeds the count; prompt preparation replaces it after history assembly and cleanup. Submission consumes that prepared history; it no longer shortens history after the boundary is set. The contributor's production fix is preserved. Tests now use complete fixtures and real prompt preparation/submission, with a clean-history control.

## User Impact

Current instructions and tool results remain available across multiple tool calls. No setting or migration is needed.

## Evidence

Authenticated Gateway `chat.send`, an isolated history-only context engine, and two actual file reads:

| Captured request | Main, six silent history messages | Candidate |
| --- | --- | --- |
| First | Current task present | Current task present |
| Second | Task and first result absent | Task and first result present |
| Third | Task and both results absent | Task and both results present |

Both runs completed the reads and retained the entire turn in chat history. The no-silent-history control passes on both. Responses were deterministic; this proves request contents, not model answer quality.

The corrected regression fails on main because the active prompt is missing, and passes with the fix. Five selected test files pass on fresh merge `3e4442b9890b85e579eb36f657e88261ca0ef825` (parents `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc` and `fa5b2d16805c7c81e2c395fbbc0ff27312b16da1`): 160 distinct tests, 250 successful executions across the two test configurations.

<details>
<summary>Commands and captured result</summary>

Gateway driver commands, using the retained proof directory:

```sh
node "$PROOF/reproduce.mjs" candidate-six 6
node "$PROOF/assert-tail.mjs" candidate-six
node "$PROOF/reproduce.mjs" candidate-clean 0
node "$PROOF/assert-tail.mjs" candidate-clean
```

Both candidate assertions exit 0. The same assertion exits 1 on the recorded main reproduction. Captured candidate checks: three requests; two completed reads; current task retained in every request; first result retained in request two; both results retained in request three; chat history retains all markers.

Selected tests:

```sh
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-context-advancement.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts \
  src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
```

The fresh merge used `node --import tsx scripts/ci-run-node-test-shard.mts`, with these five include paths and the embedded-agent and embedded-agent-run configurations. Exit 0. Six additional direct-caller files also passed on that merge (165 tests), covering replay recovery, projections, settlement, media hints, and tool-result budgets. Typechecks remain for CI.

</details>

## Compatibility

No schema, protocol, dependency, configuration, or durable transcript change. Existing context-engine commit semantics remain intact.

## Consumers

The shared boundary also serves turn completion, usage fallback, and legacy context finalization. They consume the normalized count. The independent CLI history boundary is unchanged.

## Invalidation

Each attempt computes the boundary after replay cleanup. No persistent cache or new state owner is added.

### Ordering and consumers

Session setup seeds the history count. Prompt preparation replaces it after history assembly and replay cleanup, then submission consumes the prepared history. The same count serves tool-loop advancement, reply flushing, usage fallback, and legacy turn completion. Hook and budget projections and the active-run snapshot use that prepared history. Optional settled-turn finalization still reads the newly completed assistant from the stream subscription, preserving the authored `NO_REPLY` behavior from #145343.

### Validation scope

The retained Gateway proof checks actual request contents and completed file reads with deterministic responses. Main loses the active task and results after replay cleanup; the candidate retains them. Both clean-history controls pass. Runtime proof was captured at `9dc8e3a19ad7ea694bc40ca520f1e2597e7fdc22`; the final commit changes only tests. The fresh merge includes #145343, #147139, and #147394. Its selected suites pass 160 distinct tests, with 250 executions due to configuration overlap, plus 165 tests in six additional consumer files. This does not claim a separate fresh execution of the finalizer-silence scenario, browser rendering, or answer quality. Typechecks remain for CI.

CI run [34789473564](https://github.com/openclaw/openclaw/actions/runs/34789473564) completed successfully at `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc`, including the hosted type checks.

Co-authored-by: MasterSwords1 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
Keep authored NO_REPLY during built-in optional finalization and apply the existing silence policy before retry or fallback. Preserve required replies, tool failures, timeouts, and cancellation.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…47531)

Related: openclaw#146331. Supersedes openclaw#146595 by @MasterSwords1. Thanks @fray-ai for reporting it.

## What Problem This Solves

After replay cleanup removes old messages, an assistant can lose the current task and successful tool results from later requests, even though chat history still shows them.

## Why This Change Was Made

Normalize replay before prompt preparation records the history boundary. Session setup seeds the count; prompt preparation replaces it after history assembly and cleanup. Submission consumes that prepared history; it no longer shortens history after the boundary is set. The contributor's production fix is preserved. Tests now use complete fixtures and real prompt preparation/submission, with a clean-history control.

## User Impact

Current instructions and tool results remain available across multiple tool calls. No setting or migration is needed.

## Evidence

Authenticated Gateway `chat.send`, an isolated history-only context engine, and two actual file reads:

| Captured request | Main, six silent history messages | Candidate |
| --- | --- | --- |
| First | Current task present | Current task present |
| Second | Task and first result absent | Task and first result present |
| Third | Task and both results absent | Task and both results present |

Both runs completed the reads and retained the entire turn in chat history. The no-silent-history control passes on both. Responses were deterministic; this proves request contents, not model answer quality.

The corrected regression fails on main because the active prompt is missing, and passes with the fix. Five selected test files pass on fresh merge `3e4442b9890b85e579eb36f657e88261ca0ef825` (parents `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc` and `4492504cc1f3704f8b3a5459f75a9c57e1f96edd`): 160 distinct tests, 250 successful executions across the two test configurations.

<details>
<summary>Commands and captured result</summary>

Gateway driver commands, using the retained proof directory:

```sh
node "$PROOF/reproduce.mjs" candidate-six 6
node "$PROOF/assert-tail.mjs" candidate-six
node "$PROOF/reproduce.mjs" candidate-clean 0
node "$PROOF/assert-tail.mjs" candidate-clean
```

Both candidate assertions exit 0. The same assertion exits 1 on the recorded main reproduction. Captured candidate checks: three requests; two completed reads; current task retained in every request; first result retained in request two; both results retained in request three; chat history retains all markers.

Selected tests:

```sh
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-context-advancement.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts \
  src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
```

The fresh merge used `node --import tsx scripts/ci-run-node-test-shard.mts`, with these five include paths and the embedded-agent and embedded-agent-run configurations. Exit 0. Six additional direct-caller files also passed on that merge (165 tests), covering replay recovery, projections, settlement, media hints, and tool-result budgets. Typechecks remain for CI.

</details>

## Compatibility

No schema, protocol, dependency, configuration, or durable transcript change. Existing context-engine commit semantics remain intact.

## Consumers

The shared boundary also serves turn completion, usage fallback, and legacy context finalization. They consume the normalized count. The independent CLI history boundary is unchanged.

## Invalidation

Each attempt computes the boundary after replay cleanup. No persistent cache or new state owner is added.

### Ordering and consumers

Session setup seeds the history count. Prompt preparation replaces it after history assembly and replay cleanup, then submission consumes the prepared history. The same count serves tool-loop advancement, reply flushing, usage fallback, and legacy turn completion. Hook and budget projections and the active-run snapshot use that prepared history. Optional settled-turn finalization still reads the newly completed assistant from the stream subscription, preserving the authored `NO_REPLY` behavior from openclaw#145343.

### Validation scope

The retained Gateway proof checks actual request contents and completed file reads with deterministic responses. Main loses the active task and results after replay cleanup; the candidate retains them. Both clean-history controls pass. Runtime proof was captured at `9dc8e3a19ad7ea694bc40ca520f1e2597e7fdc22`; the final commit changes only tests. The fresh merge includes openclaw#145343, openclaw#147139, and openclaw#147394. Its selected suites pass 160 distinct tests, with 250 executions due to configuration overlap, plus 165 tests in six additional consumer files. This does not claim a separate fresh execution of the finalizer-silence scenario, browser rendering, or answer quality. Typechecks remain for CI.

CI run [34789473564](https://github.com/openclaw/openclaw/actions/runs/34789473564) completed successfully at `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc`, including the hosted type checks.

Co-authored-by: MasterSwords1 <[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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

2 participants