Skip to content

fix(cron): a session cron's reply reaches the model once - #201838

Merged
obviyus merged 5 commits into
mainfrom
fix/cron-reply-single-copy
Nov 20, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/cron-reply-single-copy

Conversation

@obviyus

@obviyus obviyus commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

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 send OK two:

  • Before: the model saw TICK twice in its context and answered your next message with "I replied "TICK" to the last message, but you asked for "OK two"".
  • Now: the chat UI still shows TICK once, the model sees TICK once, and it answers OK two normally.

The fix

  • Pass displayOnly: true when 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, and commitExecutionResult (src/cron/isolated-agent/delivery-dispatch.ts) for persistent webhooks.
  • Thread displayOnly through commitCronConversationResult → commitBackgroundPayloadsToSession → commitBackgroundResultToSession so the writer stores excludeFromContext: true with no openclawModelPlacement: "pending".
  • Leave isolated crons, creator-chat notifications, run-outcome notices, and subagent completions unchanged.

Proof

Isolated scratch Gateways on merge base dbc1aa04e88f vs head bc46e649be75 (Claude claude-sonnet-5-5, Anthropic Messages, 2026-11-20; unrelated chat ran 12/12 turns ok concurrently):

Scenario Model copies (base → head) Cache read/write after cron (base → head) UI rows (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 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)
  • Other routes: Earlier real-Gateway runs on OpenAI Responses, Claude, and OpenAI Chat Completions all reduced copies from 2 to 1 with steady cache reads and smaller prompts.
  • UI and side effects: Control UI shows the cron reply once on both sides; on head the next user turn answers normally instead of reacting to a duplicate reply. Isolated and creator-chat crons are unchanged.
  • Tests: 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 in src/sessions/background-session-result.test.ts, 248 consumer tests, and tsgo:core all pass.

CI notes

  • 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…"): not caused by this PR; fails identically on merge base dbc1aa04e88f and 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 base dbc1aa04e88f and head (this PR does not touch automation read boundaries).
Full test details

Why a parameter (and not derivation or removal)

  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 (settleSessionEventTurn and commitExecutionResult at src/cron/isolated-agent/delivery-dispatch.ts:112-136, callers :196 and :421).

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.

Behavior notes and unchanged paths

  • Host-authored payloads in the same commit become display-only too (for example, isError payloads kept on no_change). 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 (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 (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. 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).

Integration and unit tests (merge base dbc1aa04e88f vs 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.

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

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: 248 tests pass. tsgo:core passes. check:test-types reports only existing errors in test/scripts/release-* (unrelated).

Earlier real Gateway runs (main vs head)

Isolated scratch Gateways from source (--profile scratch state, env -i), real providers, an unrelated chat running 12 turns concurrently (12/12 ok in 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.

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

Persistent webhook (POST /hooks/agent with sessionMode: "persistent", sessionKey: <chat>, deliver: false):

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 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 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 screenshots

Base:

base: model confused by the duplicate cron reply

Head:

head: cron reply once, normal next turn

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).

…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]>
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Marks 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.

  • Before: The provider receives two copies of SCHEDULED_REPLY_42 while chat history displays one result.
  • After: The provider receives one copy and chat history still displays one result.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused fix with supplied end-to-end evidence and meaningful transport regressions; existing exclusion and pending-placement fields require no migration, and historical rows retain their interpretation.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied live results exercise real scratch Gateways and providers through cron runs and subsequent conversation requests, showing one model copy and one display row across three transports; the committed Gateway harness independently targets both affected execution styles and isolated-job controls.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After an in-session automation replies, the model receives that answer twice and may respond as though it answered twice.
Reason: The maintainer-authored change restores one model copy while preserving the visible result and existing isolated-job semantics.

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
Reviewed head: 29b5f42a5241db590095e971d4bb6852ac3d4d73

Before merge

None.

Findings

None.

Agent review details

How this fits together

Cron 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]
Loading

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit edbc5bc adds src/auto-reply/reply/session-event-automation.ts:236 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: edbc5bcea9b6; files: src/auto-reply/reply/session-event-automation.ts)
  • Peter Steinberger: Raw commit 074b316 adds src/sessions/background-session-result.ts:153 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 074b316e9ec8; files: src/sessions/background-session-result.ts)

PR surface

Source +15, Tests +235. Total +250 across 5 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 18 3 +15
Tests 1 235 0 +235
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 253 3 +250

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Duplicate automation replies pollute subsequent model context and can confuse responses, with a limited cron-specific blast radius.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Duplicate automation replies pollute subsequent model context and can confuse responses, with a limited cron-specific blast radius.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 19, 2026, 8:37 AM ET / 13:37 UTC.

@obviyus

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the remaining red checks on head bc46e64 also fail on this PR's merge base, so this PR did not cause them.

  • checks-node-changed-1: src/cron/cron-delivery-outcomes.e2e.test.ts > "applies threshold and cooldown once before transporting execution failure alerts" (the alert text lacks "failed 2 times in a row"). Run locally on the merge base dbc1aa04e88f (main, no PR changes), it fails with the same assertion. This PR does not change 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 only its own reads at the final effect" (gets "Automation operator source changed" instead of "agent runtime authority is no longer active"). Run locally on the merge base dbc1aa04e88f, it fails the same way. This PR does not change automation read boundaries.
  • openclaw/ci-gate: the aggregate of the two checks above.

The one red this PR did cause, check-lint-core-5, is fixed on this head and passes. Exact-head local review: "patch is correct", 0 findings. Exact-head real-Gateway E2E is in the PR body.

@obviyus
obviyus merged commit b4ddf4b into main Nov 20, 2026
123 of 127 checks passed
@obviyus
obviyus deleted the fix/cron-reply-single-copy branch November 20, 2026 04:55
@obviyus

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

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.

obviyus added a commit that referenced this pull request Nov 20, 2026
obviyus added a commit that referenced this pull request Nov 20, 2026
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]>
obviyus added a commit that referenced this pull request Nov 20, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…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:

![base: model confused by the duplicate cron reply](https://github.com/user-attachments/assets/a22433d5-3578-48c1-8722-22f1fb1cd2de)

Head:

![head: cron reply once, normal next turn](https://github.com/user-attachments/assets/48862c19-db85-490f-bb71-06f845e8136f)

### 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
## 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:

![base: model confused by the duplicate cron reply](https://github.com/user-attachments/assets/a22433d5-3578-48c1-8722-22f1fb1cd2de)

Head:

![head: cron reply once, normal next turn](https://github.com/user-attachments/assets/48862c19-db85-490f-bb71-06f845e8136f)

### 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant