Skip to content

fix(agent): allow message-tool progress before the final reply - #119605

Merged
obviyus merged 1 commit into
openclaw:mainfrom
Glucksberg:fix/102179-finality-aware-message-tool
Aug 10, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
Glucksberg:fix/102179-finality-aware-message-tool

Conversation

@Glucksberg

@Glucksberg Glucksberg commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #116426
Related: #96827

What Problem This Solves

Fixes an issue where agents using message-tool-only replies could send one visible update, then hit a durable terminal-delivery rejection on the next update and retry the same failed call repeatedly.

Why This Change Was Made

The shared message tool now exposes one finality contract to generic, Claude CLI, and Codex runtimes: final=false sends progress; final=true or omission sends the completed current-source reply. Finality is recorded before provider I/O, carried in the tool result, and ends embedded runs only after confirmed delivery.

A later terminal call with an existing durable outcome returns already_delivered or delivery_ambiguous as a non-error result without provider I/O. This removes the model retry cascade while preserving crash-safe receipt ordering. CLI failures after progress remain visible. Codex's separate schema projection and turn-end inference were deleted.

Upstream Codex dynamic tools accept OpenClaw's JSON schema and forward arguments unchanged (codex-rs/protocol/src/dynamic_tools.rs, codex-rs/app-server/src/dynamic_tools.rs); finality therefore belongs to the shared OpenClaw message-tool contract, not the Codex protocol.

User Impact

Agents can send visible progress followed by one final source reply without repeated delivery failures. Existing one-shot calls remain terminal when final is omitted. Automatic source replies and explicit out-of-band sends are unchanged.

Evidence

  • Current-main fault proof: a generic omitted source send arms a terminal receipt; the next terminal send is rejected before provider dispatch.
  • Focused local proof: 800/800 tests passed in one grouped command across schema/prompt, embedded and CLI evidence, durable receipt, gateway no-send outcomes, and Codex projection.
  • Targeted Oxfmt, Oxlint, core tsgo, and extensions tsgo passed.
  • Production LOC: +140 / -165 (net -25). Tests: +164 / -88 (net +76).
  • Distill: one shared finality contract replaces Codex-only projection and deferred inference.
  • Greybeard: one boolean per successful source send; no new config, store, cache, scan, or provider round-trip.
  • The first local ClawSweeper finding was fixed: CLI sent-target finality now reaches the shared failure resolver; a progress-then-failure regression proves the visible interruption.

Exact-head mock-gateway verdict (aa16477da7ca660de3d15301c0ce4449ff177756):

{
  "scenario": "message-tool progress, terminal reply, repeated terminal attempt",
  "channelApiDispatches": 2,
  "progressReplies": 1,
  "finalReplies": 1,
  "repeatedTerminalProviderDispatches": 0,
  "repeatedTerminalResult": "already_delivered",
  "retryableErrors": 0
}

This rewrite retains the useful finality work from #119605 by @Glucksberg and the original duplicate-reply investigation from #102179 by @849261680; both are credited in the commit trailers.

Exact-head real-user Telegram proof (aa16477da7ca660de3d15301c0ce4449ff177756):

{
  "scope": "forum topic",
  "visibleReplies": "message_tool",
  "streaming": "off",
  "progressMessages": 1,
  "finalMessages": 1,
  "ordinaryAssistantSummaries": 0,
  "edits": 0,
  "deletes": 0,
  "messageFailuresOrRetries": 0
}

The Claude CLI agent executed both message-tool calls against Telegram. The recorder observed progress first, then the terminal reply; the private assistant summary stayed suppressed.

@Glucksberg
Glucksberg marked this pull request as ready for review August 5, 2026 12:48
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L labels Aug 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ac5a385270

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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 Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 7, 2026, 3:32 AM ET / 07:32 UTC.

ClawSweeper review

What this changes

This PR makes a successful current-source message-tool reply terminal by default, while retaining explicit final: false as a progress update that permits continuation.

Regression provenance

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

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 5 items remain

