Skip to content

fix: recover final replies after settled tool-only turns - #110565

Merged
joshavant merged 7 commits into
mainfrom
fix/108738-settled-tool-continuation
Jul 22, 2026
Merged

joshavant merged 7 commits into
mainfrom
fix/108738-settled-tool-continuation

Conversation

@joshavant

@joshavant joshavant commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #108738

AI-assisted: implemented and reviewed with Codex; I understand and verified the resulting runtime behavior.

Additional instructions

Allow edits from maintainers is enabled for this repository-owned branch.

What Problem This Solves

Users could see completed tool activity but receive no final channel reply when a provider ended the post-tool assistant turn without visible text. Side-effecting turns were especially problematic: replaying the original request could repeat a write, while refusing every continuation left the user with a silent or failed turn.

Why This Change Was Made

The shared runner now recognizes a structurally settled post-tool turn that still requires a visible terminal reply and asks the selected harness to perform one isolated finalization turn over frozen settled context.

The contract is fail-closed:

  • finalization is available only when the harness explicitly implements it;
  • the finalizer receives no application tool surface and cannot repeat completed work;
  • active, errored, asynchronous, already-delivered, spawned-session, background, intentionally silent, or compacted finalization states remain excluded;
  • full-attempt harnesses are projected through a narrow result validator that rejects capability evidence, unsuccessful terminal state, tool calls, or empty/silent answers;
  • Codex uses a private app-server turn with transcript projection and mirror attestation;
  • Copilot resumes the exact compatible native session with tools, agents, skills, memory, schedules, extensions, hooks, and user-input surfaces disabled, while retaining the SDK-managed safety foundation;
  • the built-in OpenClaw harness uses the same narrow finalization boundary.

Required cron announcements opt into the same terminal-reply expectation; optional/no-delivery scheduled work remains unchanged. Ordinary onboarding, provider selection, and non-finalization Codex/Copilot runs keep their existing paths.

User Impact

Users receive the missing final explanation or acknowledgment after completed tool work. Completed side effects are not replayed, and a harness that cannot prove an isolated capability-free finalization fails closed instead of silently weakening the boundary.

Evidence

Live fix proof — implementation head

A real Telegram adapter with a Convex-leased ordinary telegram credential and deterministic mock provider exercised a side-effecting write followed by an empty terminal assistant turn on 80eba5b1bc9. Current head cc5b8c0e926 adds only the fail-closed interrupted-turn guard and its focused tests:

Pre-fix regression reproduction

The same live Telegram scenario and credential against pinned pre-fix SHA d5a8233e76ff7aeeafbff493db1dda5ba7e77dcc failed both attempts without the final marker:

No telegram-user credential was leased or used.

Static and focused verification

  • node scripts/check-changed.mjs on Blacksmith Testbox tbx_01ky4k1gyc4yznx3wxm5vkqtsg: passed all-project TSGo, formatting, SDK contracts/budgets, plugin boundaries, core/extensions/scripts lint with 0 warnings/errors, and runtime import-cycle checks.
  • CI follow-up gates: production/full-tree/script unused-export scans passed with 0 entries; the complete docs gate passed formatting, Markdown lint, MDX, glossary, links, and generated-map freshness.
  • Interrupted Codex finalization: 16 focused tests passed, including partial assistant text followed by status: interrupted rejection and proof that no transcript mirror occurs; scoped extension prod/test types, lint, guards, and cycle checks passed on Testbox tbx_01ky4paw8wj4v3jqrr59c8jhf9.
  • Post-fix local ClawSweeper review at cc5b8c0e926: patch correct, confidence 0.91, no review findings, security cleared.
  • Focused final hardening matrix: 147 tests passed across the core result contract, Codex attestation/finalizer, and Copilot resume isolation.
  • $autoreview --mode branch --base origin/main: clean; no accepted/actionable findings.
  • git diff --check: clean.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling extensions: qa-lab size: L maintainer Maintainer-authored PR labels Jul 18, 2026
@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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 12:05 PM ET / 16:05 UTC.

Summary
The branch adds one bounded, tool-disabled continuation after a settled tool turn ends without visible assistant text, with embedded-runner tests and a real Telegram QA scenario.

PR surface: Source +59, Tests +228, Other +80. Total +367 across 10 files.

Reproducibility: yes. at source/evidence level: the supplied PR includes a deterministic mock-provider scenario run through a real Telegram adapter, plus a pre-fix baseline and a post-fix marker. I could not independently execute or inspect the current checkout because the read-only sandbox command failed before inspection.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #108738
Summary: This PR is a candidate fix for the open tool-only final-reply regression; the earlier closed proposal is related but did not merge.

Members:

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

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster ✨ media proof bonus
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Rebase onto current main and refresh the focused runner and Telegram proof against the resulting head.
  • Have a maintainer decide whether settled side-effecting tool turns belong in the shared continuation policy.

Mantis proof suggestion
A redacted Telegram transcript can independently verify the intended user-visible reply and the absence of a repeated side effect. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram live proof: verify a settled write followed by an empty terminal turn sends exactly one final reply without repeating the write, and return redacted evidence.

Risk before merge

  • [P1] The retry changes a shared terminal decision surface: an incorrect predicate could turn intentionally silent, delivered, errored, asynchronous, or background runs into an extra model request.
  • [P1] Although the continuation disables tools, the branch must be rebased and its focused runner plus Telegram proof refreshed against current main before merge because the GitHub context reports it behind its base and currently draft.

Maintainer options:

  1. Rebase and refresh the behavioral proof (recommended)
    Rebase onto current main, rerun the focused terminal tests and Telegram regression, and show that recovery still emits one reply while exposing no tools.
  2. Accept the terminal-policy tradeoff
    A maintainer may intentionally accept the shared continuation semantics if the broader final-reply recovery is preferred over the stricter historical replay-safe boundary.
  3. Pause for a terminal-contract decision
    Do not merge while draft if maintainers want a canonical policy for tool-only terminal turns before selecting the recovery boundary.

Next step before merge

  • [P2] The remaining blocker is a protected shared agent-runtime policy choice plus rebase/refresh validation, not a narrow mechanical repair for ClawSweeper to make automatically.

Maintainer decision needed

  • Question: Should OpenClaw adopt a shared, tool-disabled continuation after an otherwise settled tool-only terminal turn has no visible final reply?
  • Rationale: This is an intentional change to the agent-runtime terminal contract and is protected for maintainer judgment; the earlier related proposal used a more restrictive replay-safe boundary.
  • Likely owner: hannesrudolph — The closest available history signal is the author of the previous alternative implementation that framed the competing safety boundary.
  • Options:
    • Approve the bounded recovery (recommended): Accept the shared recovery after the branch is rebased and the current-head runner and Telegram proof confirm no extra tool execution or terminal-state regression.
    • Retain the stricter boundary: Limit continuation to a narrower replay-safe or read-only subset if maintainers do not want settled side-effecting calls to receive an additional model turn.
    • Pause the policy change: Keep the regression issue open while defining the canonical terminal fallback contract before merging this behavior change.

Security
Cleared: The supplied diff adds no dependency, workflow, secret, permission, package-resolution, or artifact-execution change; its main safety mechanism removes tools from the recovery attempt.

Review details

Best possible solution:

Keep the recovery bounded in the shared terminal-resolution path, preserve all explicit silent and terminal exclusions, then rebase and re-prove one final reply with zero tool definitions and no repeated side effect before a maintainer accepts the policy change.

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

Yes, at source/evidence level: the supplied PR includes a deterministic mock-provider scenario run through a real Telegram adapter, plus a pre-fix baseline and a post-fix marker. I could not independently execute or inspect the current checkout because the read-only sandbox command failed before inspection.

Is this the best way to solve the issue?

Unclear: continuing from settled transcript state with tools disabled directly addresses the missing reply and avoids repeating writes, but choosing this broader shared terminal behavior over the prior replay-safe boundary requires maintainer policy approval.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 3fd3ad830148.

Label changes

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P1: The reported behavior can leave channel users without a final acknowledgment after completed tool work.
  • merge-risk: 🚨 compatibility: The patch changes shared embedded-agent terminal retry semantics for existing sessions and intentionally silent states.
  • merge-risk: 🚨 message-delivery: The patch changes whether a tool-only terminal outcome results in a fresh outbound final reply.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR provides an after-fix real Telegram adapter run with a side-effecting write, one recovery continuation, zero continuation tools, and a visible success marker, alongside an exact pre-fix baseline; redact private data in any refreshed proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR provides an after-fix real Telegram adapter run with a side-effecting write, one recovery continuation, zero continuation tools, and a visible success marker, alongside an exact pre-fix baseline; redact private data in any refreshed proof.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The fix changes an observable Telegram final reply after a tool-only turn, and the supplied scenario is directly demonstrable in Telegram.
Evidence reviewed

PR surface:

Source +59, Tests +228, Other +80. Total +367 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 118 59 +59
Tests 2 244 16 +228
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 81 1 +80
Total 10 443 76 +367

What I checked:

  • Reported live behavior proof: The PR body provides a candidate Telegram run, a pre-fix baseline run, a one-write/one-continuation counter, and a zero-tool continuation assertion; the GitHub context also records a successful Real behavior proof check. (qa/scenarios/channels/telegram-empty-response-after-write-recovery.yaml:1, 500d4191bf71)
  • Shared runtime surface: The supplied diff places the continuation decision in embedded terminal resolution and disables tools before dispatching the recovery attempt, rather than adding channel-specific retry behavior. (src/agents/embedded-agent-runner/run/terminal-resolution.ts:125, 500d4191bf71)
  • Prior alternative: The related earlier PR used a narrower read-only/replay-safe continuation strategy but was closed unmerged; this PR deliberately changes the boundary to recover after settled side-effecting calls with tools disabled. (src/agents/embedded-agent-runner/run/incomplete-turn.ts:137, 54b9e92f7592)
  • Review limitation: A read-only command intended to inspect the repository policy, scoped instructions, source, notes, and history failed immediately with the sandbox error bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted; no local files were read or changed.

Likely related people:

  • hannesrudolph: Authored the earlier, closely related post-tool empty-reply continuation proposal, which documents the same terminal-shape problem and contrasting safety boundary. (role: prior alternative implementation author; confidence: medium; commits: 54b9e92f7592; files: src/agents/embedded-agent-runner/run/incomplete-turn.ts, src/agents/embedded-agent-runner/run/terminal-resolution.ts)
  • joshavant: Authored the current candidate and supplied the live Telegram regression proof; included for follow-up on this branch, not as a claim of current-main ownership. (role: current proposed implementation author; confidence: high; commits: 500d4191bf71; files: src/agents/embedded-agent-runner/run/attempt-dispatch-preparation.ts, qa/scenarios/channels/telegram-empty-response-after-write-recovery.yaml)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-18T08:27:03.643Z sha 500d419 :: needs maintainer review before merge. :: none

@joshavant
joshavant marked this pull request as draft July 18, 2026 16:02
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 18, 2026
@Johannes-Berggren

Copy link
Copy Markdown

Validated this draft against the live 7.1 failure signatures from my repro on #108738 (Slack socket mode + @openclaw/codex app-server, gpt-5.6): the new emptyStopAfterSettledTools gate matches them exactly.

Both of our hard failures logged:

incomplete turn detected: … stopReason=stop hasLastAssistant=no hasCurrentAttemptAssistant=yes
payloads=0 tools=1 replaySafe=no … emptyRetries=0/1 missingAssistantRetries=0/1 — surfacing error to user

i.e. every retry family was skipped (0/N), not exhausted — the empty-response retry requires replay safety, which a turn with an executed tool can never have. Continuing from settled results with the tool surface removed sidesteps exactly that bind, and the conditions in resolveSettledToolTerminalContinuationInstruction (stop-reason stop, ≥1 settled non-error tool, lifecycle fully completed, empty visible response) match both of our logged runs. Right shape for the fix.

One gap worth a look before this leaves draft: both of our hard-error repros were cron-triggered runs (the terminal error additionally put each job into cron error backoff). As written,

allowEmptyStopContinuation:
  runParams.trigger == null ||
  runParams.trigger === "user" ||
  runParams.trigger === "manual",

excludes "cron" and "heartbeat", so scheduled runs keep dead-ending into surfacing error to user + backoff. If the exclusion is about not spending an extra model call when nobody is waiting: scheduled runs that announce into channels hit the same user-visible message loss, and the errored cron takes the failure backoff on top. Including "cron" — or gating on whether the run has a delivery target rather than on trigger — would cover the remaining half of our production incidents.

Happy to live-test against our Slack/codex workload once this lands in a beta.

@joshavant

Copy link
Copy Markdown
Collaborator Author

Live E2E proof completed against exact head a2ab1d2759b05f4bbfbe0d3cc4d036996fb30dda.

  • Regression reproduction: base d5a8233e76f plus only the deterministic QA fixture, through a real Telegram group and an ordinary Convex telegram bot-pair lease. Result: 0 passed / 1 failed; no visible reply, timed out after 60s. Crabbox run
  • Candidate fix proof: identical real Telegram scenario on the PR head. Result: 1 passed / 0 failed, exact visible reply TELEGRAM-EMPTY-WRITE-RECOVERED-OK, requests=3 writes=1 continuations=1. Crabbox run
  • Supplemental Codex app-server proof: real Codex app-server runtime against the deterministic mock provider, comparing OpenClaw and Codex cells. The disposable fixture override only made the scenario runtime-pair selectable and removed its OpenClaw-specific continuation-string assertion; production code remained the exact PR head. Both cells passed and Codex delivered EMPTY-RECOVERED-OK with normalized usage. Runtime-pair run, structured-result verification

Downloaded evidence is under .artifacts/qa-e2e/108738-{base-repro,candidate-fix,runtime-pair}/. The broker inventory had multiple active ordinary telegram rows. No telegram-user credential was leased.

@joshavant
joshavant marked this pull request as ready for review July 21, 2026 00:56
@joshavant
joshavant force-pushed the fix/108738-settled-tool-continuation branch from a2ab1d2 to 6302e79 Compare July 21, 2026 04:43
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 21, 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: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@joshavant

Copy link
Copy Markdown
Collaborator Author

Implemented the accepted terminal-reply contract follow-up in 1c56f46:

  • The embedded runner now accepts an explicit required/optional terminal reply expectation while preserving existing user/manual defaults.
  • Isolated cron maps resolved announce delivery to required; none, webhook, and unresolved routes remain optional.
  • Added focused required/optional/invalid-route coverage and a permanent Gateway + scheduler + write-tool + qa-channel regression scenario for [7.1 regression] tool-only turn produces empty final text — outbound payload dropped, control UI hides turn #108738.
  • Tightened the QA fixture so recovery does not shadow later heartbeat turns and the scenario requires exactly one outbound delivery.

Proof:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: copilot labels Jul 21, 2026
obviyus added a commit that referenced this pull request Sep 21, 2026
Related: #110565

## What Problem This Solves

Fixes announced automations being treated as missing replies when they intentionally have nothing to report.

## User Impact

User impact: scheduled jobs can finish silently without an unwanted recovery answer or a false missing-payload error. Direct user messages still require a reply. Execution failures, cancellations, failed child handoffs, and transport errors remain failures.

## Why This Change Was Made

An announce destination selects where an automation's output goes; it does not require output on every run. Both CLI and embedded execution now receive the same optional-reply contract. The cron finalizer consumes the runtime outcome instead of independently classifying empty output as failure.

This restores the documented automation contract without changing configuration, stored jobs, tool permissions, or retry budgets. It does not interpret an assistant's prose as proof that an arbitrary task succeeded.

## Evidence

- The same announced `NO_REPLY` job failed on baseline `6beea0a8521`: two provider requests followed by `incomplete_turn`. Its test job was removed and runner cleanup completed.
- 130 focused tests passed in **61.04 seconds wall time** across cron completion, CLI reply hooks, and embedded terminal resolution; 98 CLI-policy and fallback-classification tests also passed in **57.01 seconds wall time** after cleanup. Coverage includes required direct-user `NO_REPLY` recovery, optional silence, provider/tool errors, cancellation, failed child handoffs, and delivery errors.
- Telegram Test Server, leased real-user recorder, isolated Gateway at `8ffdf068593`: an announced cron returning `NO_REPLY` completed with `runStatus: ok`, one provider request, and zero SUT messages. The job was removed and runner scratch cleaned up.
- Direct-user control on the same candidate: the model first returned `NO_REPLY`; recovery made one continuation request and Telegram showed exactly one `CRON_REPLY_HUMAN_OK` message. Utility recaps were disabled in this isolated fixture so the injected silence reached the user turn, not background work.
- Full build, scoped type-aware lint, both full dead-code scans, formatting, and whitespace checks passed. Production code shrank by 43 lines. The follow-up only inlines an unchanged internal predicate and removes an obsolete test assertion; it does not change the Telegram-tested behavior.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
Related: openclaw#110565

## What Problem This Solves

Fixes announced automations being treated as missing replies when they intentionally have nothing to report.

## User Impact

User impact: scheduled jobs can finish silently without an unwanted recovery answer or a false missing-payload error. Direct user messages still require a reply. Execution failures, cancellations, failed child handoffs, and transport errors remain failures.

## Why This Change Was Made

An announce destination selects where an automation's output goes; it does not require output on every run. Both CLI and embedded execution now receive the same optional-reply contract. The cron finalizer consumes the runtime outcome instead of independently classifying empty output as failure.

This restores the documented automation contract without changing configuration, stored jobs, tool permissions, or retry budgets. It does not interpret an assistant's prose as proof that an arbitrary task succeeded.

## Evidence

- The same announced `NO_REPLY` job failed on baseline `c7725c10b87`: two provider requests followed by `incomplete_turn`. Its test job was removed and runner cleanup completed.
- 130 focused tests passed in **61.04 seconds wall time** across cron completion, CLI reply hooks, and embedded terminal resolution; 98 CLI-policy and fallback-classification tests also passed in **57.01 seconds wall time** after cleanup. Coverage includes required direct-user `NO_REPLY` recovery, optional silence, provider/tool errors, cancellation, failed child handoffs, and delivery errors.
- Telegram Test Server, leased real-user recorder, isolated Gateway at `8ffdf068593`: an announced cron returning `NO_REPLY` completed with `runStatus: ok`, one provider request, and zero SUT messages. The job was removed and runner scratch cleaned up.
- Direct-user control on the same candidate: the model first returned `NO_REPLY`; recovery made one continuation request and Telegram showed exactly one `CRON_REPLY_HUMAN_OK` message. Utility recaps were disabled in this isolated fixture so the injected silence reached the user turn, not background work.
- Full build, scoped type-aware lint, both full dead-code scans, formatting, and whitespace checks passed. Production code shrank by 43 lines. The follow-up only inlines an unchanged internal predicate and removes an obsolete test assertion; it does not change the Telegram-tested behavior.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…ht after it (#162367)

Related: #110565, #115104, #119605

## What Problem This Solves

Fixes: a chat gets two nearly identical messages when a turn sends a progress update with `message(final=false)` and then ends without a final answer.

In our setup a group turn sent "started the run, I'll report back" as progress and stopped empty. Settled-turn finalization then made an extra model call, which restated the same progress, and both messages landed 12 s apart.

## User Impact

If the last thing a turn does is post progress to the current conversation and then it stops empty or with `NO_REPLY`, that progress message is the reply. No second model call, no duplicate. Turns that did more work after or alongside the progress, or that sent nothing, still get finalization.

## Why This Change Was Made

Provenance:

- Settled-turn finalization (#110565, closes #108738) exists so users are never left with no reply after tools ran but the model said nothing. Fallback text after an empty finalizer came later in #133520; #138645 keeps that fallback private in message-tool-only groups.
- `final:false` vs `final:true` (#105365, then the shared contract in #119605) keeps progress from ending a run early and keeps a later failure visible after progress.
- #115104 (fixing #111764) made marked progress *permit* finalization. #111764's caveat was progress sent early in a long tool run, followed by an empty final completion, which was swallowed silently. #127070 applied the same rule to queued follow-ups.

Root cause: none of these checks look at order. A progress message sent as the turn's **last** tool batch was written after the model had seen every other tool result. When the model then stops empty, the finalizer gets the same transcript and no new information, so all it can do is restate the progress. That is the duplicate. The #111764 case is different: there, tool work came after the progress, and that case is unchanged.

Fix: the decision happens when the runtime settles the attempt (`completeEmbeddedAttemptResult`), not per assistant message. The embedded subscriber only records, per provider turn (reset on `turn_start`), whether every tool that finished in that turn was a complete, non-error, non-partial `final:false` text send to the current source, and it keeps that fact for the latest turn that ran tools. At settlement, if that holds, the run ended normally (`terminal.kind === "ok"`), and the terminal assistant response stopped with empty text or `NO_REPLY`, the attempt result marks that latest progress send final and sets `sourceReplyDeliveryState: "delivered"`. Every downstream consumer (finalization gate, terminal resolution, follow-up delivery, run-entry terminal reply) then sees the same completed-reply fact an explicit `final:true` produces. No consumer special case, no prompt or tool-text change. Native-async fragments do not split a turn: an async send followed by a later tool turn, or async work and progress in the same response, still finalizes. Progress reactions, partial or errored sends, closing text, and work in the same batch keep today's behavior.

Options considered:
- Give the finalizer the sent text and accept `NO_REPLY`: this still costs a model call, depends on the model's judgment, and needs a new "empty finalizer is fine" path next to the #133520 fallback.
- Tighten the `final` tool description: models already end empty after progress, so this cannot guarantee anything.

Hermes (`agent/turn_empty_response.py`) handles this the same way. When an empty response follows visible content with only housekeeping tools after it, Hermes reuses that content as the final answer and marks it as already shown so it is not re-sent. It nudges once only when substantive tools ran after the content.

Scope: this changes only the embedded runner. Codex app-server turns can plausibly hit the same duplicate: Codex marks `final:false` in `dynamic-tools.ts` and can complete a turn with no agent message. But "nothing ran after the progress" there depends on item order across native Codex items (shell, apply_patch) that never pass through the OpenClaw dynamic-tool bridge. That makes the Codex event projector a separate owner, so it is a follow-up.

No overlap with Pash/Sarah changes: `a2bbcbf40684` and #154217 touch unrelated hunks in these files, and intentional `NO_REPLY` after a delivered message stays honored.

## Bounded cost

- The new path only removes a model call: when the latest tool batch was only complete progress sends and the model then stops empty, settled finalization is skipped (0 extra calls instead of up to 2).
- Every other path is unchanged: settled finalization keeps its existing cap of 2 tool-free attempts (`MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS`, covered by `settled-turn-finalization.test.ts`). The finalizer has no tools, so it cannot send progress and cannot re-enter this path.
- The settlement check runs once per attempt result and does not schedule retries, runs, or model calls.
- Tested: `attempt-result.test.ts` drives the real `runAgentLoop` with the real subscriber, then the real `completeEmbeddedAttemptResult` and `resolveSettledToolTerminalContinuationInstruction`. Progress-last followed by an empty terminal gives a delivered reply and no finalizer. Two cases still finalize: an async progress send, then an empty tail, then a read, then an empty terminal; and async read plus progress in one response, then an empty terminal. Each failed on the head before its fix with `expected 'delivered' to be 'missing'`. The QA scenario asserts 2 model requests (no finalization request) for progress-then-empty and 3 for the write-then-empty control.

## Evidence

QA lab, mock-openai, isolated gateway child, qa-channel group with `visibleReplies: message_tool`. New scenario `group-progress-then-empty-finalization`:

- Before (origin/main + scenario): fail. The progress room got `["Started the run, I will report back. QA-GROUP-PROGRESS-OK", "Still running, I will report back. QA-GROUP-PROGRESS-OK"]`.
- After: pass. The progress room got 1 post and made 2 model requests (no finalization request). The control room (write, then empty stop, nothing sent) still ran finalization, made 3 model requests, and posted `QA-GROUP-WRITE-FINALIZED-OK` once.

Settlement regressions in `attempt-result.test.ts` (real agent loop): on the previous per-message head, the async-continuation case fails with `expected 'delivered' to be 'missing'`. Subscriber batch-fact table: only-progress is true; same-batch work, a later batch, a reaction, and a partial/errored send are false. Focused suites pass: attempt-result (43), suppression (32), tools handler, settled-tool evidence, settled-turn finalization, attempt-execution-phase, and lifecycle.

Real gateway (qa-channel, round 3 head): the scenario passes with 1 progress post and 2 requests, and the write control finalizes with 3 requests. The scenario is the only CI-runnable check of the consumer chain after the attempt result: run-loop finalization admission, terminal resolution, payload building, and channel delivery. The loop tests stop at the delivery fact, so a consumer that ignored it would still pass them, but here it would post a second message.

### Live model, Telegram Test Server group

Setup: a real user in the QA group, `messages.groupChat.visibleReplies: message_tool`, live OpenAI `gpt-5.5` through a pass-through proxy, isolated gateway. The prompt asked the model to post a `final:false` progress update saying the report run started and then stop. In both runs below the model did that unsteered: one successful `message(final:false)`, then an empty stop. In each run the bot's transient status draft (`Working`) appears and is deleted after delivery; that is existing progress-draft behavior and the same before and after.

| Run | Bot posts that remain | Model requests (main agent) | Finalizer |
|---|---|---|---|
| Before, origin/main `7dd6ab7` | 2: `Monthly report run has started — I’ll report back here when it finishes.` (t=13.1 s), then `Done.` (t=17.7 s) | 3 | ran (`settled post-tool turn lacked a final answer`) |
| After, `e27810b` | 1: `Monthly report run started. I’ll report back here when it finishes.` (t=13.8 s) | 2 | not run |

Control on `e27810b` (finalizer must still run after real work): the model posted `Checking the clock now.` with `final:false`, then ran `exec date -u`. The proxy replaced only the model's next response with an empty turn, which is the incident's "ends empty" shape; the finalizer request itself went to the live model. The finalizer ran and the group received `The UTC time is Thu Oct 1 13:08:11 UTC 2026.`

An earlier variant that told the model to end with `NO_REPLY` produced one post on both refs: on main the live finalizer also answered `NO_REPLY` twice, and the private fallback stayed private per #138645. Main still spent 2 extra model calls there; the fix spends none.

LOC vs merge base: production +47/-3 (`src/agents` subscriber + attempt-result), docs +5/-1, tests and QA fixtures +441.

Test cost (`pnpm test <file> --maxWorkers=1`, wall, head e27810b, shared loaded host): `attempt-result.test.ts` 46.4 s for 44 tests, with the 3 new real-loop cases at 0.2 to 0.6 s each; `embedded-agent-subscribe.subscribe-embedded-agent-session.source-reply-suppression.test.ts` 53.4 s for 32 tests, with the 5 batch-fact cases at 4 to 160 ms each. Most of the wall time is import and transform. The new cases use no timers, sleeps, or gateway boots. No attributable CI timing exists yet for this head.

CI on 959c8b0 (run 36873121248, after one rerun of failed jobs):
- `gateway-timeout-recovery-subagent.e2e.test.ts`: fails 2 of 2 locally on clean origin/main. Known flake #161139, with fixture fix #162260 open. The scenario never uses the message tool.
- `src/gateway/server.chat-steer-direct-command.test.ts` (skills watchers left open): fails the same way on four unrelated PRs today: `steipete/session-store-agent-db-drain`, `chore/chrome-devtools-mcp-1.10.1`, `chore/npm-12-1-20261001`, `codex/repair-child-completion`.
- `node-worker-launch-wire.e2e.test.ts` and `telegram-model-picker-prepared-gateway.e2e.test.ts`: red on the first attempt and green on rerun; both pass locally on head and on main.
- `src/auto-reply/reply/dispatch-from-config.secrets.test.ts` "quiet group link": still red. Only the file's first case fails, at its default 1 s `vi.waitFor`; that case took 1437 ms in CI while the following cases took about 60 ms. The same three-file shard passes locally on the head, on head merged with current main, with `CI=true`, and twice on main under `taskpolicy -b`. The test drives the `secrets` tool, which never touches the message-tool progress path, the new `turn_start` reset, or attempt-result settlement. I could not reproduce it on main or find it on another PR's CI from the last two days (93 failed node jobs scanned), so this one is not proven unrelated.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…ht after it (openclaw#162367)

Related: openclaw#110565, openclaw#115104, openclaw#119605

## What Problem This Solves

Fixes: a chat gets two nearly identical messages when a turn sends a progress update with `message(final=false)` and then ends without a final answer.

In our setup a group turn sent "started the run, I'll report back" as progress and stopped empty. Settled-turn finalization then made an extra model call, which restated the same progress, and both messages landed 12 s apart.

## User Impact

If the last thing a turn does is post progress to the current conversation and then it stops empty or with `NO_REPLY`, that progress message is the reply. No second model call, no duplicate. Turns that did more work after or alongside the progress, or that sent nothing, still get finalization.

## Why This Change Was Made

Provenance:

- Settled-turn finalization (openclaw#110565, closes openclaw#108738) exists so users are never left with no reply after tools ran but the model said nothing. Fallback text after an empty finalizer came later in openclaw#133520; openclaw#138645 keeps that fallback private in message-tool-only groups.
- `final:false` vs `final:true` (openclaw#105365, then the shared contract in openclaw#119605) keeps progress from ending a run early and keeps a later failure visible after progress.
- openclaw#115104 (fixing openclaw#111764) made marked progress *permit* finalization. openclaw#111764's caveat was progress sent early in a long tool run, followed by an empty final completion, which was swallowed silently. openclaw#127070 applied the same rule to queued follow-ups.

Root cause: none of these checks look at order. A progress message sent as the turn's **last** tool batch was written after the model had seen every other tool result. When the model then stops empty, the finalizer gets the same transcript and no new information, so all it can do is restate the progress. That is the duplicate. The openclaw#111764 case is different: there, tool work came after the progress, and that case is unchanged.

Fix: the decision happens when the runtime settles the attempt (`completeEmbeddedAttemptResult`), not per assistant message. The embedded subscriber only records, per provider turn (reset on `turn_start`), whether every tool that finished in that turn was a complete, non-error, non-partial `final:false` text send to the current source, and it keeps that fact for the latest turn that ran tools. At settlement, if that holds, the run ended normally (`terminal.kind === "ok"`), and the terminal assistant response stopped with empty text or `NO_REPLY`, the attempt result marks that latest progress send final and sets `sourceReplyDeliveryState: "delivered"`. Every downstream consumer (finalization gate, terminal resolution, follow-up delivery, run-entry terminal reply) then sees the same completed-reply fact an explicit `final:true` produces. No consumer special case, no prompt or tool-text change. Native-async fragments do not split a turn: an async send followed by a later tool turn, or async work and progress in the same response, still finalizes. Progress reactions, partial or errored sends, closing text, and work in the same batch keep today's behavior.

Options considered:
- Give the finalizer the sent text and accept `NO_REPLY`: this still costs a model call, depends on the model's judgment, and needs a new "empty finalizer is fine" path next to the openclaw#133520 fallback.
- Tighten the `final` tool description: models already end empty after progress, so this cannot guarantee anything.

Hermes (`agent/turn_empty_response.py`) handles this the same way. When an empty response follows visible content with only housekeeping tools after it, Hermes reuses that content as the final answer and marks it as already shown so it is not re-sent. It nudges once only when substantive tools ran after the content.

Scope: this changes only the embedded runner. Codex app-server turns can plausibly hit the same duplicate: Codex marks `final:false` in `dynamic-tools.ts` and can complete a turn with no agent message. But "nothing ran after the progress" there depends on item order across native Codex items (shell, apply_patch) that never pass through the OpenClaw dynamic-tool bridge. That makes the Codex event projector a separate owner, so it is a follow-up.

No overlap with Pash/Sarah changes: `77fbaa7ae43d` and openclaw#154217 touch unrelated hunks in these files, and intentional `NO_REPLY` after a delivered message stays honored.

## Bounded cost

- The new path only removes a model call: when the latest tool batch was only complete progress sends and the model then stops empty, settled finalization is skipped (0 extra calls instead of up to 2).
- Every other path is unchanged: settled finalization keeps its existing cap of 2 tool-free attempts (`MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS`, covered by `settled-turn-finalization.test.ts`). The finalizer has no tools, so it cannot send progress and cannot re-enter this path.
- The settlement check runs once per attempt result and does not schedule retries, runs, or model calls.
- Tested: `attempt-result.test.ts` drives the real `runAgentLoop` with the real subscriber, then the real `completeEmbeddedAttemptResult` and `resolveSettledToolTerminalContinuationInstruction`. Progress-last followed by an empty terminal gives a delivered reply and no finalizer. Two cases still finalize: an async progress send, then an empty tail, then a read, then an empty terminal; and async read plus progress in one response, then an empty terminal. Each failed on the head before its fix with `expected 'delivered' to be 'missing'`. The QA scenario asserts 2 model requests (no finalization request) for progress-then-empty and 3 for the write-then-empty control.

## Evidence

QA lab, mock-openai, isolated gateway child, qa-channel group with `visibleReplies: message_tool`. New scenario `group-progress-then-empty-finalization`:

- Before (origin/main + scenario): fail. The progress room got `["Started the run, I will report back. QA-GROUP-PROGRESS-OK", "Still running, I will report back. QA-GROUP-PROGRESS-OK"]`.
- After: pass. The progress room got 1 post and made 2 model requests (no finalization request). The control room (write, then empty stop, nothing sent) still ran finalization, made 3 model requests, and posted `QA-GROUP-WRITE-FINALIZED-OK` once.

Settlement regressions in `attempt-result.test.ts` (real agent loop): on the previous per-message head, the async-continuation case fails with `expected 'delivered' to be 'missing'`. Subscriber batch-fact table: only-progress is true; same-batch work, a later batch, a reaction, and a partial/errored send are false. Focused suites pass: attempt-result (43), suppression (32), tools handler, settled-tool evidence, settled-turn finalization, attempt-execution-phase, and lifecycle.

Real gateway (qa-channel, round 3 head): the scenario passes with 1 progress post and 2 requests, and the write control finalizes with 3 requests. The scenario is the only CI-runnable check of the consumer chain after the attempt result: run-loop finalization admission, terminal resolution, payload building, and channel delivery. The loop tests stop at the delivery fact, so a consumer that ignored it would still pass them, but here it would post a second message.

### Live model, Telegram Test Server group

Setup: a real user in the QA group, `messages.groupChat.visibleReplies: message_tool`, live OpenAI `gpt-5.5` through a pass-through proxy, isolated gateway. The prompt asked the model to post a `final:false` progress update saying the report run started and then stop. In both runs below the model did that unsteered: one successful `message(final:false)`, then an empty stop. In each run the bot's transient status draft (`Working`) appears and is deleted after delivery; that is existing progress-draft behavior and the same before and after.

| Run | Bot posts that remain | Model requests (main agent) | Finalizer |
|---|---|---|---|
| Before, origin/main `449f5a8` | 2: `Monthly report run has started — I’ll report back here when it finishes.` (t=13.1 s), then `Done.` (t=17.7 s) | 3 | ran (`settled post-tool turn lacked a final answer`) |
| After, `e27810b` | 1: `Monthly report run started. I’ll report back here when it finishes.` (t=13.8 s) | 2 | not run |

Control on `e27810b` (finalizer must still run after real work): the model posted `Checking the clock now.` with `final:false`, then ran `exec date -u`. The proxy replaced only the model's next response with an empty turn, which is the incident's "ends empty" shape; the finalizer request itself went to the live model. The finalizer ran and the group received `The UTC time is Thu Oct 1 13:08:11 UTC 2026.`

An earlier variant that told the model to end with `NO_REPLY` produced one post on both refs: on main the live finalizer also answered `NO_REPLY` twice, and the private fallback stayed private per openclaw#138645. Main still spent 2 extra model calls there; the fix spends none.

LOC vs merge base: production +47/-3 (`src/agents` subscriber + attempt-result), docs +5/-1, tests and QA fixtures +441.

Test cost (`pnpm test <file> --maxWorkers=1`, wall, head e27810b, shared loaded host): `attempt-result.test.ts` 46.4 s for 44 tests, with the 3 new real-loop cases at 0.2 to 0.6 s each; `embedded-agent-subscribe.subscribe-embedded-agent-session.source-reply-suppression.test.ts` 53.4 s for 32 tests, with the 5 batch-fact cases at 4 to 160 ms each. Most of the wall time is import and transform. The new cases use no timers, sleeps, or gateway boots. No attributable CI timing exists yet for this head.

CI on 959c8b0 (run 36873121248, after one rerun of failed jobs):
- `gateway-timeout-recovery-subagent.e2e.test.ts`: fails 2 of 2 locally on clean origin/main. Known flake openclaw#161139, with fixture fix openclaw#162260 open. The scenario never uses the message tool.
- `src/gateway/server.chat-steer-direct-command.test.ts` (skills watchers left open): fails the same way on four unrelated PRs today: `steipete/session-store-agent-db-drain`, `chore/chrome-devtools-mcp-1.10.1`, `chore/npm-12-1-20261001`, `codex/repair-child-completion`.
- `node-worker-launch-wire.e2e.test.ts` and `telegram-model-picker-prepared-gateway.e2e.test.ts`: red on the first attempt and green on rerun; both pass locally on head and on main.
- `src/auto-reply/reply/dispatch-from-config.secrets.test.ts` "quiet group link": still red. Only the file's first case fails, at its default 1 s `vi.waitFor`; that case took 1437 ms in CI while the following cases took about 60 ms. The same three-file shard passes locally on the head, on head merged with current main, with `CI=true`, and twice on main under `taskpolicy -b`. The test drives the `secrets` tool, which never touches the message-tool progress path, the new `turn_start` reset, or attempt-result settlement. I could not reproduce it on main or find it on another PR's CI from the last two days (93 failed node jobs scanned), so this one is not proven unrelated.

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 extensions: codex extensions: copilot extensions: qa-lab maintainer Maintainer-authored PR mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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.

[7.1 regression] tool-only turn produces empty final text — outbound payload dropped, control UI hides turn

3 participants