Skip to content

fix: finish completed tool work after empty final responses - #115104

Merged
steipete merged 2 commits into
mainfrom
codex/fix-settled-empty-finalization
Aug 10, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/fix-settled-empty-finalization

Conversation

@steipete

@steipete steipete commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #111764
Related: #108738, #110565

What Problem This Solves

A settled tool turn can run its isolated, tool-disabled finalizer successfully and still receive a normal completed response with no visible text. Current main turns that valid completed-empty result into an exception, classifies finalization as failed, and surfaces the generic “Agent couldn't generate a response” warning even though the tool work completed.

The secondary failure was at the continuation gate: any messaging-tool send suppressed finalization, so an explicit sourceReplyFinal: false progress update could be mistaken for the terminal source reply.

Why This Change Was Made

This rewrite preserves the private lifecycle outcome introduced on the prior branch but applies Peter's explicit product decision: completed-empty is silent success.

  • The harness lifecycle distinguishes answered from empty only after a normally stopped, capability-free finalizer. Empty is a completed diagnostic outcome, not a harness error. Explicit NO_REPLY, tool calls, interruption, provider errors, compaction, and capability activity remain rejected.
  • The embedded terminal path carries completed-empty as a closed finalization fact, returns no payload, no NO_REPLY, no filler assistant text, and no meta.error. Run-entry's existing terminal owner records canonical completed/ok plus terminal reply disposition empty.
  • Existing authoritative tool-error payloads and failureSignal win over empty completion, so a real failed tool remains visible and is never relabeled successful.
  • The finalizer gate uses explicit final/progress messaging evidence while preserving legacy unmarked-send semantics. Marked progress permits finalization; marked final and legacy sends do not.
  • agent-run-terminal-outcome.ts remains the sole terminal precedence owner. No new terminal reason or downstream status inference was added.

The Codex integration opts into empty text only for the isolated settled-turn finalizer. Ordinary bounded Codex callers still reject an empty response, and an empty finalizer result is not mirrored into transcript history.

User Impact

When settled tool work completes and the isolated finalizer also completes without text, OpenClaw delivers nothing while recording a truthful completed-empty internal outcome. There is no fabricated summary in delivery, transcripts, or prompt history. Progress messages no longer suppress a required finalizer. Real provider, timeout, abort, and failed-tool outcomes remain honest.

No configuration, default, public/plugin API, protocol version, SQLite schema, or authorization policy changes.

Evidence

  • Pre-fix lifecycle owner: node scripts/run-vitest.mjs src/agents/harness/settled-turn-finalization-result.test.ts src/agents/harness/lifecycle.test.ts src/agents/embedded-agent-runner/run.incomplete-turn.test.ts failed the completed-empty classifier because main emitted a generic Error instead of the private lifecycle outcome.
  • Pre-fix embedded owner: node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run.incomplete-turn.test.ts reported 4 failures / 171 passing: completed-empty became the generic tool-side-effect warning, failed-tool fallback was misclassified, marked progress blocked finalization, and a settled continuation was skipped.
  • Passing-after on head 7d374a0c5c5fd3bf0bb469dc5b6a2200771bfed0: the expanded focused command covering validator, lifecycle, selection, embedded owner, Codex bounded turn, and Codex finalizer passed 347 tests across 4 Vitest shards.
  • Exact-head CI exposed one stale sibling assertion in src/agents/harness/selection.test.ts; it now asserts the new outcome: "answered" plus nested result shape while retaining the original assistant-content contract.
  • node scripts/check-changed.mjs passed on Blacksmith Testbox tbx_01kzpk7dz62srswem488tvqsm9 (Actions run 31425511650): env ratchet 503/503, Plugin SDK baseline unchanged, all four typecheck lanes, core/extension lint, boundaries, dead exports, and database-first guards passed.
  • Codex-backed autoreview completed in one round with no accepted/actionable findings (0.93 confidence).
  • Production LOC: +149/-52. Tests: +155/-22. The production growth establishes one private closed lifecycle outcome across generic and Codex harnesses while retaining the existing canonical terminal/reply owners.
  • Direct pinned Codex inspection at rust-v0.147.0: codex-rs/app-server/src/thread_state.rs:158-170 records a final item only for nonblank final text; codex-rs/app-server/src/bespoke_event_handling.rs:1276-1301 serializes a missing final item as an empty item list; and codex-rs/app-server/src/bespoke_event_handling.rs:1470-1497 still emits TurnStatus::Completed when there is no error.
  • ClawSweeper rank-up moves are resolved: Peter explicitly chose silent completed-empty success; the branch was rebased onto green main; direct Codex source was inspected; exact-head required CI is watched to completion before prepare.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Jul 28, 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: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 28, 2026