Keep this PR open as the active candidate fix for a shipped repeated-source-reply regression. The shared runtime change is coherent, but the only real Gateway artifact covers an older head and the required direct Codex-source contract check is unavailable in this review environment.

Priority: P1
Reviewed head: 1ff40da7877ee5ad16e46eab112712f763e3e5cd

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation review is solid, but the current head lacks qualifying real behavior proof.
Proof confidence 🧂 unranked krab (1/6) Needs stronger real behavior proof before merge: The supplied real Gateway artifact is for a6de61a rather than current head 1ff40da, so it does not prove the final current implementation; post a redacted exact-head run and redact private details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The supplied real Gateway artifact is for a6de61a rather than current head 1ff40da, so it does not prove the final current implementation; post a redacted exact-head run and redact private details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Current-main regression path: Current main records qualifying message-tool delivery but returns the existing hook result without a terminal signal, leaving the loop able to request another model turn; this matches the reported cascade mechanism.
Candidate repair boundary: The PR carries producer-owned finality through the terminal guard and subscriber; explicit false remains progress, while omitted or true finality is terminal.
Historical provenance: Merged predecessor #92343 introduced the continuation behavior in commit 4620929; the issue reports the resulting behavior on a released version.
Findings None None.
Security None None.

How this fits together

In message-tool-only channel runs, visible replies are sent through the message tool instead of an automatic assistant final. The embedded runner records delivery finality, uses it to stop a completed source turn, and prevents later duplicate replies from reaching the channel.

flowchart LR
  A[Incoming channel turn] --> B[Embedded agent run]
  B --> C[Message tool send]
  C --> D[Delivery finality evidence]
  D --> E{Progress or terminal reply?}
  E -->|Progress| B
  E -->|Terminal| F[Stop source turn]
  F --> G[Suppress duplicate source replies]
  G --> H[Channel transcript]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The supplied real Gateway artifact is for a6de61a rather than current head 1ff40da, so it does not prove the final current implementation; post a redacted exact-head run and redact private details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The real Gateway proof is for an older head, not the current finality implementation; merge should wait for a redacted exact-head run.
  • Resolve merge risk (P1) - Changing omitted message-tool finality affects visible reply termination across message-tool-only channel surfaces, so the explicit-progress and cross-route variants need exact-head behavior evidence.
  • Resolve merge risk (P1) - The unavailable sibling Codex source prevents an independent dependency-contract verdict for the Codex adapter.
  • Complete next step (P2) - The remaining merge blockers are exact-head real behavior proof and the unavailable direct Codex dependency-contract check, not a mechanical patch repair.
Agent review details

Security

None.

PR surface

Source +295, Tests +611, Other +137. Total +1043 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 19 394 99 +295
Tests 12 739 128 +611
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 156 19 +137
Total 33 1289 246 +1043

Review metrics

Metric Value Why it matters
Operator configuration surface 0 added or changed The patch changes runtime message-delivery semantics without adding a config or default for operators to migrate.

Stored data model

Persistent data-model change detected: serialized state: extensions/qa-lab/src/providers/mock-openai/server.test.ts, serialized state: src/agents/embedded-agent-runner/run/message-tool-terminal.ts, serialized state: src/agents/sessions/agent-session-base.ts, serialized state: src/agents/sessions/sdk.test.ts. Confirm migration or upgrade compatibility proof before merge.

Mantis proof suggestion

A Telegram Desktop trace would directly show the absent duplicate reply on the current head. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify a message-tool-only group run sends one omitted-final terminal source reply with no later model reply, while final=false progress can precede it.

Merge-risk options

Maintainer options:

  1. Refresh exact-head delivery proof (recommended)
    Run the real Gateway scenario on the current head and publish a redacted trace showing one omitted-final source reply and the explicit-progress path.
  2. Pause pending contract review
    Hold this PR if the upstream Codex source contract cannot be inspected in the review environment.

Technical review

Best possible solution:

Retain the producer-owned finality marker and runner-owned terminal guard, then add exact-head Gateway evidence covering omitted-terminal delivery and explicit-false progress before merge.

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

