Repository navigation
fix(cron): a session cron's reply reaches the model once - #201838
Conversation
…l copy A session-target or main-session cron turn already holds its reply in model context. The settle step's commit into the same conversation is now display-only, so the row is never placed into the next request. Co-authored-by: obviyus <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesMarks a session cron’s displayed result as excluded from model context because its original reply is already there. Example: A session-target cron replies SCHEDULED_REPLY_42, followed by two user turns.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a concrete duplicate-context bug still present on current main; no actionable correctness or security findings remain. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCron settlement sends prepared replies through the canonical background-result writer, which persists conversation rows consumed separately by chat display and model-context placement. flowchart TD
A[Cron turn] --> B[Original model reply]
A --> C[Session event settlement]
C --> D[Background result writer]
D --> E[Display only result row]
E --> F[Chat history]
B --> G[Next model request]
Technical reviewBest possible solution: Keep the existing result writer and explicitly exclude only a producing session turn’s display copy from model placement. Do we have a high-confidence way to reproduce the issue? The current-main settlement and placement paths establish the duplicate-copy mechanism; the author supplies matching live comparisons and reports base-red/head-green Gateway regressions, which were not rerun during this read-only review. Is this the best way to solve the issue? The flag expresses a fact known by settlement and unavailable to the generic writer, preserving foreign-result placement without new state, heuristic detection, or removal of persistent display output. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 08b4ac92c197. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +15, Tests +235. Total +250 across 5 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 19, 2026, 8:37 AM ET / 13:37 UTC. |
…active turn Co-authored-by: obviyus <[email protected]>
… conversation Co-authored-by: obviyus <[email protected]>
Co-authored-by: obviyus <[email protected]>
Co-authored-by: obviyus <[email protected]>
Co-authored-by: obviyus <[email protected]>
|
Maintainer override: the remaining red checks on head bc46e64 also fail on this PR's merge base, so this PR did not cause them.
The one red this PR did cause, |
|
Landed in b4ddf4b with the maintainer override above for two reds that also fail on the merge base. A session or main-session cron's reply reached the model twice: once as the delivered reply and once as a persisted result. The result is now kept for display only, so the model sees the reply once. Exact-head E2E (Claude): session-target, main-session and persistent-webhook crons went from 2 copies to 1 in the model's request, cache reads stayed level, and the next user turn answered correctly instead of referring back to the duplicate. |
Co-authored-by: obviyus <[email protected]>
The cron reply merge (#201838) and the Chat Completions silent-turn merge (#201843) are fixed on main, and the skills-after-reload rebuild no longer occurs on Anthropic seeds 1 and 6. Co-authored-by: obviyus <[email protected]>
…low and a concurrent chat on five transports (#201723) ## What was wrong The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing. **Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in #201838. This journey would have caught it. ## Fix - Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock. - Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off. - Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one. - Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model. - The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s. ## Numbers | | main (before this PR) | this PR | |---|---|---| | Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey | | Transports | 3 | 5 | | Stability journey | n/a | 5/5 | | Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 | | Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 | <details><summary>Breaks still on main (accepted entries)</summary> | Where | Change | Owner | |---|---|---| | Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | #199530 | | Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (#201654 closed) | | Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | #201710 / documented exception of the opt-out surface | Removed because their owners landed: the cron reply twice (#201838), the Chat Completions silent-turn merge (#201843), the cron-first `message` growth (#201710), and the skills rebuild after `config.patch` (issue #202150, which no longer reproduces on Anthropic seeds 1 and 6). Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal. </details> <details><summary>Steer signal</summary> - The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event. - On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held. - Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn. - A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path. </details> <details><summary>Rebuild evidence checks</summary> - Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary. - Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive. - Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too. </details> <details><summary>Cron-first red on base</summary> On the parent of #201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes. </details> <details><summary>Harness fixes</summary> - Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`. - After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay. - Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey. - The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation. </details> <details><summary>Gates</summary> - `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5. - `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass. - Local review on this head: patch is correct, no findings. </details> Co-authored-by: Ayaan Zaidi <[email protected]>
…1838) ## Problem A session-target cron (`sessionTarget: "session:<key>"`) or a main-session cron runs its turn in the target conversation. That turn's own assistant reply stays in model context (it is hidden from the chat view because cron execution prose is audit-only). When the turn settles, `settleSessionEventTurn` publishes the settled reply into the same conversation through `commitCronConversationResult`, so the chat view can show it. The cron turn still holds the session at that moment, so `commitBackgroundResultToSession` writes the row as a pending background result (`excludeFromContext` + `openclawModelPlacement: "pending"`). The next request boundary then places it into model context as a normal assistant message. Result: the model sees the cron reply twice. In a real run the model apologised for "answering twice". Isolated crons are not affected (0 copies in the chat). ## Solution The settle step's commit is always into the conversation that the cron turn ran in, so the row is for display only. `settleSessionEventTurn` now passes `displayOnly: true`. The writer then stores `excludeFromContext: true` with no pending placement, so the row is shown in the chat and never placed into model context. ### Why a parameter (and not derivation or removal) The brief asked for subtraction first. I checked both options: 1. **Derive at the write site.** `commitBackgroundResultToSession` only knows "this session has active work". It cannot tell whether that work is the producer (this cron turn) or a foreign turn (a user typing while an isolated cron result arrives from another session, a subagent completion). Both callers also pass the same `{ kind: "cron", jobId, runId }` provenance. The run registry entry that names the job (`cronRunsByJobId`) is consumed before the commit. Exact derivation needs new state; a heuristic (active cron turn in this session) would drop a foreign result from model context when two crons overlap. 2. **Drop the commit.** The cron turn's own reply is `display: false`, so this commit is the only persistent display path. Removing it removes the reply from the chat after a reload. Making the raw reply visible instead changes what the chat shows (no_change, silent replies, directive text, media). So the only callers that know the fact ("my own turn already holds this text") state it. The flag is threaded through `commitCronConversationResult` → `commitBackgroundPayloadsToSession` → `commitBackgroundResultToSession`. Two callers set it: - `settleSessionEventTurn` (`src/auto-reply/reply/session-event-automation.ts`): session-target and main-session cron turns. - `commitExecutionResult` (`src/cron/isolated-agent/delivery-dispatch.ts:112-136`, callers `:196` and `:421`): a persistent execution committing into its own conversation. ### Is the isolated runner reachable with a `session:` or `main` job? - **From the cron timer: no.** - `script` payloads return early (`src/cron/service/timer-execution.ts:362`). - `runsCronMainSessionRoute` (`src/cron/service/timer-session-route.ts:20-30`) sends every non-plugin-command job with `sessionTarget: "main"`, or with `session:` and `agentTurn`, to `executeMainSessionCronJob` (`timer-execution.ts:379`). - Validation (`src/cron/service/jobs-validation.ts:106-127`) allows only `agentTurn` or `command` on `session:` targets, and only `systemEvent`, `agentTurn` or `script` on `main`. - In `executeDetachedCronJob`, `command` payloads go to the command runner (`timer-execution.ts:479`), and anything else that is not `agentTurn` is rejected (`:526`). - What remains for `runIsolatedAgentJob` (`:541`) with a `session:` target is a plugin-command job. `runPluginCommandScheduledTurn` claims those, because `readPluginCommandScheduledJob` either returns the schedule or throws (`src/gateway/plugin-command-scheduled-run.ts:70-92`). So they never reach `runCronIsolatedAgentTurn` (`src/gateway/server-cron-agent-run.ts:39-60`). - **From persistent webhooks: yes.** `src/gateway/server/hooks.ts:315` builds `sessionTarget: "session:<key>"` for `sessionMode: "persistent"` and calls `runCronIsolatedAgentTurn` directly (`:548`). That path's `commitExecutionResult` committed into the execution's own conversation, so it had the same double copy. It now passes `displayOnly: true` too, and the persistent-session delivery tests assert the flag. This part is proven by reading the code and by those unit tests; no real-Gateway run covers webhooks. ### Behavior notes - **Host-authored payloads in the same commit become display-only too.** For example, the `isError` payloads kept on `no_change`. They no longer reach the model through the placed row. This is intended: the model already saw its own turn, and the host text is for the reader. - **Retries that straddle the deploy.** A retry over an old pending row with the same idempotency key stays pending, because the retry spreads `priorMessage` (`src/sessions/background-session-result.ts:164-169`). Only runs that straddle the deploy are affected. - **Reset between turn end and commit.** The row lands display-only in the new transcript. This is defensible: the reset already dropped the turn that produced it. - **CLI runtime.** By reading the code, CLI runtime sessions take the same settle path, and their history reader also skips `excludeFromContext` rows, so the fix holds. This is not tested end to end. ### Unchanged - Isolated crons, source-conversation commits (an isolated cron created from a chat), run-outcome notices and subagent completions keep their placement. - Readers: placement readers match only `openclawModelPlacement: "pending"`; the Control UI automation boundary reads `openclawAutomation`, which is kept. Existing pending rows from older versions are still placed once (accepted, transient). ## Evidence ### Tests (red on merge base `8c6946658cc8`, green on head) `src/cron/session-cron-result-single-copy.gateway.integration.test.ts`: a real Gateway, cron service and session store; only the provider endpoint is synthetic. For each transport (OpenAI Responses, Anthropic Messages): user turn, cron run, two follow-ups, then count copies of the cron reply in the last request and display rows in `chat.history`. | Test | Responses base | Responses head | Anthropic base | Anthropic head | |---|---|---|---|---| | session-target cron: 1 model copy, 1 display row | red (2 copies) | green | red (2 copies) | green | | main systemEvent cron: 1 model copy, 1 display row | red (2 copies) | green | red (2 copies) | green | | isolated cron: unrelated chat has 0 copies, 0 rows | green | green | green | green | | isolated cron from a chat: keeps placement (1 copy, 1 row) | green | green | green | green | The last two are guards for unchanged behavior, so they pass on both sides. Unit cases in `src/sessions/background-session-result.test.ts`: while a turn holds the session, `displayOnly` writes `excludeFromContext` with no placement, and a commit without the flag stays pending. Consumer suites (background result, destination/current-session completion, double announce, cron notifications, session event handoff and automation result, CLI history boundary): 248 tests pass. `tsgo:core` passes. `check:test-types` reports only existing errors in `test/scripts/release-*` (unrelated). ### Real Gateway, main vs head Isolated scratch Gateways from source (`--profile` scratch state, `env -i`), real providers, an unrelated chat running 12 turns concurrently. Scenarios: session-target cron + 2 user turns, main systemEvent cron + 2 turns, isolated cron, isolated cron created from the chat. "copies" = assistant copies of the cron reply in the last request of the conversation. Cache = cached input / input tokens per request after the cron run (Anthropic: cache read / cache write). | Route | Scenario | Copies main | Copies head | Cache per request after cron, main → head (last 2 requests) | Display rows main / head | |---|---|---|---|---|---| | OpenAI Responses | session-target cron + 2 turns | 2 | **1** | 33665/35391, 35388/35961 → 33391/35109, 35106/35679 | 1 / 1 | | OpenAI Responses | main systemEvent cron + 2 turns | 2 | **1** | 31610/32256, 32245/32900 → 31338/31976, 31973/32611 | 1 / 1 | | OpenAI Responses | isolated cron (other chat) | 0 | 0 | 30651/31225 → 30378/30952 | 0 / 0 | | OpenAI Responses | isolated cron from this chat | 1 | 1 | 30659/31233 → 30386/30960 | 1 / 1 | | Claude (Anthropic Messages) | session-target cron + 2 turns | 2 | **1** | 62675/2754, 65429/883 → 62542/2746, 65288/883 | 1 / 1 | | Claude (Anthropic Messages) | main systemEvent cron + 2 turns | 2 | **1** | 58889/986, 59875/990 → 58758/986, 59744/986 | 1 / 1 | | Claude (Anthropic Messages) | isolated cron (other chat) | 0 | 0 | 57364/885 → 57233/885 | 0 / 0 | | Claude (Anthropic Messages) | isolated cron from this chat | 1 | 1 | 57365/884 → 57234/884 | 1 / 1 | | OpenAI Chat Completions | session-target cron + 2 turns | 2 | **1** | 33086/34812, 34809/35382 → 32813/34531, 34528/35101 | 1 / 1 | | OpenAI Chat Completions | main systemEvent cron + 2 turns | 2 | **1** | 31028/31666, 31663/32304 → 30760/31398, 31395/32033 | 1 / 1 | | OpenAI Chat Completions | isolated cron (other chat) | 0 | 0 | 30073/30647 → 29800/30374 | 0 / 0 | | OpenAI Chat Completions | isolated cron from this chat | 1 | 1 | 30076/30650 → 29803/30377 | 1 / 1 | The concurrent chat finished all 12 turns `ok` in every run. Cache reads stay at the same level on head (no new prefix breaks); the head prompt is smaller by the removed copy. Chat Completions and Anthropic merge adjacent assistant messages, so copies are counted as reply lines, not messages. ### Real Gateway, persistent webhook (main vs head) `POST /hooks/agent` with `sessionMode: "persistent"`, `sessionKey: <chat>`, `deliver: false` (the `hooks.ts:315` → `:548` → `runCronIsolatedAgentTurn` → `commitExecutionResult` path), then two user turns in that chat, with an unrelated chat running 12 turns concurrently. Same isolated scratch setup as above. | Route | Copies main | Copies head | Cache, last request main → head | Display rows main / head | |---|---|---|---|---| | OpenAI Responses | 2 | **1** | 31240/31852 → 30983/31556 | 2 / 2 | | OpenAI Chat Completions | 2 | **1** | 30659/31235 → 30413/30986 | 2 / 2 | The webhook gives 2 display rows on both sides. The webhook turn's own reply is visible in the chat (its provenance is not cron execution, so it is not hidden), and the committed result row is shown as well. This duplicate display is pre-existing and not changed by this PR; it is a follow-up candidate (the persistent-webhook commit may be redundant for display too). The first main run on Chat Completions was discarded because the model chose a silent reply; the rerun is shown. ## E2E (exact head `bc46e649be75` vs merge base `8c6946658cc8`, 2026-11-20) Isolated scratch Gateways from source (`ocx src`, `--profile` scratch state, `env -i`, random ports), real Claude route (`claude-sonnet-5-5`, Anthropic Messages) behind a logging proxy. Each scenario: user turn, cron (or webhook) comes due, two user turns. An unrelated chat ran 12 turns concurrently in every run. Cache = provider `cache_read_input_tokens` / `cache_creation_input_tokens` per request after the cron run. | Scenario | Copies in model context, base → head | Cache after cron, base → head | Display rows (UI), base / head | |---|---|---|---| | session-target cron + 2 turns | 2 → **1** | 62672/2754, 65426/914 → 62536/2746, 65282/883 | 1 / 1 | | main systemEvent cron + 2 turns | 2 → **1** | 58880/986, 59866/990 → 58748/986, 59734/986 | 1 / 1 | | isolated cron (other chat) | 0 → 0 | 57358/885 → 57227/885 | 0 / 0 | | isolated cron created from this chat | 1 → 1 | 57359/884 → 57228/884 | 1 / 1 | | persistent webhook into this chat (`c1b1db1` path) | 2 → **1** | 56479/1821, 58300/888 → 56348/1810, 58158/884 | 2 / 2 (pre-existing, see above) | - Cache reads stay at the same level on head (no new prefix break); head requests are smaller by the removed copy. - Side effects: the concurrent chat finished 12/12 turns `ok` on both sides; every scenario turn returned `ok`; isolated and creator-chat crons unchanged. - OpenAI Responses (`gpt-6.2-astra`) was also run, but the provider intermittently rejected identical requests with `400 invalid_json_schema` (`uniqueItems` in a tool schema) on both sides, so only the main-session scenario completed comparably there: 2 copies on base, 1 on head. ### UI The Control UI chat for the session-target cron shows the cron reply (`TICK`) once on both sides. On base, the model saw it twice and answered the next turn with "I replied \"TICK\" to the last message, but you asked for \"OK two\""; on head it answers `OK two`. Base:  Head:  ### CI - `check-lint-core-5`: fixed in `bc46e649be75` (`no-base-to-string`, `await-thenable` in the new integration test). - `checks-node-changed-1` (`src/cron/cron-delivery-outcomes.e2e.test.ts` "applies threshold and cooldown once…") and `checks-node-changed-7` (`test/e2e/qa-lab/runtime/system-turn-automation-read-boundaries.e2e.test.ts` "serves a non-admin automation notice…"): not caused by this PR. Both fail identically on the merge base `8c6946658cc8` (same assertion, same received value) and on head; this PR does not touch failure alerts or automation read boundaries. ## Measurement plan 24 h after deploy on a host: count placed automation-result rows that duplicate the immediately preceding model-context assistant reply in the same session. Expected: 0 (baseline on one production host: 33 of 102 placed rows in 7 days). Co-authored-by: Ayaan Zaidi <[email protected]>
…low and a concurrent chat on five transports (openclaw#201723) ## What was wrong The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing. **Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in openclaw#201838. This journey would have caught it. ## Fix - Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock. - Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off. - Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one. - Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model. - The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s. ## Numbers | | main (before this PR) | this PR | |---|---|---| | Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey | | Transports | 3 | 5 | | Stability journey | n/a | 5/5 | | Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 | | Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 | <details><summary>Breaks still on main (accepted entries)</summary> | Where | Change | Owner | |---|---|---| | Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | openclaw#199530 | | Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (openclaw#201654 closed) | | Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | openclaw#201710 / documented exception of the opt-out surface | Removed because their owners landed: the cron reply twice (openclaw#201838), the Chat Completions silent-turn merge (openclaw#201843), the cron-first `message` growth (openclaw#201710), and the skills rebuild after `config.patch` (issue openclaw#202150, which no longer reproduces on Anthropic seeds 1 and 6). Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal. </details> <details><summary>Steer signal</summary> - The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event. - On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held. - Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn. - A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path. </details> <details><summary>Rebuild evidence checks</summary> - Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary. - Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive. - Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too. </details> <details><summary>Cron-first red on base</summary> On the parent of openclaw#201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes. </details> <details><summary>Harness fixes</summary> - Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`. - After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay. - Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey. - The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation. </details> <details><summary>Gates</summary> - `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5. - `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass. - Local review on this head: patch is correct, no findings. </details> Co-authored-by: Ayaan Zaidi <[email protected]>
## Problem
A session-target cron (`sessionTarget: "session:<key>"`) or a main-session cron runs its turn in the target conversation. That turn's own assistant reply stays in model context (it is hidden from the chat view because cron execution prose is audit-only).
When the turn settles, `settleSessionEventTurn` publishes the settled reply into the same conversation through `commitCronConversationResult`, so the chat view can show it. The cron turn still holds the session at that moment, so `commitBackgroundResultToSession` writes the row as a pending background result (`excludeFromContext` + `openclawModelPlacement: "pending"`). The next request boundary then places it into model context as a normal assistant message.
Result: the model sees the cron reply twice. In a real run the model apologised for "answering twice". Isolated crons are not affected (0 copies in the chat).
## Solution
The settle step's commit is always into the conversation that the cron turn ran in, so the row is for display only. `settleSessionEventTurn` now passes `displayOnly: true`. The writer then stores `excludeFromContext: true` with no pending placement, so the row is shown in the chat and never placed into model context.
### Why a parameter (and not derivation or removal)
The brief asked for subtraction first. I checked both options:
1. **Derive at the write site.** `commitBackgroundResultToSession` only knows "this session has active work". It cannot tell whether that work is the producer (this cron turn) or a foreign turn (a user typing while an isolated cron result arrives from another session, a subagent completion). Both callers also pass the same `{ kind: "cron", jobId, runId }` provenance. The run registry entry that names the job (`cronRunsByJobId`) is consumed before the commit. Exact derivation needs new state; a heuristic (active cron turn in this session) would drop a foreign result from model context when two crons overlap.
2. **Drop the commit.** The cron turn's own reply is `display: false`, so this commit is the only persistent display path. Removing it removes the reply from the chat after a reload. Making the raw reply visible instead changes what the chat shows (no_change, silent replies, directive text, media).
So the only callers that know the fact ("my own turn already holds this text") state it. The flag is threaded through `commitCronConversationResult` → `commitBackgroundPayloadsToSession` → `commitBackgroundResultToSession`. Two callers set it:
- `settleSessionEventTurn` (`src/auto-reply/reply/session-event-automation.ts`): session-target and main-session cron turns.
- `commitExecutionResult` (`src/cron/isolated-agent/delivery-dispatch.ts:112-136`, callers `:196` and `:421`): a persistent execution committing into its own conversation.
### Is the isolated runner reachable with a `session:` or `main` job?
- **From the cron timer: no.**
- `script` payloads return early (`src/cron/service/timer-execution.ts:362`).
- `runsCronMainSessionRoute` (`src/cron/service/timer-session-route.ts:20-30`) sends every non-plugin-command job with `sessionTarget: "main"`, or with `session:` and `agentTurn`, to `executeMainSessionCronJob` (`timer-execution.ts:379`).
- Validation (`src/cron/service/jobs-validation.ts:106-127`) allows only `agentTurn` or `command` on `session:` targets, and only `systemEvent`, `agentTurn` or `script` on `main`.
- In `executeDetachedCronJob`, `command` payloads go to the command runner (`timer-execution.ts:479`), and anything else that is not `agentTurn` is rejected (`:526`).
- What remains for `runIsolatedAgentJob` (`:541`) with a `session:` target is a plugin-command job. `runPluginCommandScheduledTurn` claims those, because `readPluginCommandScheduledJob` either returns the schedule or throws (`src/gateway/plugin-command-scheduled-run.ts:70-92`). So they never reach `runCronIsolatedAgentTurn` (`src/gateway/server-cron-agent-run.ts:39-60`).
- **From persistent webhooks: yes.** `src/gateway/server/hooks.ts:315` builds `sessionTarget: "session:<key>"` for `sessionMode: "persistent"` and calls `runCronIsolatedAgentTurn` directly (`:548`). That path's `commitExecutionResult` committed into the execution's own conversation, so it had the same double copy. It now passes `displayOnly: true` too, and the persistent-session delivery tests assert the flag. This part is proven by reading the code and by those unit tests; no real-Gateway run covers webhooks.
### Behavior notes
- **Host-authored payloads in the same commit become display-only too.** For example, the `isError` payloads kept on `no_change`. They no longer reach the model through the placed row. This is intended: the model already saw its own turn, and the host text is for the reader.
- **Retries that straddle the deploy.** A retry over an old pending row with the same idempotency key stays pending, because the retry spreads `priorMessage` (`src/sessions/background-session-result.ts:164-169`). Only runs that straddle the deploy are affected.
- **Reset between turn end and commit.** The row lands display-only in the new transcript. This is defensible: the reset already dropped the turn that produced it.
- **CLI runtime.** By reading the code, CLI runtime sessions take the same settle path, and their history reader also skips `excludeFromContext` rows, so the fix holds. This is not tested end to end.
### Unchanged
- Isolated crons, source-conversation commits (an isolated cron created from a chat), run-outcome notices and subagent completions keep their placement.
- Readers: placement readers match only `openclawModelPlacement: "pending"`; the Control UI automation boundary reads `openclawAutomation`, which is kept. Existing pending rows from older versions are still placed once (accepted, transient).
## Evidence
### Tests (red on merge base `dbc1aa04e88f`, green on head)
`src/cron/session-cron-result-single-copy.gateway.integration.test.ts`: a real Gateway, cron service and session store; only the provider endpoint is synthetic. For each transport (OpenAI Responses, Anthropic Messages): user turn, cron run, two follow-ups, then count copies of the cron reply in the last request and display rows in `chat.history`.
| Test | Responses base | Responses head | Anthropic base | Anthropic head |
|---|---|---|---|---|
| session-target cron: 1 model copy, 1 display row | red (2 copies) | green | red (2 copies) | green |
| main systemEvent cron: 1 model copy, 1 display row | red (2 copies) | green | red (2 copies) | green |
| isolated cron: unrelated chat has 0 copies, 0 rows | green | green | green | green |
| isolated cron from a chat: keeps placement (1 copy, 1 row) | green | green | green | green |
The last two are guards for unchanged behavior, so they pass on both sides.
Unit cases in `src/sessions/background-session-result.test.ts`: while a turn holds the session, `displayOnly` writes `excludeFromContext` with no placement, and a commit without the flag stays pending.
Consumer suites (background result, destination/current-session completion, double announce, cron notifications, session event handoff and automation result, CLI history boundary): 248 tests pass. `tsgo:core` passes. `check:test-types` reports only existing errors in `test/scripts/release-*` (unrelated).
### Real Gateway, main vs head
Isolated scratch Gateways from source (`--profile` scratch state, `env -i`), real providers, an unrelated chat running 12 turns concurrently. Scenarios: session-target cron + 2 user turns, main systemEvent cron + 2 turns, isolated cron, isolated cron created from the chat. "copies" = assistant copies of the cron reply in the last request of the conversation. Cache = cached input / input tokens per request after the cron run (Anthropic: cache read / cache write).
| Route | Scenario | Copies main | Copies head | Cache per request after cron, main → head (last 2 requests) | Display rows main / head |
|---|---|---|---|---|---|
| OpenAI Responses | session-target cron + 2 turns | 2 | **1** | 33665/35391, 35388/35961 → 33391/35109, 35106/35679 | 1 / 1 |
| OpenAI Responses | main systemEvent cron + 2 turns | 2 | **1** | 31610/32256, 32245/32900 → 31338/31976, 31973/32611 | 1 / 1 |
| OpenAI Responses | isolated cron (other chat) | 0 | 0 | 30651/31225 → 30378/30952 | 0 / 0 |
| OpenAI Responses | isolated cron from this chat | 1 | 1 | 30659/31233 → 30386/30960 | 1 / 1 |
| Claude (Anthropic Messages) | session-target cron + 2 turns | 2 | **1** | 62675/2754, 65429/883 → 62542/2746, 65288/883 | 1 / 1 |
| Claude (Anthropic Messages) | main systemEvent cron + 2 turns | 2 | **1** | 58889/986, 59875/990 → 58758/986, 59744/986 | 1 / 1 |
| Claude (Anthropic Messages) | isolated cron (other chat) | 0 | 0 | 57364/885 → 57233/885 | 0 / 0 |
| Claude (Anthropic Messages) | isolated cron from this chat | 1 | 1 | 57365/884 → 57234/884 | 1 / 1 |
| OpenAI Chat Completions | session-target cron + 2 turns | 2 | **1** | 33086/34812, 34809/35382 → 32813/34531, 34528/35101 | 1 / 1 |
| OpenAI Chat Completions | main systemEvent cron + 2 turns | 2 | **1** | 31028/31666, 31663/32304 → 30760/31398, 31395/32033 | 1 / 1 |
| OpenAI Chat Completions | isolated cron (other chat) | 0 | 0 | 30073/30647 → 29800/30374 | 0 / 0 |
| OpenAI Chat Completions | isolated cron from this chat | 1 | 1 | 30076/30650 → 29803/30377 | 1 / 1 |
The concurrent chat finished all 12 turns `ok` in every run. Cache reads stay at the same level on head (no new prefix breaks); the head prompt is smaller by the removed copy. Chat Completions and Anthropic merge adjacent assistant messages, so copies are counted as reply lines, not messages.
### Real Gateway, persistent webhook (main vs head)
`POST /hooks/agent` with `sessionMode: "persistent"`, `sessionKey: <chat>`, `deliver: false` (the `hooks.ts:315` → `:548` → `runCronIsolatedAgentTurn` → `commitExecutionResult` path), then two user turns in that chat, with an unrelated chat running 12 turns concurrently. Same isolated scratch setup as above.
| Route | Copies main | Copies head | Cache, last request main → head | Display rows main / head |
|---|---|---|---|---|
| OpenAI Responses | 2 | **1** | 31240/31852 → 30983/31556 | 2 / 2 |
| OpenAI Chat Completions | 2 | **1** | 30659/31235 → 30413/30986 | 2 / 2 |
The webhook gives 2 display rows on both sides. The webhook turn's own reply is visible in the chat (its provenance is not cron execution, so it is not hidden), and the committed result row is shown as well. This duplicate display is pre-existing and not changed by this PR; it is a follow-up candidate (the persistent-webhook commit may be redundant for display too). The first main run on Chat Completions was discarded because the model chose a silent reply; the rerun is shown.
## E2E (exact head `bc46e649be75` vs merge base `dbc1aa04e88f`, 2026-11-20)
Isolated scratch Gateways from source (`ocx src`, `--profile` scratch state, `env -i`, random ports), real Claude route (`claude-sonnet-5-5`, Anthropic Messages) behind a logging proxy. Each scenario: user turn, cron (or webhook) comes due, two user turns. An unrelated chat ran 12 turns concurrently in every run. Cache = provider `cache_read_input_tokens` / `cache_creation_input_tokens` per request after the cron run.
| Scenario | Copies in model context, base → head | Cache after cron, base → head | Display rows (UI), base / head |
|---|---|---|---|
| session-target cron + 2 turns | 2 → **1** | 62672/2754, 65426/914 → 62536/2746, 65282/883 | 1 / 1 |
| main systemEvent cron + 2 turns | 2 → **1** | 58880/986, 59866/990 → 58748/986, 59734/986 | 1 / 1 |
| isolated cron (other chat) | 0 → 0 | 57358/885 → 57227/885 | 0 / 0 |
| isolated cron created from this chat | 1 → 1 | 57359/884 → 57228/884 | 1 / 1 |
| persistent webhook into this chat (`c1b1db1` path) | 2 → **1** | 56479/1821, 58300/888 → 56348/1810, 58158/884 | 2 / 2 (pre-existing, see above) |
- Cache reads stay at the same level on head (no new prefix break); head requests are smaller by the removed copy.
- Side effects: the concurrent chat finished 12/12 turns `ok` on both sides; every scenario turn returned `ok`; isolated and creator-chat crons unchanged.
- OpenAI Responses (`gpt-6.2-astra`) was also run, but the provider intermittently rejected identical requests with `400 invalid_json_schema` (`uniqueItems` in a tool schema) on both sides, so only the main-session scenario completed comparably there: 2 copies on base, 1 on head.
### UI
The Control UI chat for the session-target cron shows the cron reply (`TICK`) once on both sides. On base, the model saw it twice and answered the next turn with "I replied \"TICK\" to the last message, but you asked for \"OK two\""; on head it answers `OK two`.
Base:

Head:

### CI
- `check-lint-core-5`: fixed in `bc46e649be75` (`no-base-to-string`, `await-thenable` in the new integration test).
- `checks-node-changed-1` (`src/cron/cron-delivery-outcomes.e2e.test.ts` "applies threshold and cooldown once…") and `checks-node-changed-7` (`test/e2e/qa-lab/runtime/system-turn-automation-read-boundaries.e2e.test.ts` "serves a non-admin automation notice…"): not caused by this PR. Both fail identically on the merge base `dbc1aa04e88f` (same assertion, same received value) and on head; this PR does not touch failure alerts or automation read boundaries.
## Measurement plan
24 h after deploy on a host: count placed automation-result rows that duplicate the immediately preceding model-context assistant reply in the same session. Expected: 0 (baseline on one production host: 33 of 102 placed rows in 7 days).
Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit b4ddf4b)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 8860f4b986b02bcfeb677b763c23bb1f201b5ac6)
(cherry picked from commit 10ccf1b8f9d535706af9119f502d027fe8c758ec)
What was wrong
When a session-target cron (
sessionTarget: "session:<key>") or a main-session cron ran in a chat, its assistant reply stayed in model context (hidden from the chat UI). When the turn settled, OpenClaw committed a second copy into the same chat so the UI could display it; because the cron turn still held the session, that row was written as a pending background result and later injected into model context too. As a result, the model saw its own cron reply twice and sometimes got confused or apologized for repeating itself.Example
A session-target cron runs in your chat and replies
TICK, and then you sendOK two:TICKtwice in its context and answered your next message with "I replied "TICK" to the last message, but you asked for "OK two"".TICKonce, the model seesTICKonce, and it answersOK twonormally.The fix
displayOnly: truewhen a turn commits its settled reply back into the same conversation it ran in:settleSessionEventTurn(src/auto-reply/reply/session-event-automation.ts) for session-target and main-session crons, andcommitExecutionResult(src/cron/isolated-agent/delivery-dispatch.ts) for persistent webhooks.displayOnlythroughcommitCronConversationResult→commitBackgroundPayloadsToSession→commitBackgroundResultToSessionso the writer storesexcludeFromContext: truewith noopenclawModelPlacement: "pending".Proof
Isolated scratch Gateways on merge base
dbc1aa04e88fvs headbc46e649be75(Claudeclaude-sonnet-5-5, Anthropic Messages, 2026-11-20; unrelated chat ran 12/12 turnsokconcurrently):systemEventcron + 2 turnsc1b1db1path)src/cron/session-cron-result-single-copy.gateway.integration.test.ts(red on base with 2 copies, green on head for OpenAI Responses and Anthropic Messages), unit tests insrc/sessions/background-session-result.test.ts, 248 consumer tests, andtsgo:coreall pass.CI notes
check-lint-core-5: fixed inbc46e649be75(no-base-to-string,await-thenablein the new integration test).checks-node-changed-1(src/cron/cron-delivery-outcomes.e2e.test.ts"applies threshold and cooldown once…"): not caused by this PR; fails identically on merge basedbc1aa04e88fand head (this PR does not touch failure alerts).checks-node-changed-7(test/e2e/qa-lab/runtime/system-turn-automation-read-boundaries.e2e.test.ts"serves a non-admin automation notice…"): not caused by this PR; fails identically on merge basedbc1aa04e88fand head (this PR does not touch automation read boundaries).Full test details
Why a parameter (and not derivation or removal)
commitBackgroundResultToSessiononly knows "this session has active work". It cannot tell whether that work is the producer (this cron turn) or a foreign turn (a user typing while an isolated cron result arrives from another session, a subagent completion). Both callers also pass the same{ kind: "cron", jobId, runId }provenance. The run registry entry that names the job (cronRunsByJobId) is consumed before the commit. Exact derivation needs new state; a heuristic (active cron turn in this session) would drop a foreign result from model context when two crons overlap.display: false, so this commit is the only persistent display path. Removing it removes the reply from the chat after a reload. Making the raw reply visible instead changes what the chat shows (no_change, silent replies, directive text, media).So the only callers that know the fact ("my own turn already holds this text") state it (
settleSessionEventTurnandcommitExecutionResultatsrc/cron/isolated-agent/delivery-dispatch.ts:112-136, callers:196and:421).Is the isolated runner reachable with a
session:ormainjob?scriptpayloads return early (src/cron/service/timer-execution.ts:362).runsCronMainSessionRoute(src/cron/service/timer-session-route.ts:20-30) sends every non-plugin-command job withsessionTarget: "main", or withsession:andagentTurn, toexecuteMainSessionCronJob(timer-execution.ts:379).src/cron/service/jobs-validation.ts:106-127) allows onlyagentTurnorcommandonsession:targets, and onlysystemEvent,agentTurnorscriptonmain.executeDetachedCronJob,commandpayloads go to the command runner (timer-execution.ts:479), and anything else that is notagentTurnis rejected (:526).runIsolatedAgentJob(:541) with asession:target is a plugin-command job.runPluginCommandScheduledTurnclaims those, becausereadPluginCommandScheduledJobeither returns the schedule or throws (src/gateway/plugin-command-scheduled-run.ts:70-92). So they never reachrunCronIsolatedAgentTurn(src/gateway/server-cron-agent-run.ts:39-60).src/gateway/server/hooks.ts:315buildssessionTarget: "session:<key>"forsessionMode: "persistent"and callsrunCronIsolatedAgentTurndirectly (:548). That path'scommitExecutionResultcommitted into the execution's own conversation, so it had the same double copy. It now passesdisplayOnly: truetoo, and the persistent-session delivery tests assert the flag.Behavior notes and unchanged paths
isErrorpayloads kept onno_change). Intended: the model already saw its own turn, and the host text is for the reader.priorMessage(src/sessions/background-session-result.ts:164-169). Only runs that straddle the deploy are affected.excludeFromContextrows, so the fix holds (not tested end to end).openclawModelPlacement: "pending"; the Control UI automation boundary readsopenclawAutomation, which is kept. Existing pending rows from older versions are still placed once (accepted, transient).Integration and unit tests (merge base
dbc1aa04e88fvs head)src/cron/session-cron-result-single-copy.gateway.integration.test.ts: a real Gateway, cron service and session store; only the provider endpoint is synthetic.Unit cases in
src/sessions/background-session-result.test.ts: while a turn holds the session,displayOnlywritesexcludeFromContextwith no placement, and a commit without the flag stays pending. Consumer suites: 248 tests pass.tsgo:corepasses.check:test-typesreports only existing errors intest/scripts/release-*(unrelated).Earlier real Gateway runs (main vs head)
Isolated scratch Gateways from source (
--profilescratch state,env -i), real providers, an unrelated chat running 12 turns concurrently (12/12okin every run). Cache = cached input / input tokens per request after the cron run (Anthropic: cache read / cache write). Chat Completions and Anthropic merge adjacent assistant messages, so copies are counted as reply lines, not messages.Persistent webhook (
POST /hooks/agentwithsessionMode: "persistent",sessionKey: <chat>,deliver: false):The webhook gives 2 display rows on both sides because the webhook turn's own reply is visible in the chat (its provenance is not cron execution) and the committed result row is shown as well; this duplicate display is pre-existing and not changed by this PR (follow-up candidate). The first main run on Chat Completions was discarded because the model chose a silent reply; the rerun is shown.
On the 2026-11-20 E2E run, OpenAI Responses (
gpt-6.2-astra) was also run, but the provider intermittently rejected identical requests with400 invalid_json_schema(uniqueItemsin a tool schema) on both sides, so only the main-session scenario completed comparably there: 2 copies on base, 1 on head.UI screenshots
Base:
Head:
Measurement plan
24 h after deploy on a host: count placed automation-result rows that duplicate the immediately preceding model-context assistant reply in the same session. Expected: 0 (baseline on one production host: 33 of 102 placed rows in 7 days).