Skip to content

fix(cli): keep conversation context after cancellation - #147139

Merged
obviyus merged 7 commits into
mainfrom
bugloop/resume-after-cancel
Sep 13, 2026
Merged

obviyus merged 7 commits into
mainfrom
bugloop/resume-after-cancel

Conversation

@obviyus

@obviyus obviyus commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #144392

Supersedes #145788 by @Marvinthebored. Thanks to @EnotionZ for the issue report. The original commit and authorship are preserved.

What Problem This Solves

Canceling a reply makes the next turn forget the conversation, even though earlier messages still appear in history.

User Impact

Stopping a reply keeps the established conversation available for the next turn. Invalid sessions and account boundaries still receive their existing checks.

Why This Change Was Made

Retain established native bindings on cancellation. Clear unfinished replacements on both thrown errors and returned partial-output interruptions. An incomplete fork claim is restored by current-owner cleanup even when the signal is aborted. New claims, successor publication, and recovery arming retain their abort guards; all writes retain session, lifecycle, writer, and source-binding checks.

This preserves partial-output reporting from #126883 while removing cancellation-only binding invalidation. No schema, migration, configuration, protocol, or dependency change.

Final-head evidence

Head b068bf05618ddcd3e1b28894c68ad734e0eac997 includes a one-line test-type correction that passes the existing defined session entry; the command still reloads persisted state before choosing the next native binding. All 157 tests in that file, targeted lint, and formatting pass. Production source is unchanged from 2c163fd9eb57100ae3a2eec38cb6038e5f752851.

The complete affected owner suites passed on fresh merge 4b66a1a18209c21b5e92986452b2b98b95ae6fa1, with parents 2c163fd9eb57100ae3a2eec38cb6038e5f752851 and main 9542320aa5cdcc4af53e3b05ad75160992a34407. All 28 complete canonical groups exited 0: 46,971 labeled passes and 88 skips. Three cases are unlabelled in the native support summary; no status is inferred. This includes both fork-restoration cases and all four abort/timeout × established/replacement command cases. Complete current group membership, exact commands, numeric exits, and raw logs are retained.

env -u NO_COLOR -u FORCE_COLOR node --import tsx scripts/ci-run-node-test-shard.mts

Hosted CI run 34774482283, attempt 1 passed except checks-node-compact-small-32 and its aggregate gate. Its QA-profile routing assertion is base-red: the same test fails on plain main 28887b564210326174413d0d8ade72b38268d5f3 and fresh candidate/main merge 7ea7374fcf62570c9b3fa631cf17072ef5eda2d6, both exit 1. #143968 (07b96d9b4122e1afdd0efbb662b2335eb716dfec) added qa-profile-run-status.test.ts as a sixth workflow reader without updating the five-target expectation. This PR changes none of those routing inputs.

OPENCLAW_E2E_USE_PREBUILT_DIST=1 node scripts/run-vitest.mjs run \
  test/scripts/test-projects.test.ts -t 'routes QA Profile Evidence'

Fork-claim correction

Candidate 2c163fd9eb57100ae3a2eec38cb6038e5f752851 restores a committed fork claim after cancellation before a successor appears. Previously, restoration rejected the aborted signal, lost the fork marker, and let the next command resume the source directly. Cleanup now uses the existing current-owner settlement assertion. Stale session, lifecycle, writer, placement, and source-binding checks remain enforced.

The regression fails on e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8: the marker is absent and the next command receives forkCliSessionOnResume=false. After correction, both the recovery-error control and actual-signal cancellation pass; stored/cache markers and the source checkpoint remain, and the next command receives forkCliSessionOnResume=true.

env -u NO_COLOR -u FORCE_COLOR node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.agents.config.ts \
  src/agents/command/attempt-execution.cli.test.ts --maxWorkers=1 \
  -t 'preserves a restored fork marker before a successor'

Fresh merge 54a5c90a8b4585f72842e380365b95263b05983d has first parent candidate 2c163fd9eb57100ae3a2eec38cb6038e5f752851 and second parent main adb6e518a44218650883f3daec4bd319165e0017. All 436 tests in seven complete focused files passed, including command successor/flag cleanup, aborted pre-successor restoration, stale-store guards, returned interruption, thrown cancellation, auto-reply, and fork-runner siblings. This bounded rerun supplements the earlier complete suites.

Both real Gateway cancellation shapes also passed on that merge: before output (zero assistant events) and after first output. Both next turns resumed the same native binding, logged historyPrompt=none, and recalled PEBBLE-7429. Both drivers exited 0. The new catalog regression uses the real command/store entry point with a mocked native runner; it proves next-turn fork routing, not a new live source-transcript isolation capture.

Targeted lint passed, including max-lines:

pnpm exec oxlint --config .oxlintrc.json \
  src/agents/command/attempt-execution.ts \
  src/agents/command/attempt-execution.cli.test.ts

Original red evidence remains intact. Exact commands, merge identities, numeric exits, and complete captures are retained. The complete affected-suite rerun and final-head CI classification are recorded above.

Earlier evidence

Validated corrected candidate 4fd555e5957f86289cf981ce4cf4b0bb1122c679 on temporary merge d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d. Its parents are that candidate and main a0cce74d389d737d6dcf21de7344af10cf862f72.

All 28 complete canonical CI groups for the affected agent, reply, scheduled-run, and fast test suites exited 0 on that merge. Reporters label 46,859 tests passed and 88 skipped. The full command persistence matrix passed, including unfinished-successor and temporary-flag cleanup for abort and timeout, plus established-binding resume.

Each complete group ran through the CI command, with its canonical configuration, include list and environment preserved:

node --import tsx scripts/ci-run-node-test-shard.mts

These are the complete affected test suites on the recorded merge. Final-head CI and its reproduced base-red exception are recorded above. Initial host setup failures were retained, then resolved by removing conflicting color settings and making GNU timeout available without replacing existing command resolution. No source assertions or timeouts were relaxed. One native summary leaves three cases unlabeled; the raw count line is retained without assigning them a status.

The real Gateway was also rerun from the merge with isolated state, workspace and port:

OPENCLAW_CONFIG_PATH="$PROOF/openclaw.json" OPENCLAW_STATE_DIR="$PROOF/state" \
  pnpm openclaw gateway --port 21978 --bind loopback

chat.send remembered a synthetic code, a second request started a long reply, chat.abort canceled it, and the next chat.send requested the code without repeating it.

Cancellation Recorded main Corrected merge
Before output Fresh native session; UNKNOWN Same native binding; PEBBLE-7429
After first output Fresh native session; UNKNOWN Same native binding; PEBBLE-7429

Both drivers exited 0. Both continuations logged useResume=true with the same native fingerprint and historyPrompt=none. The pre-output run had zero assistant events before cancellation. Original red captures, merge parents, selection, exact commands, numeric exits and complete logs are preserved. Final-head CI and its reproduced base-red exception are recorded above.

Compatibility and prior behavior

This deliberately changes the cancellation-only binding invalidation retained by #126883 and #128131. Partial output remains visible, interrupted turns remain unsuccessful, and successful authentication settlement remains suppressed. Expired-session recovery from #115513 and the retired-field migration from #143347 remain unchanged. There is no schema, migration, configuration, protocol, dependency, or permission change.

Consumers

Command attempts, auto-reply turns, and scheduled turns consume the binding result. History import, session freshness, catalog continuation, export, runtime selection, and detached-media continuation read the retained binding or its explicit absence.

Catalog adoption seeds a binding with forceReuse and a one-shot fork marker. The command path claims that marker before execution and can persist a successor before final settlement. These writes require the current session, lifecycle, writer, and expected source binding. Successful settlement removes the temporary reuse flag; interrupted replacement cleanup removes the successor and flag together. An established binding remains available after cancellation. Cancellation before a fork successor appears restores the one-shot marker, so the next command must still fork from the source. Cache updates occur at the successful commit, and scheduled continuation publication follows base-session persistence.

Evidence limits

The real Gateway sequences cover cancellation before output and after the first output. Both failed on main fe3b2891fdeaa1a891d54cb2b306e975fc5408cf and passed at f9c5b148cf4d92de5211315a4e8c374bef279d9d. The next turn resumed the same native binding without replaying local history and recalled the seeded code.

The initial 272 focused tests include command persistence and next-turn routing, auto-reply retention, failed-flush cleanup, and scheduled-run settlement. They ran on the branch based on f85a9945daaebc61d041db27b4d3175d17082e37. The later fresh merge d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d, recorded above, passed all 28 complete affected test groups and both real Gateway cancellation shapes. No browser-click or platform-specific UI claim is made.

The two test suites that failed on the contributor head pass when applied to the refreshed main base and after correction. The original hosted failures were not reproduced in their original shard order, so their cause remains unclassified. No assertion or timeout was relaxed for this repair.

Test ledger clarification

  • The ordinary-abort policy and command assertions now require retention instead of unconditional deletion. Command coverage also checks the subsequent resume.
  • The contributor-only interrupted-flush helper matrix was removed before the final diff because command persistence coverage supersedes it.
  • The retained interrupted-partial-output fixture now names an established reusable session. Its unchanged clear assertion independently protects failed transcript flush; its partial-output, unsuccessful-hook, timeout, and authentication assertions remain.
  • The new composition cases invoke runAgentAttempt, claim a fork, persist its successor, abort the actual signal, consume the production settlement result, reopen stored state, and check the next attempt. The channel regression invokes executeAgentTurn; the failed-flush regression invokes runPreparedCliAgent. Direct policy-unit assertions supplement these entry-point checks.

The earlier head e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8 only replaces a retained unflushed ID with the equivalent condition at its two consumers. Review accepted that behavior-preserving delta. CI run 34769866871 passed at attempt 2 on this exact head. Attempt 1 had one test failure in an unrelated QA binary-admission case; it passed on the retry without a code or timeout change and is recorded as a flake.

@clawsweeper

clawsweeper Bot commented Sep 13, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 13, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 2:33 PM ET / 18:33 UTC (Revision 6).

ClawSweeper review

What this changes

Preserves CLI conversation bindings after cancellation, clears unfinished replacements, and restores interrupted fork claims so subsequent turns retain the intended conversation.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary: current main and the latest release still invalidate established bindings on cancellation. The recorded runtime evidence supports the repair, and this review found no blocking defect.

Priority: P1
Reviewed head: b068bf05618ddcd3e1b28894c68ad734e0eac997

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with convincing runtime evidence, meaningful persistence regressions, and no blocking finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Recorded real Gateway and native CLI sequences exercise cancellation before and after output, then demonstrate same-binding recall without history replay; the latest commit changes only a test argument, preserving that production coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): Recorded real Gateway and native CLI sequences exercise cancellation before and after output, then demonstrate same-binding recall without history replay; the latest commit changes only a test argument, preserving that production coverage.
Evidence reviewed 9 items Current main still has the reported behavior: At the fetched main revision, shouldClearFailedCliSessionBinding clears ordinary AbortError bindings, and buildCliRunResult independently clears every returned terminal interruption.
Latest-release comparison: The v2026.9.4 source also clears non-fork bindings on AbortError; this is not an already-shipped cancellation repair.
Settlement preserves the existing failure distinctions: Interrupted settlement retains established continuity while still clearing disabled bindings, failed transcript flushes, and replacements. Interrupted output remains unsuccessful and cannot invoke successful authentication binding.
Findings None None.
Security None None.

How this fits together

OpenClaw stores a reference to each CLI backend’s native conversation so later agent turns can resume it. Cancellation settlement decides whether that reference remains usable before the next command or channel turn.

flowchart TD
  A[Command or channel turn] --> B[Stored conversation binding]
  B --> C[Native CLI execution]
  C --> D[Cancellation settlement]
  D --> E[Retain established conversation]
  D --> F[Clear unfinished replacement]
  D --> G[Restore incomplete fork claim]
  E --> H[Next turn resumes]
  G --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +20, Tests +193. Total +213 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 31 11 +20
Tests 4 245 52 +193
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 276 63 +213

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #144392
Summary: This PR is a candidate repair for the reported cancellation-induced loss of native conversation continuity.

Members:

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

Technical review

Best possible solution:

Keep cancellation separate from conversation invalidation while retaining current-owner cleanup, expired-session recovery, and next-turn reuse checks.

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

Yes: current source clears established bindings after cancellation, matching the supplied Gateway before/after sequences. This review inspected that path without executing it.

Is this the best way to solve the issue?

Yes: changing the existing settlement policy repairs continuity without duplicating history replay, adding configuration, or weakening the store’s current-owner checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 29517dc5f3ad.

Labels

Label justifications:

  • P1: Cancellation currently causes real CLI-backed conversations to lose model-facing continuity on the next turn.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Recorded real Gateway and native CLI sequences exercise cancellation before and after output, then demonstrate same-binding recall without history replay; the latest commit changes only a test argument, preserving that production coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real Gateway and native CLI sequences exercise cancellation before and after output, then demonstrate same-binding recall without history replay; the latest commit changes only a test argument, preserving that production coverage.

Evidence

What I checked:

  • Current main still has the reported behavior: At the fetched main revision, shouldClearFailedCliSessionBinding clears ordinary AbortError bindings, and buildCliRunResult independently clears every returned terminal interruption. (src/agents/cli-session.ts:163, 29517dc5f3ad)
  • Latest-release comparison: The v2026.9.4 source also clears non-fork bindings on AbortError; this is not an already-shipped cancellation repair. (src/agents/cli-session.ts:167, 3a9d69db306c)
  • Settlement preserves the existing failure distinctions: Interrupted settlement retains established continuity while still clearing disabled bindings, failed transcript flushes, and replacements. Interrupted output remains unsuccessful and cannot invoke successful authentication binding. (src/agents/cli-runner/cli-run-settlement.ts:502, b068bf05618d)
  • Cleanup retains current-owner enforcement: Fork restoration uses the existing settlement assertion. The store owner still compares session identity, lifecycle, writer, and source binding; the SQLite commit edge revalidates its snapshot and invokes assertCommitAllowed before writing. New fork claims and successor publication retain their abort guards. (src/agents/command/attempt-execution.ts:1124, b068bf05618d)
  • Behavioral regression coverage: Command tests exercise persisted state and next-turn routing for thrown aborts, four returned-interruption/replacement combinations, and cancellation before fork successor creation. Sibling coverage checks stale binding owners, failed flushes, partial output, and channel retention. Tests were inspected, not executed during this read-only review. (src/agents/command/attempt-execution.cli.test.ts:1526, b068bf05618d)
  • Recorded real Gateway proof: The supplied PR body, captured under sourceRevision 276c52ced26306d290c8562ab987f6f0ffbdf0ecbd26dd3362711c1a3f2f9b54, records real chat.send → chat.abort → chat.send sequences before output and after first output on merge 54a5c90a8b4585f72842e380365b95263b05983d. Both continuations retained the native binding, logged historyPrompt=none, recalled the synthetic code, and exited zero. Catalog fork routing is separately supported by production command/store tests with a mocked native runner. (54a5c90a8b45)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-13T15:27:44.628Z sha f9c5b14 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T16:37:09.265Z sha 4fd555e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T16:58:41.691Z sha e2ca5b2 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T17:24:14.424Z sha e2ca5b2 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-13T17:46:32.378Z sha 2c163fd :: needs maintainer review before merge. :: none

@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 147139
head: 4fd555e
scope: owner-review

@obviyus
obviyus marked this pull request as ready for review September 13, 2026 16:34
@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 147139
head: e2ca5b2
scope: owner-review

@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 147139
head: b068bf0
scope: owner-review

@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-unrelated-red
pr: 147139
head: b068bf0
run: 34774482283 attempt: 1
failed: checks-node-compact-small-32 job=103770217753 conclusion=failure
check: openclaw/ci-gate

@obviyus
obviyus merged commit 202d309 into main Sep 13, 2026
184 of 186 checks passed
@obviyus
obviyus deleted the bugloop/resume-after-cancel branch September 13, 2026 19:01
@obviyus

obviyus commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @Marvinthebored and @EnotionZ!

Proof: Cancellation before output and after the first output both resumed the same conversation and recalled the earlier code without replaying history.

  • Bug: Stopping a reply made the next turn forget earlier context.
  • Fix: Keep established conversation bindings and clear unfinished replacements.
Before After
The next turn forgot the remembered code. The next turn resumed the conversation and recalled the code.

vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit 'cf45ff4d6a9c13164463db860285a02c1c4f2e8c':
  test(macos): observe readiness cancellation and deadline ownership (#145056)
  fix(ci): route QA Profile Evidence to its run-status owner test (#147293)
  fix(install): preserve runtime links when Node validation fails (#147221)
  test(auto-reply): reuse memory session fixtures (#147262)
  fix: hide subagent sessions from Activity (#147253)
  ci: record resources for slow runtime test commands (#147254)
  fix(update): recognize FreeBSD boot identities in triage leases (#147243)
  refactor(active-memory): share closing tag line scan (#147031)
  fix: resume Settings autosave after Reload Config (#147136)
  fix(cli): keep conversation context after cancellation (#147139)
  fix(channels): make system-agent approval cards actionable (#147152)
  refactor: retain shared database handles until their last worker closes (#147246)
  refactor(slack): share workspace-qualified target resolution (#147024)
  refactor(msteams): remove duplicate quoted-table test (#147270)
vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit 'ac59d5e09eb468dc23cf95e447608b57e71b52af': (176 commits)
  improve(gateway): avoid redundant startup preflight work (#147285)
  test(macos): observe readiness cancellation and deadline ownership (#145056)
  fix(ci): route QA Profile Evidence to its run-status owner test (#147293)
  fix(install): preserve runtime links when Node validation fails (#147221)
  test(auto-reply): reuse memory session fixtures (#147262)
  fix: hide subagent sessions from Activity (#147253)
  ci: record resources for slow runtime test commands (#147254)
  fix(update): recognize FreeBSD boot identities in triage leases (#147243)
  refactor(active-memory): share closing tag line scan (#147031)
  fix: resume Settings autosave after Reload Config (#147136)
  fix(cli): keep conversation context after cancellation (#147139)
  fix(channels): make system-agent approval cards actionable (#147152)
  refactor: retain shared database handles until their last worker closes (#147246)
  refactor(slack): share workspace-qualified target resolution (#147024)
  refactor(msteams): remove duplicate quoted-table test (#147270)
  fix(qa): bind coverage IDs to producer assertions (#144000)
  fix(linux): explain FreeBSD desktop setup prerequisites (#147211)
  fix(memory): split embedding batches rejected for an input array item cap (#139541)
  test: isolate timing metadata persistence from inherited settings (#147112)
  refactor(status): retire test-only helper publication (#147071)
  ...
obviyus added a commit that referenced this pull request Sep 13, 2026
Related: #146331. Supersedes #146595 by @MasterSwords1. Thanks @fray-ai for reporting it.

## What Problem This Solves

After replay cleanup removes old messages, an assistant can lose the current task and successful tool results from later requests, even though chat history still shows them.

## Why This Change Was Made

Normalize replay before prompt preparation records the history boundary. Session setup seeds the count; prompt preparation replaces it after history assembly and cleanup. Submission consumes that prepared history; it no longer shortens history after the boundary is set. The contributor's production fix is preserved. Tests now use complete fixtures and real prompt preparation/submission, with a clean-history control.

## User Impact

Current instructions and tool results remain available across multiple tool calls. No setting or migration is needed.

## Evidence

Authenticated Gateway `chat.send`, an isolated history-only context engine, and two actual file reads:

| Captured request | Main, six silent history messages | Candidate |
| --- | --- | --- |
| First | Current task present | Current task present |
| Second | Task and first result absent | Task and first result present |
| Third | Task and both results absent | Task and both results present |

Both runs completed the reads and retained the entire turn in chat history. The no-silent-history control passes on both. Responses were deterministic; this proves request contents, not model answer quality.

The corrected regression fails on main because the active prompt is missing, and passes with the fix. Five selected test files pass on fresh merge `3e4442b9890b85e579eb36f657e88261ca0ef825` (parents `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc` and `fa5b2d16805c7c81e2c395fbbc0ff27312b16da1`): 160 distinct tests, 250 successful executions across the two test configurations.

<details>
<summary>Commands and captured result</summary>

Gateway driver commands, using the retained proof directory:

```sh
node "$PROOF/reproduce.mjs" candidate-six 6
node "$PROOF/assert-tail.mjs" candidate-six
node "$PROOF/reproduce.mjs" candidate-clean 0
node "$PROOF/assert-tail.mjs" candidate-clean
```

Both candidate assertions exit 0. The same assertion exits 1 on the recorded main reproduction. Captured candidate checks: three requests; two completed reads; current task retained in every request; first result retained in request two; both results retained in request three; chat history retains all markers.

Selected tests:

```sh
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-context-advancement.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts \
  src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
```

The fresh merge used `node --import tsx scripts/ci-run-node-test-shard.mts`, with these five include paths and the embedded-agent and embedded-agent-run configurations. Exit 0. Six additional direct-caller files also passed on that merge (165 tests), covering replay recovery, projections, settlement, media hints, and tool-result budgets. Typechecks remain for CI.

</details>

## Compatibility

No schema, protocol, dependency, configuration, or durable transcript change. Existing context-engine commit semantics remain intact.

## Consumers

The shared boundary also serves turn completion, usage fallback, and legacy context finalization. They consume the normalized count. The independent CLI history boundary is unchanged.

## Invalidation

Each attempt computes the boundary after replay cleanup. No persistent cache or new state owner is added.

### Ordering and consumers

Session setup seeds the history count. Prompt preparation replaces it after history assembly and replay cleanup, then submission consumes the prepared history. The same count serves tool-loop advancement, reply flushing, usage fallback, and legacy turn completion. Hook and budget projections and the active-run snapshot use that prepared history. Optional settled-turn finalization still reads the newly completed assistant from the stream subscription, preserving the authored `NO_REPLY` behavior from #145343.

### Validation scope

The retained Gateway proof checks actual request contents and completed file reads with deterministic responses. Main loses the active task and results after replay cleanup; the candidate retains them. Both clean-history controls pass. Runtime proof was captured at `9dc8e3a19ad7ea694bc40ca520f1e2597e7fdc22`; the final commit changes only tests. The fresh merge includes #145343, #147139, and #147394. Its selected suites pass 160 distinct tests, with 250 executions due to configuration overlap, plus 165 tests in six additional consumer files. This does not claim a separate fresh execution of the finalizer-silence scenario, browser rendering, or answer quality. Typechecks remain for CI.

CI run [34789473564](https://github.com/openclaw/openclaw/actions/runs/34789473564) completed successfully at `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc`, including the hosted type checks.

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

Supersedes openclaw#145788 by @Marvinthebored. Thanks to @EnotionZ for the issue report. The original commit and authorship are preserved.

## What Problem This Solves

Canceling a reply makes the next turn forget the conversation, even though earlier messages still appear in history.

## User Impact

Stopping a reply keeps the established conversation available for the next turn. Invalid sessions and account boundaries still receive their existing checks.

## Why This Change Was Made

Retain established native bindings on cancellation. Clear unfinished replacements on both thrown errors and returned partial-output interruptions. An incomplete fork claim is restored by current-owner cleanup even when the signal is aborted. New claims, successor publication, and recovery arming retain their abort guards; all writes retain session, lifecycle, writer, and source-binding checks.

This preserves partial-output reporting from openclaw#126883 while removing cancellation-only binding invalidation. No schema, migration, configuration, protocol, or dependency change.

## Final-head evidence

Head `b068bf05618ddcd3e1b28894c68ad734e0eac997` includes a one-line test-type correction that passes the existing defined session entry; the command still reloads persisted state before choosing the next native binding. All 157 tests in that file, targeted lint, and formatting pass. Production source is unchanged from `2c163fd9eb57100ae3a2eec38cb6038e5f752851`.

The complete affected owner suites passed on fresh merge `4b66a1a18209c21b5e92986452b2b98b95ae6fa1`, with parents `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and main `a9a9a16114bea90d6eac90486356697df2462cb9`. All **28 complete canonical groups exited 0**: 46,971 labeled passes and 88 skips. Three cases are unlabelled in the native support summary; no status is inferred. This includes both fork-restoration cases and all four abort/timeout × established/replacement command cases. Complete current group membership, exact commands, numeric exits, and raw logs are retained.

```sh
env -u NO_COLOR -u FORCE_COLOR node --import tsx scripts/ci-run-node-test-shard.mts
```

Hosted [CI run 34774482283, attempt 1](https://github.com/openclaw/openclaw/actions/runs/34774482283) passed except `checks-node-compact-small-32` and its aggregate gate. Its QA-profile routing assertion is **base-red**: the same test fails on plain main `a1105f105a093f768914a29c24b70d6ba406cad8` and fresh candidate/main merge `7ea7374fcf62570c9b3fa631cf17072ef5eda2d6`, both exit 1. openclaw#143968 (`41aebf15de48524e80c95f05e0c1212f2dfd29c6`) added `qa-profile-run-status.test.ts` as a sixth workflow reader without updating the five-target expectation. This PR changes none of those routing inputs.

```sh
OPENCLAW_E2E_USE_PREBUILT_DIST=1 node scripts/run-vitest.mjs run \
  test/scripts/test-projects.test.ts -t 'routes QA Profile Evidence'
```

## Fork-claim correction

Candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` restores a committed fork claim after cancellation before a successor appears. Previously, restoration rejected the aborted signal, lost the fork marker, and let the next command resume the source directly. Cleanup now uses the existing current-owner settlement assertion. Stale session, lifecycle, writer, placement, and source-binding checks remain enforced.

The regression fails on `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8`: the marker is absent and the next command receives `forkCliSessionOnResume=false`. After correction, both the recovery-error control and actual-signal cancellation pass; stored/cache markers and the source checkpoint remain, and the next command receives `forkCliSessionOnResume=true`.

```sh
env -u NO_COLOR -u FORCE_COLOR node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.agents.config.ts \
  src/agents/command/attempt-execution.cli.test.ts --maxWorkers=1 \
  -t 'preserves a restored fork marker before a successor'
```

Fresh merge `54a5c90a8b4585f72842e380365b95263b05983d` has first parent candidate `2c163fd9eb57100ae3a2eec38cb6038e5f752851` and second parent main `e08263bdd3341031c219bb147638f23a1f4c3c03`. All **436 tests in seven complete focused files passed**, including command successor/flag cleanup, aborted pre-successor restoration, stale-store guards, returned interruption, thrown cancellation, auto-reply, and fork-runner siblings. This bounded rerun supplements the earlier complete suites.

Both real Gateway cancellation shapes also passed on that merge: before output (zero assistant events) and after first output. Both next turns resumed the same native binding, logged `historyPrompt=none`, and recalled `PEBBLE-7429`. Both drivers exited 0. The new catalog regression uses the real command/store entry point with a mocked native runner; it proves next-turn fork routing, not a new live source-transcript isolation capture.

Targeted lint passed, including max-lines:

```sh
pnpm exec oxlint --config .oxlintrc.json \
  src/agents/command/attempt-execution.ts \
  src/agents/command/attempt-execution.cli.test.ts
```

Original red evidence remains intact. Exact commands, merge identities, numeric exits, and complete captures are retained. The complete affected-suite rerun and final-head CI classification are recorded above.

## Earlier evidence

Validated corrected candidate `4fd555e5957f86289cf981ce4cf4b0bb1122c679` on temporary merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`. Its parents are that candidate and main `e0ad90d2bc2effce521cbde79cec2be56cece725`.

All 28 complete canonical CI groups for the affected agent, reply, scheduled-run, and fast test suites exited 0 on that merge. Reporters label **46,859 tests passed and 88 skipped**. The full command persistence matrix passed, including unfinished-successor and temporary-flag cleanup for abort and timeout, plus established-binding resume.

Each complete group ran through the CI command, with its canonical configuration, include list and environment preserved:

```sh
node --import tsx scripts/ci-run-node-test-shard.mts
```

These are the complete affected test suites on the recorded merge. Final-head CI and its reproduced base-red exception are recorded above. Initial host setup failures were retained, then resolved by removing conflicting color settings and making GNU timeout available without replacing existing command resolution. No source assertions or timeouts were relaxed. One native summary leaves three cases unlabeled; the raw count line is retained without assigning them a status.

The real Gateway was also rerun from the merge with isolated state, workspace and port:

```sh
OPENCLAW_CONFIG_PATH="$PROOF/openclaw.json" OPENCLAW_STATE_DIR="$PROOF/state" \
  pnpm openclaw gateway --port 21978 --bind loopback
```

`chat.send` remembered a synthetic code, a second request started a long reply, `chat.abort` canceled it, and the next `chat.send` requested the code without repeating it.

| Cancellation | Recorded main | Corrected merge |
| --- | --- | --- |
| Before output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |
| After first output | Fresh native session; `UNKNOWN` | Same native binding; `PEBBLE-7429` |

Both drivers exited 0. Both continuations logged `useResume=true` with the same native fingerprint and `historyPrompt=none`. The pre-output run had zero assistant events before cancellation. Original red captures, merge parents, selection, exact commands, numeric exits and complete logs are preserved. Final-head CI and its reproduced base-red exception are recorded above.

## Compatibility and prior behavior

This deliberately changes the cancellation-only binding invalidation retained by openclaw#126883 and openclaw#128131. Partial output remains visible, interrupted turns remain unsuccessful, and successful authentication settlement remains suppressed. Expired-session recovery from openclaw#115513 and the retired-field migration from openclaw#143347 remain unchanged. There is no schema, migration, configuration, protocol, dependency, or permission change.

## Consumers

Command attempts, auto-reply turns, and scheduled turns consume the binding result. History import, session freshness, catalog continuation, export, runtime selection, and detached-media continuation read the retained binding or its explicit absence.

Catalog adoption seeds a binding with `forceReuse` and a one-shot fork marker. The command path claims that marker before execution and can persist a successor before final settlement. These writes require the current session, lifecycle, writer, and expected source binding. Successful settlement removes the temporary reuse flag; interrupted replacement cleanup removes the successor and flag together. An established binding remains available after cancellation. Cancellation before a fork successor appears restores the one-shot marker, so the next command must still fork from the source. Cache updates occur at the successful commit, and scheduled continuation publication follows base-session persistence.

## Evidence limits

The real Gateway sequences cover cancellation before output and after the first output. Both failed on main `0c664785f82d3af6c2101efb53d7269d30261f4c` and passed at `f9c5b148cf4d92de5211315a4e8c374bef279d9d`. The next turn resumed the same native binding without replaying local history and recalled the seeded code.

The initial 272 focused tests include command persistence and next-turn routing, auto-reply retention, failed-flush cleanup, and scheduled-run settlement. They ran on the branch based on `329bc5bf9694af38477f9fd45ebe47ad86b538a9`. The later fresh merge `d5f41d1cd6c9b603db32deec1d60c1ba93e7e04d`, recorded above, passed all 28 complete affected test groups and both real Gateway cancellation shapes. No browser-click or platform-specific UI claim is made.

The two test suites that failed on the contributor head pass when applied to the refreshed main base and after correction. The original hosted failures were not reproduced in their original shard order, so their cause remains unclassified. No assertion or timeout was relaxed for this repair.

## Test ledger clarification

- The ordinary-abort policy and command assertions now require retention instead of unconditional deletion. Command coverage also checks the subsequent resume.
- The contributor-only interrupted-flush helper matrix was removed before the final diff because command persistence coverage supersedes it.
- The retained interrupted-partial-output fixture now names an established reusable session. Its unchanged clear assertion independently protects failed transcript flush; its partial-output, unsuccessful-hook, timeout, and authentication assertions remain.
- The new composition cases invoke `runAgentAttempt`, claim a fork, persist its successor, abort the actual signal, consume the production settlement result, reopen stored state, and check the next attempt. The channel regression invokes `executeAgentTurn`; the failed-flush regression invokes `runPreparedCliAgent`. Direct policy-unit assertions supplement these entry-point checks.

The earlier head `e2ca5b29bfa09810aaa20eca8a1d0e85ced913c8` only replaces a retained unflushed ID with the equivalent condition at its two consumers. Review accepted that behavior-preserving delta. CI run [34769866871](https://github.com/openclaw/openclaw/actions/runs/34769866871) passed at attempt 2 on this exact head. Attempt 1 had one test failure in an unrelated QA binary-admission case; it passed on the retry without a code or timeout change and is recorded as a flake.

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…47531)

Related: openclaw#146331. Supersedes openclaw#146595 by @MasterSwords1. Thanks @fray-ai for reporting it.

## What Problem This Solves

After replay cleanup removes old messages, an assistant can lose the current task and successful tool results from later requests, even though chat history still shows them.

## Why This Change Was Made

Normalize replay before prompt preparation records the history boundary. Session setup seeds the count; prompt preparation replaces it after history assembly and cleanup. Submission consumes that prepared history; it no longer shortens history after the boundary is set. The contributor's production fix is preserved. Tests now use complete fixtures and real prompt preparation/submission, with a clean-history control.

## User Impact

Current instructions and tool results remain available across multiple tool calls. No setting or migration is needed.

## Evidence

Authenticated Gateway `chat.send`, an isolated history-only context engine, and two actual file reads:

| Captured request | Main, six silent history messages | Candidate |
| --- | --- | --- |
| First | Current task present | Current task present |
| Second | Task and first result absent | Task and first result present |
| Third | Task and both results absent | Task and both results present |

Both runs completed the reads and retained the entire turn in chat history. The no-silent-history control passes on both. Responses were deterministic; this proves request contents, not model answer quality.

The corrected regression fails on main because the active prompt is missing, and passes with the fix. Five selected test files pass on fresh merge `3e4442b9890b85e579eb36f657e88261ca0ef825` (parents `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc` and `4492504cc1f3704f8b3a5459f75a9c57e1f96edd`): 160 distinct tests, 250 successful executions across the two test configurations.

<details>
<summary>Commands and captured result</summary>

Gateway driver commands, using the retained proof directory:

```sh
node "$PROOF/reproduce.mjs" candidate-six 6
node "$PROOF/assert-tail.mjs" candidate-six
node "$PROOF/reproduce.mjs" candidate-clean 0
node "$PROOF/assert-tail.mjs" candidate-clean
```

Both candidate assertions exit 0. The same assertion exits 1 on the recorded main reproduction. Captured candidate checks: three requests; two completed reads; current task retained in every request; first result retained in request two; both results retained in request three; chat history retains all markers.

Selected tests:

```sh
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-context-advancement.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts \
  src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
```

The fresh merge used `node --import tsx scripts/ci-run-node-test-shard.mts`, with these five include paths and the embedded-agent and embedded-agent-run configurations. Exit 0. Six additional direct-caller files also passed on that merge (165 tests), covering replay recovery, projections, settlement, media hints, and tool-result budgets. Typechecks remain for CI.

</details>

## Compatibility

No schema, protocol, dependency, configuration, or durable transcript change. Existing context-engine commit semantics remain intact.

## Consumers

The shared boundary also serves turn completion, usage fallback, and legacy context finalization. They consume the normalized count. The independent CLI history boundary is unchanged.

## Invalidation

Each attempt computes the boundary after replay cleanup. No persistent cache or new state owner is added.

### Ordering and consumers

Session setup seeds the history count. Prompt preparation replaces it after history assembly and replay cleanup, then submission consumes the prepared history. The same count serves tool-loop advancement, reply flushing, usage fallback, and legacy turn completion. Hook and budget projections and the active-run snapshot use that prepared history. Optional settled-turn finalization still reads the newly completed assistant from the stream subscription, preserving the authored `NO_REPLY` behavior from openclaw#145343.

### Validation scope

The retained Gateway proof checks actual request contents and completed file reads with deterministic responses. Main loses the active task and results after replay cleanup; the candidate retains them. Both clean-history controls pass. Runtime proof was captured at `9dc8e3a19ad7ea694bc40ca520f1e2597e7fdc22`; the final commit changes only tests. The fresh merge includes openclaw#145343, openclaw#147139, and openclaw#147394. Its selected suites pass 160 distinct tests, with 250 executions due to configuration overlap, plus 165 tests in six additional consumer files. This does not claim a separate fresh execution of the finalizer-silence scenario, browser rendering, or answer quality. Typechecks remain for CI.

CI run [34789473564](https://github.com/openclaw/openclaw/actions/runs/34789473564) completed successfully at `aa2bcb6ebe293c76eb1c715dae9a386da3750dfc`, including the hosted type checks.

Co-authored-by: MasterSwords1 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. 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.

2 participants