Yes—current main’s terminal hook records delivery without returning a terminal signal, and the linked issue supplies a shipped-version channel trace matching that path.

Is this the best way to solve the issue?

Yes, conditionally—the producer-owned marker and runner-owned guard are a cleaner fix than Codex-only deferred inference, but the current head still needs real behavior proof and direct Codex-contract verification.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Current main can emit repeated visible source replies during message-tool-only channel runs.
  • merge-risk: 🚨 compatibility: Omitted message-tool finality changes from continuation to terminal behavior for existing message-tool-only runs.
  • merge-risk: 🚨 message-delivery: The patch controls whether later source replies are sent or suppressed after a delivered message.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The supplied real Gateway artifact is for a6de61a rather than current head 1ff40da, so it does not prove the final current implementation; post a redacted exact-head run and redact private details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The change affects visible Telegram message-tool replies and can be demonstrated in a short group-chat recording.

Evidence

What I checked:

Likely related people:

  • joshavant: Authored the merged predecessor that established the current message-tool continuation path now being repaired. (role: feature rework author; confidence: high; commits: 462092936a5c; files: src/agents/embedded-agent-runner/run/message-tool-terminal.ts, src/agents/embedded-agent-runner/run/attempt-session.ts)

Rank-up moves

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

  • Post a redacted exact-head Gateway trace covering omitted-final terminal delivery and explicit-false progress.
  • Refresh review once the sibling Codex source contract can be directly inspected.

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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-05T15:20:01.230Z sha 9873bd389a2e0c26bf69049431a7dd1c8cfe03bc :: found issues before merge. :: [P1] Unify omitted-final delivery state
  • reviewed 2026-08-05T16:24:50.894Z sha 9873bd389a2e0c26bf69049431a7dd1c8cfe03bc :: needs real behavior proof before merge. :: [P1] Derive source-reply finality from canonical delivery evidence
  • reviewed 2026-08-05T16:34:48.593Z sha 9873bd389a2e0c26bf69049431a7dd1c8cfe03bc :: needs real behavior proof before merge. :: [P1] Preserve omitted-source terminal delivery
  • reviewed 2026-08-06T04:44:15.452Z sha a6de61a30e993dc6ab0b8dcbebfac815ae6c9952 :: needs real behavior proof before merge. :: [P1] Preserve deferred omitted-final behavior
  • reviewed 2026-08-06T05:49:06.871Z sha a6de61a30e993dc6ab0b8dcbebfac815ae6c9952 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-06T06:38:49.059Z sha a6de61a30e993dc6ab0b8dcbebfac815ae6c9952 :: needs changes before merge. :: [P1] Keep explicit reply targets out of terminal reservation
  • reviewed 2026-08-06T07:32:33.622Z sha 74739cf8b1ec4ec2488ab94ac354d6ae1be87db9 :: needs real behavior proof before merge. :: [P1] Exclude explicit reply targets from terminal reservation
  • reviewed 2026-08-06T07:44:51.055Z sha 74739cf8b1ec4ec2488ab94ac354d6ae1be87db9 :: needs real behavior proof before merge. :: [P1] Reserve and terminate explicit current-source reply actions

@Glucksberg
Glucksberg force-pushed the fix/102179-finality-aware-message-tool branch from ac5a385 to b2b27dc Compare August 5, 2026 13:28
@Glucksberg

Copy link
Copy Markdown
Contributor Author

@openclaw-mantis telegram desktop proof: verify a message_tool_only group run sends progress then exactly one final source reply, without another model-generated reply.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 5, 2026
@Glucksberg

Copy link
Copy Markdown
Contributor Author

After-fix runtime proof on exact head f28b620fc0c587442406c41b4a2fcb9c44ce0cc4:

OpenClaw QA Scenario Suite
Passed: 2
Failed: 0

message-tool-progress-final
progress=QA-MESSAGE-TOOL-PROGRESS
final=QA-MESSAGE-TOOL-FINAL-OK
providerRequests=2
successfulMessageCalls=2

message-tool-stranded-final-retry-failure
diagnostic=1
rawOutbound=0
retryRequests=1

This used an ephemeral real Gateway plus the qa-channel transport and deterministic mock provider. The first scenario proves final=false remains nonterminal, final=true is delivered once, and no third provider continuation occurs. The second proves a missing terminal tool delivery leaves a visible sanitized fallback without leaking private final text.

Reproduction:

OPENCLAW_BUILD_PRIVATE_QA=1 node scripts/run-node.mjs qa suite \
  --provider-mode mock-openai \
  --scenario message-tool-progress-final \
  --scenario message-tool-stranded-final-retry-failure \
  --channel-driver qa-channel \
  --output-dir .artifacts/qa-e2e/pr-119605-message-finality

Canonical exact-head PR CI is also green (pending=0).

@Glucksberg

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot removed the mantis: telegram-visible-proof Mantis should capture Telegram visible proof. label Aug 5, 2026
@Glucksberg

Copy link
Copy Markdown
Contributor Author

Addressed the latest compatibility finding on exact head f47d11515d244430efd491c9f16f63c15521cd80.

  • message_tool_only: only explicit final: true is terminal; omitted final remains non-terminal, so an ordinary message send can still be followed by another tool/model turn.
  • automatic: confirmed current-source replies retain the existing terminal-delivery/dedupe behavior even though that tool surface does not expose the Codex-only final control.
  • Regression proof: terminal hook 27/27, subscriber continuation/suppression 21/21, full subscriber tool handler 146/146, message tool 229/229, delivery evidence 19/19, and payload error handling 73/73.
  • Real Gateway + qa-channel scenarios: 2/2 passed (progress then explicit final; stranded-final retry failure diagnostic).
  • Production and agent-test TypeScript checks, targeted Oxlint/Oxfmt, and git diff --check passed.
  • Final autoreview: patch correct (0.97), no accepted/actionable findings.
  • Exact-head CI run 31016380963: green; the earlier cancelled automation jobs were superseded, with no current failing checks.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@Glucksberg

Copy link
Copy Markdown
Contributor Author

Final exact-head proof for 9873bd389a2e0c26bf69049431a7dd1c8cfe03bc:

  • Fixed the QA gap from the prior review: the scenario now inspects the complete post-start outbound transcript for the source conversation, without marker filtering, and requires exactly the ordered progress and final messages. Any third automatic reply fails.
  • Exact-head real Gateway + qa-channel verdict: 2 passed, 0 failed, 0 skipped; outboundMessages=2, providerRequests=2, successfulMessageCalls=2; retry-failure proof reports diagnostic=1, rawOutbound=0, retryRequests=1.
  • The redacted exact-head verdict JSON is embedded under Exact-head QA verdict in the PR body, including head SHA, timestamps, runner, provider, channel driver, counts, and per-scenario details.
  • The PR body also records direct inspection of the Codex app-server finality contract and the ordinary message-tool omission contract.
  • QA provider tests 263/263 and scenario catalog tests 57/57 passed; QA repair autoreview was clean (0.99).
  • Exact-head CI run 31018641505: GREEN, pending=0, current failures=0.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

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

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 5, 2026
Glucksberg added a commit to Glucksberg/OpenClaw that referenced this pull request Aug 7, 2026
@obviyus
obviyus force-pushed the fix/102179-finality-aware-message-tool branch from 1ff40da to 3a5d537 Compare August 10, 2026 12:05
@obviyus obviyus changed the title fix: stop duplicate source replies after final message sends fix(agent): allow message-tool progress before the final reply Aug 10, 2026
@obviyus
obviyus force-pushed the fix/102179-finality-aware-message-tool branch from 3a5d537 to 98e971f Compare August 10, 2026 12:13
@obviyus
obviyus force-pushed the fix/102179-finality-aware-message-tool branch from 98e971f to aa16477 Compare August 10, 2026 12:15
@obviyus
obviyus merged commit cd7b7f6 into openclaw:main Aug 10, 2026
123 of 131 checks passed
@Glucksberg
Glucksberg deleted the fix/102179-finality-aware-message-tool branch August 10, 2026 14:30
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]>
obviyus added a commit that referenced this pull request Oct 18, 2026
…176141)