@clawsweeper

clawsweeper Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 10, 2026, 3:52 PM ET / 19:52 UTC.

ClawSweeper review

What this changes

The PR classifies normally completed textless settled-turn finalizers as completed-empty and permits explicitly marked progress sends to continue to finalization.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep this protected PR open: it can duplicate a reply in mixed progress/legacy delivery cases and omits completed-empty finalizer accounting from terminal metadata.

Priority: P1
Reviewed head: b7056bf9bf8289a87cc8aade48efab2524d4903e

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The intended path has focused evidence, but two concrete lifecycle defects block merge.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its supplied focused evidence does not cover the two source-proven blockers.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its supplied focused evidence does not cover the two source-proven blockers.
Evidence reviewed 8 items Mixed delivery regression: The new helper accepts any explicit progress marker as conclusive, so an unmarked legacy send in the same run is ignored and finalization can emit a duplicate reply.
Stale completed-empty metadata: The empty branch merges usage after terminal preparation, returns the old preparation, and does not merge assistant-turn statistics; terminal metadata therefore excludes the finalizer work.
Metadata owner: Terminal preparation derives usage, cost, and assistant-turn count from the usage accumulator, and run-loop forwards that prepared metadata to terminal resolution.
Findings 2 actionable findings [P1] Preserve legacy delivery suppression with marked progress
[P2] Rebuild terminal metadata after empty finalization
Security None None.

How this fits together

After tool work settles, the embedded agent runner checks delivery evidence to decide whether it needs a tool-disabled final response. The selected harness result then feeds terminal channel payloads and run metadata.

flowchart LR
A[Settled tool work] --> B[Delivery evidence]
B --> C{Reply complete?}
C -->|No| D[Isolated finalizer]
D --> E{Visible text?}
E -->|Yes| F[Reply payload]
E -->|No| G[Completed-empty state]
F --> H[Terminal metadata]
G --> H
Loading

Before merge

  • Preserve legacy delivery suppression with marked progress (P1) - A sourceReplyFinal: false marker returns false before unmarked legacy send evidence is considered. If both occur in one run, finalization can emit a duplicate source reply; only let marked progress permit finalization when all relevant send evidence is explicitly progress-marked.
  • Rebuild terminal metadata after empty finalization (P2) - This branch records finalizer usage after prepared has already captured agentMeta, then returns the stale preparation. The completed run omits finalizer usage, cost, and assistant-turn accounting; merge the finalizer's attempt stats and rebuild terminal preparation before returning.
  • Resolve merge risk (P1) - Mixed marked-progress and unmarked legacy sends can produce a duplicate final reply.
  • Resolve merge risk (P1) - Completed-empty finalizers can omit usage, cost, and assistant-turn accounting from the returned run metadata.
  • Resolve merge risk (P1) - The required sibling Codex source checkout is unavailable, so the Codex protocol claim cannot be independently audited here.

Findings

  • [P1] Preserve legacy delivery suppression with marked progress — src/agents/embedded-agent-runner/delivery-evidence.ts:89-96
  • [P2] Rebuild terminal metadata after empty finalization — src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:109-130
Agent review details

Security

None.

PR surface

Source +97, Tests +130. Total +227 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 13 150 53 +97
Tests 5 150 20 +130
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 300 73 +227

Review metrics

Metric Value Why it matters
Production versus tests production +149/-52, tests +151/-21 This bug fix expands shared lifecycle behavior; the positive production delta must include the two owner-boundary repairs before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #111764
Summary: This PR is the remaining candidate fix for completed-empty finalization, while its two blockers are distinct regressions in the proposed implementation.

Members:

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

Merge-risk options

Maintainer options:

  1. Repair delivery and accounting (recommended)
    Retain legacy-send suppression in mixed evidence and rebuild terminal metadata after recording completed-empty finalizer work.

Technical review

Best possible solution:

Preserve conservative suppression for all unmarked delivery evidence and rebuild terminal preparation after completed-empty accounting so payloads and metadata derive from the same final facts.

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

Yes: a run with one sourceReplyFinal: false target plus an unmarked legacy send passes the new gate, and the completed-empty branch returns metadata prepared before finalizer usage is merged.

Is this the best way to solve the issue?

No: the best fix is to preserve legacy delivery suppression in mixed evidence and rebuild terminal preparation after adding finalizer statistics.

Full review comments:

  • [P1] Preserve legacy delivery suppression with marked progress — src/agents/embedded-agent-runner/delivery-evidence.ts:89-96
    A sourceReplyFinal: false marker returns false before unmarked legacy send evidence is considered. If both occur in one run, finalization can emit a duplicate source reply; only let marked progress permit finalization when all relevant send evidence is explicitly progress-marked.
    Confidence: 0.94
  • [P2] Rebuild terminal metadata after empty finalization — src/agents/embedded-agent-runner/run/settled-turn-finalization.ts:109-130
    This branch records finalizer usage after prepared has already captured agentMeta, then returns the stale preparation. The completed run omits finalizer usage, cost, and assistant-turn accounting; merge the finalizer's attempt stats and rebuild terminal preparation before returning.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8a5978154f69.

Labels

Label changes:

  • add merge-risk: 🚨 other: Completed-empty finalizer work is missing from returned terminal usage and cost metadata.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its supplied focused evidence does not cover the two source-proven blockers.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: The changed delivery gate can send an extra source reply after tool work.
  • merge-risk: 🚨 message-delivery: Mixed legacy and explicit-progress send evidence can be misclassified as eligible for finalization.
  • merge-risk: 🚨 other: Completed-empty finalizer work is missing from returned terminal usage and cost metadata.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its supplied focused evidence does not cover the two source-proven blockers.

Evidence

What I checked:

Likely related people:

  • steipete: Recent lifecycle history and the active branch concentrate on this terminal-finalization path. (role: recent area contributor; confidence: high; commits: b7056bf9bf82, 1fedcca9a916, e9e6ef3edbf2; files: src/agents/embedded-agent-runner/delivery-evidence.ts, src/agents/embedded-agent-runner/run/settled-turn-finalization.ts)
  • joshavant: Introduced the settled-tool finalization flow that this branch modifies. (role: introduced behavior; confidence: high; commits: 6eea20ce181e; files: src/agents/embedded-agent-runner/run/settled-turn-finalization.ts)
  • Brian Snyder: Authored the Codex finalizer prompt-echo follow-up in the same finalization surface. (role: adjacent Codex contributor; confidence: medium; commits: cce8a21492a5; files: extensions/codex/src/app-server/settled-turn-finalizer.ts)

Rank-up moves

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

  • Add mixed marked-progress plus unmarked-legacy delivery coverage.
  • Assert completed-empty finalizer usage and assistant-turn metadata.
  • Re-run the focused lifecycle and delivery suites.

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 (5 earlier review cycles)
  • reviewed 2026-07-28T09:24:44.531Z sha ef1d4a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-03T15:51:15.756Z sha ef1d4a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-09T11:54:32.137Z sha f74ccaa :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T17:02:12.768Z sha 4be89aac81d3bdf5997628b39511ef3e4eeaf798 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T18:51:48.106Z sha b131c009bcf408e2a837c9d159aa76f40a368f11 :: needs maintainer review before merge. :: none

@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 Aug 3, 2026
@steipete steipete self-assigned this Aug 9, 2026
@steipete
steipete force-pushed the codex/fix-settled-empty-finalization branch from ef1d4a8 to f74ccaa Compare August 9, 2026 11:05
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 9, 2026
@steipete
steipete force-pushed the codex/fix-settled-empty-finalization branch from f74ccaa to 4be89aa Compare August 10, 2026 15:48
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed mantis: telegram-visible-proof Mantis should capture Telegram visible proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 10, 2026
@steipete
steipete force-pushed the codex/fix-settled-empty-finalization branch 2 times, most recently from b131c00 to b7056bf Compare August 10, 2026 19:26
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 10, 2026
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Aug 10, 2026
@steipete
steipete force-pushed the codex/fix-settled-empty-finalization branch from b7056bf to 7d374a0 Compare August 10, 2026 20:00
@steipete
steipete merged commit 9a0ea5d into main Aug 10, 2026
198 of 200 checks passed
@steipete
steipete deleted the codex/fix-settled-empty-finalization branch August 10, 2026 20:24
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 11, 2026
…#115104)

* fix(agents): record completed-empty finalization

* test(agents): align settled finalization outcome assertion
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 extensions: codex maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

1 participant