Related: #170653, #176092

## What Problem This Solves

Fixes: a cron job stops right after it sends a message to its own delivery target, so its next steps never run.

## User Impact

User impact: a cron job can send to its configured chat with the `message` tool and then continue, for example to update a state file or ledger. Before this fix the turn ended about 0.3 s after the send. A job that recorded "reserved" before sending never recorded "sent", and the next run refused to post because it could not prove delivery. Chat replies are unchanged.

## Why This Change Was Made

Cron runs use the job's delivery target as the turn's current source. Since #170653, a confirmed send to that source with `final` omitted counts as the final source reply:
- Codex interrupts the turn (`turn.dynamic_tool_terminal_release`, then `turn/interrupt`).
- The embedded runner returns `terminate: true`.

A cron target is a configured destination, not a conversation the turn answers, so the send should not end the turn.

What changed:
- The cron source-delivery plan now owns this decision: `messageTool.finalByDefault: false`, passed to runs as `messageToolFinalByDefault`.
- One resolver, `resolveMessageToolSourceReplyFinal(args, finalByDefault)`, applies it at every place that decides finality: Codex dynamic tools, the embedded terminal hook and subscriber, and CLI evidence.
- An explicit `final` still wins.
- `resolveMessageToolSourceReplyFinal` is now exported from `plugin-sdk/agent-harness-runtime`, next to its sibling `isDeliveredMessageToolOnlySourceReplyResult`, so Codex uses the same owner. The public export budgets go up by one (callable 2206 to 2207, total 3808 to 3809), each with a recorded reason.
- Chat turns keep the default (omitted `final` ends the turn).
- Delivery facts do not change. A send still counts as reaching the cron target, so `announce` still skips its fallback and no duplicate posts.
- The model's turn guidance (Codex `openclaw_source_delivery` context and embedded runtime instructions) now states the rule when the default is off. Chat guidance text is byte-identical.

This change is compatible with #176093. That PR keys on an explicit `final: false`, and this change does not touch it.

Comparison: hermes-agent never ends a turn on a send. Its cron same-target guard returns a skipped tool result and lets the turn continue (NousResearch/hermes-agent#1357).

### Decision

Cron turns intentionally stop following the "omitted `final` ends the turn" default from #119605/#170653. That default fits a chat, where the send answers the inbound message. A cron target is a configured destination, and the job decides when it is done.
- **Tradeoff accepted:** a cron send with `final` omitted costs one more model call, the call #170653 removed. Losing a job's post-send steps without notice costs more.
- **Users see no duplicates:** `announce` still skips its fallback after a send, and `none` keeps the final text private.
- **Unchanged:** chat turns and an explicit `final`.

## Evidence

**Live failure (Codex runtime, stock main):**
- A daily cron photo job sent its photo (`ok: true`).
- The trajectory then shows `tool.result`, then `turn.dynamic_tool_terminal_release` 4 ms later, then `model.completed` with no assistant text, then `session.ended`.
- The job's next step, marking its ledger entry `sent`, never ran. The next run blocked on the unconfirmed entry.

**End-to-end, QA Lab** (real gateway, cron scheduler, qa-channel, mock-openai; the Codex cell runs the real `codex app-server`). New scenario `cron-send-then-continue` covers delivery modes `none` and `announce`. In each, the model sends to the delivery target without `final`, then writes a marker file, then finishes.

| | embedded | codex |
|---|---|---|
| main `adb12365084` (no fix) | fail: one request, turn ended after send | fail: one request, turn ended after send |
| this PR | pass: send, then `write`, one channel message per mode | pass: send, then `bash`, one channel message per mode |

Each runtime cell's scenario details now include the request trace for each delivery mode (`message -> next tool -> final`, plus what qa-channel received). This run is at the PR head:

```text
codex     none: message -> exec_command -> final; channel=["QA-CRON-SEND-CONTINUE-SENT"] | announce: message -> exec_command -> final; channel=["QA-CRON-SEND-CONTINUE-SENT"]
embedded  none: message -> write -> final;        channel=["QA-CRON-SEND-CONTINUE-SENT"] | announce: message -> write -> final;        channel=["QA-CRON-SEND-CONTINUE-SENT"]
```

On main, both cells stop after the first request: `requests=[{"tool":"message",...}]`, and no further tool call follows.

**Regression scenarios on both runtimes:** 10 message-tool, cron, sub-agent and A2A scenarios, run under `--runtime-pair openclaw,codex`.
- Pass, with no change in the chat paths: `group-visible-reply-tool`, `message-tool-stranded-final-reply`, `group-message-tool-unavailable-fallback`, `cron-send-then-continue`. `runtime-tool-message-tool` skipped.
- Fail: `cron-failed-tool-terminal-finalization` (Codex cell), `a2a-message-tool-mirror-dedupe`, `message-delivery-decision-inspection`, `subagent-forked-context`, `yield-rejection-no-warning` (Codex cell). Each fails in the same runtime cells on unpatched main `adb12365084` on this host, so these failures already exist on main and are not caused by this change.

**Unit:**
- New matrices in the Codex dynamic-tool and embedded terminal-hook suites, plus a cron run assertion. On main, exactly the bug cells fail (7 failed); with this PR all pass.
- 17 affected files, 572 tests, all passing. This includes the existing duplicate-reply protection suites (`message-tool-terminal*.test.ts`, `dynamic-tools.source-reply`, `run-attempt-lifecycle-controller`, `event-projector.source-finish`, `message-tool-execution`) and `agent-tools.prefix-stability`, all unchanged.

**Lint:** `oxlint --type-aware` reports `max-lines` on `run-attempt-dispatch.ts` and three unresolved-type errors in `dynamic-tools.ts`. All four already appear on main with the same local setup.

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

Related: openclaw#170653, openclaw#176092

## What Problem This Solves

Fixes: a cron job stops right after it sends a message to its own delivery target, so its next steps never run.

## User Impact

User impact: a cron job can send to its configured chat with the `message` tool and then continue, for example to update a state file or ledger. Before this fix the turn ended about 0.3 s after the send. A job that recorded "reserved" before sending never recorded "sent", and the next run refused to post because it could not prove delivery. Chat replies are unchanged.

## Why This Change Was Made

Cron runs use the job's delivery target as the turn's current source. Since openclaw#170653, a confirmed send to that source with `final` omitted counts as the final source reply:
- Codex interrupts the turn (`turn.dynamic_tool_terminal_release`, then `turn/interrupt`).
- The embedded runner returns `terminate: true`.

A cron target is a configured destination, not a conversation the turn answers, so the send should not end the turn.

What changed:
- The cron source-delivery plan now owns this decision: `messageTool.finalByDefault: false`, passed to runs as `messageToolFinalByDefault`.
- One resolver, `resolveMessageToolSourceReplyFinal(args, finalByDefault)`, applies it at every place that decides finality: Codex dynamic tools, the embedded terminal hook and subscriber, and CLI evidence.
- An explicit `final` still wins.
- `resolveMessageToolSourceReplyFinal` is now exported from `plugin-sdk/agent-harness-runtime`, next to its sibling `isDeliveredMessageToolOnlySourceReplyResult`, so Codex uses the same owner. The public export budgets go up by one (callable 2206 to 2207, total 3808 to 3809), each with a recorded reason.
- Chat turns keep the default (omitted `final` ends the turn).
- Delivery facts do not change. A send still counts as reaching the cron target, so `announce` still skips its fallback and no duplicate posts.
- The model's turn guidance (Codex `openclaw_source_delivery` context and embedded runtime instructions) now states the rule when the default is off. Chat guidance text is byte-identical.

This change is compatible with openclaw#176093. That PR keys on an explicit `final: false`, and this change does not touch it.

Comparison: hermes-agent never ends a turn on a send. Its cron same-target guard returns a skipped tool result and lets the turn continue (NousResearch/hermes-agent#1357).

### Decision

Cron turns intentionally stop following the "omitted `final` ends the turn" default from openclaw#119605/openclaw#170653. That default fits a chat, where the send answers the inbound message. A cron target is a configured destination, and the job decides when it is done.
- **Tradeoff accepted:** a cron send with `final` omitted costs one more model call, the call openclaw#170653 removed. Losing a job's post-send steps without notice costs more.
- **Users see no duplicates:** `announce` still skips its fallback after a send, and `none` keeps the final text private.
- **Unchanged:** chat turns and an explicit `final`.

## Evidence

**Live failure (Codex runtime, stock main):**
- A daily cron photo job sent its photo (`ok: true`).
- The trajectory then shows `tool.result`, then `turn.dynamic_tool_terminal_release` 4 ms later, then `model.completed` with no assistant text, then `session.ended`.
- The job's next step, marking its ledger entry `sent`, never ran. The next run blocked on the unconfirmed entry.

**End-to-end, QA Lab** (real gateway, cron scheduler, qa-channel, mock-openai; the Codex cell runs the real `codex app-server`). New scenario `cron-send-then-continue` covers delivery modes `none` and `announce`. In each, the model sends to the delivery target without `final`, then writes a marker file, then finishes.

| | embedded | codex |
|---|---|---|
| main `6d14590f417` (no fix) | fail: one request, turn ended after send | fail: one request, turn ended after send |
| this PR | pass: send, then `write`, one channel message per mode | pass: send, then `bash`, one channel message per mode |

Each runtime cell's scenario details now include the request trace for each delivery mode (`message -> next tool -> final`, plus what qa-channel received). This run is at the PR head:

```text
codex     none: message -> exec_command -> final; channel=["QA-CRON-SEND-CONTINUE-SENT"] | announce: message -> exec_command -> final; channel=["QA-CRON-SEND-CONTINUE-SENT"]
embedded  none: message -> write -> final;        channel=["QA-CRON-SEND-CONTINUE-SENT"] | announce: message -> write -> final;        channel=["QA-CRON-SEND-CONTINUE-SENT"]
```

On main, both cells stop after the first request: `requests=[{"tool":"message",...}]`, and no further tool call follows.

**Regression scenarios on both runtimes:** 10 message-tool, cron, sub-agent and A2A scenarios, run under `--runtime-pair openclaw,codex`.
- Pass, with no change in the chat paths: `group-visible-reply-tool`, `message-tool-stranded-final-reply`, `group-message-tool-unavailable-fallback`, `cron-send-then-continue`. `runtime-tool-message-tool` skipped.
- Fail: `cron-failed-tool-terminal-finalization` (Codex cell), `a2a-message-tool-mirror-dedupe`, `message-delivery-decision-inspection`, `subagent-forked-context`, `yield-rejection-no-warning` (Codex cell). Each fails in the same runtime cells on unpatched main `6d14590f417` on this host, so these failures already exist on main and are not caused by this change.

**Unit:**
- New matrices in the Codex dynamic-tool and embedded terminal-hook suites, plus a cron run assertion. On main, exactly the bug cells fail (7 failed); with this PR all pass.
- 17 affected files, 572 tests, all passing. This includes the existing duplicate-reply protection suites (`message-tool-terminal*.test.ts`, `dynamic-tools.source-reply`, `run-attempt-lifecycle-controller`, `event-projector.source-finish`, `message-tool-execution`) and `agent-tools.prefix-stability`, all unchanged.

**Lint:** `oxlint --type-aware` reports `max-lines` on `run-attempt-dispatch.ts` and three unresolved-type errors in `dynamic-tools.ts`. All four already appear on main with the same local setup.

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 gateway Gateway runtime 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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants