Skip to content

fix(agents): avoid oversized raw history in final answers - #186288

Merged
obviyus merged 4 commits into
openclaw:mainfrom
ericcaiwx-star:codex/186244-assembled-finalization-history
Oct 28, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
ericcaiwx-star:codex/186244-assembled-finalization-history

Conversation

@ericcaiwx-star

@ericcaiwx-star ericcaiwx-star commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Isolated post-tool finalization reopened raw session history even when the selected context engine had already excluded that history from the source attempt. A short final answer could therefore send a much larger conversation to the provider.

Fixes #186244. Already-delivered-message admission is tracked separately in #179003 and is outside this repair, as confirmed by the maintainer.

Why This Change Was Made

The restricted built-in adapter passes the frozen settled model view through a host-private parameter. It uses the explicit OpenClaw transcript capture when present, otherwise the canonical settled messagesSnapshot; an explicitly unavailable or foreign-harness projection is refused.

The existing prepareEmbeddedAttemptHistory owner selects this view instead of rehydrated raw history and reuses the existing session byte/event window and tool-result omission policy. An empty selected view also replaces the hydrated messages. The original SessionManager retains all transcript writes and receipts.

The finalizer still receives no live context engine. Its bootstrap, maintenance, ingestion, afterTurn hooks, ambient prompt contributors, tools and trajectory capabilities are not restored. Empty-finalizer retries reuse the original settled view. This adds no config/env/schema or public SDK capability and introduces no new current-turn boundary inference.

User Impact

Excluded old history stays out of the isolated finalization request while the current request, completed tool evidence and selected summary remain available. Durable history is retained. Finalization remains tool-free, and interrupted work cannot be completed by replaying tools during this step.

Evidence

Refreshed main integration

Merged main 342da13c92e0af1add7936f9bc479394f01e426c into the latest contributor head, producing a8cad32e618122fbe474a5102890fe34e5fc9b57. The history owner preserves both main's Anthropic turn-scoped system-update clearing and the frozen selected-view snapshot. Fresh built-Gateway proof measured one finalizer request per ref: 52,085 bytes on main (excluded raw canary restored) versus 2,490 bytes on the merged candidate (summary and current write receipt retained, canary absent). Both turns completed successfully, offered zero finalizer tools, and added no engine lifecycle calls. The 11 finalization tests and 8 upstream bounded-context tests passed again, with focused lint/formatting. Test-line growth remains zero.

Independent current-main comparison

Independent built-Gateway evidence compares current main 4b27ee88cec9a78377a04b2e3a352ba7c503450e twice with the candidate production code twice, plus normal-finalization controls on both revisions. Isolated finalizer requests measured 52,100 bytes on main in both runs versus 2,505 bytes on the candidate in both runs. Main restored the excluded raw canary; the candidate retained the selected summary and current write receipt without the canary. Every isolated finalizer offered zero tools and left context-engine lifecycle counters unchanged. All six measured turns completed successfully. The latest contributor head changes only tests and passed both changed suites (11 tests), focused lint and formatting. Whole-PR test-line delta is zero, without a ceiling change.

Contributor's earlier proof

Named base: 63ba4974f67c1eba483f8b7121c2bf7416d75ae4.

Candidate: a037f29b1bad9717aca3a3db9559b941534e4efd.

Real built CLI/Gateway proof on Linux

Both revisions completed frozen dependency installation and full builds. Final candidate full build exited 0 in 3m2.2s; the actual built CLI reported OpenClaw 2026.10.7 (a037f29).

The primary fixture uses a real Gateway, sessions.create, two agent CLI turns and an actual committed write to a task-owned file. Its HTTP/SSE Responses provider and context-engine plugin are synthetic local fixtures. The empty post-tool answer really enters isolated finalization; the finalizer offers zero tools. A plain read-only continuation is not used as a substitute for that admission.

  • Base: ordinary request excluded the old canary, but isolated finalization restored it: 50,786 versus 82,564 reserialized JSON bytes. ocpr prove --phase pre recorded command exit 1, with successful tool commit and clean Gateway shutdown.
  • Candidate primary: ordinary request 50,793 bytes; finalizer 1,745 bytes. Old canary absent from provider input, current write evidence retained, visible/history answer present, and old raw canary still present in durable history.
  • Additional positive scenario: a non-empty engine-selected summary survives ordinary and isolated requests; finalizer 1,880 bytes. Primary lifecycle counts remain assemble=5, commitTurn=2, maintain=3, bootstrap=1, with no finalizer engine callbacks.
  • Both scenarios confirm an active subsequent turn through real chat.abort, omit its cancelled output, preserve the committed write, and close cleanly. The cancelled CLI exits 1 as expected for this cancellation control; each proof driver exits 0 only after the positive cancellation and cleanup assertions.
  • Persisted-state compatibility: copy the cleanly closed named-base managed SQLite state, reopen it with candidate built CLI/Doctor/Gateway, and complete a new ordinary turn on that existing session. Old/new answers and the old actual write survive; the original baseline database hashes remain unchanged. This is named-base-to-candidate state compatibility, not a stable-release installer/version upgrade claim.

Exact commands executed by ocpr:

node bin/ocpr prove 186244 --phase pre --sha 63ba4974f67c1eba483f8b7121c2bf7416d75ae4 --cmd "python3 /tmp/oc-186244-runtime-access/formal-entry.py --sha 63ba4974f67c1eba483f8b7121c2bf7416d75ae4 --root /tmp/oc-186244-entry-formal-pre-1 --port 19981"
node bin/ocpr prove 186244 --phase post --sha a037f29b1bad9717aca3a3db9559b941534e4efd --cmd "python3 /tmp/oc-186244-runtime-access/186244-proof-suite.py --sha a037f29b1bad9717aca3a3db9559b941534e4efd --label 2"
Actual captured post-proof stdout
PROOF_SUBCASE 1 COMMAND ["python3", "/tmp/oc-186244-runtime-access/186244-formal-post-entry.py", "--sha", "a037f29b1bad9717aca3a3db9559b941534e4efd", "--root", "/tmp/oc-186244-entry-formal-post-2", "--port", "19982"]
{"sha": "a037f29b1bad9717aca3a3db9559b941534e4efd", "scope": "actual built Gateway + managed session + synthetic local Responses provider + synthetic bounded context engine; no live Discord/lossless-claw/OAuth or reporter token-price claim", "builtCLI": "OpenClaw 2026.10.7 (a037f29)", "sessionKey": "agent:main:proof186244-cabb06b2d2c94a1fa0ecaa4bdc328642", "actualWriteCommitted": true, "normalInputBytes": 50793, "finalizerInputBytes": 1745, "normalOldNoiseAbsent": true, "finalizerRawNoisePresent": false, "finalizerWriteEvidencePresent": true, "finalizerToolsDisabled": true, "visibleAnswer": true, "historyAnswer": true, "historyRawCanaryPreserved": true, "engineMetrics": [{"kind": "assemble", "inputMessages": 0, "selectedMessages": 0, "inputBytes": 2, "selectedBytes": 2, "tokenBudget": 75543}, {"kind": "assemble", "inputMessages": 0, "selectedMessages": 0, "inputBytes": 2, "selectedBytes": 2, "tokenBudget": 56083}, {"kind": "commitTurn"}, {"kind": "maintain"}, {"kind": "bootstrap"}, {"kind": "maintain"}, {"kind": "assemble", "inputMessages": 3, "selectedMessages": 0, "inputBytes": 162457, "selectedBytes": 2, "tokenBudget": 99525}, {"kind": "assemble", "inputMessages": 0, "selectedMessages": 0, "inputBytes": 2, "selectedBytes": 2, "tokenBudget": 76068}, {"kind": "assemble", "inputMessages": 0, "selectedMessages": 0, "inputBytes": 2, "selectedBytes": 2, "tokenBudget": 75943}, {"kind": "commitTurn"}, {"kind": "maintain"}], "productRed": false, "primaryEngineLifecycleCounts": {"assemble": 5, "commitTurn": 2, "maintain": 3, "bootstrap": 1}, "primaryRequests": 4, "primaryAuxRequests": 2, "productFixed": true, "cancelCliExit": 1, "activeCancelConfirmed": true, "cancelledOutputAbsent": true, "writePreservedAfterCancel": true, "requests": 5, "auxRequests": 3, "failures": [], "cancelWaiting": true, "cancelTransportClosed": true, "gatewayExit": 0, "portClosed": true, "shutdownClean": true}
PROOF_SUBCASE 1 EXIT 0
PROOF_SUBCASE 2 COMMAND ["python3", "/tmp/oc-186244-runtime-access/186244-formal-summary-entry.py", "--expect", "post", "--sha", "a037f29b1bad9717aca3a3db9559b941534e4efd", "--root", "/tmp/oc-186244-entry-summary-post-2", "--port", "19983"]
{"sha": "a037f29b1bad9717aca3a3db9559b941534e4efd", "scope": "actual built Gateway + managed session + synthetic local Responses provider + synthetic bounded context engine; no live Discord/lossless-claw/OAuth or reporter token-price claim", "builtCLI": "OpenClaw 2026.10.7 (a037f29)", "sessionKey": "agent:main:proof186244-1f205487b5084ad19275802647ac127c", "actualWriteCommitted": true, "normalInputBytes": 50960, "finalizerInputBytes": 1880, "normalOldNoiseAbsent": true, "finalizerRawNoisePresent": false, "finalizerWriteEvidencePresent": true, "finalizerToolsDisabled": true, "visibleAnswer": true, "historyAnswer": true, "historyRawCanaryPreserved": true, "engineMetrics": [{"kind": "assemble", "inputMessages": 0, "selectedMessages": 1, "inputBytes": 2, "selectedBytes": 91, "tokenBudget": 75542}, {"kind": "assemble", "inputMessages": 1, "selectedMessages": 1, "inputBytes": 91, "selectedBytes": 91, "tokenBudget": 56082}, {"kind": "commitTurn"}, {"kind": "maintain"}, {"kind": "bootstrap"}, {"kind": "maintain"}, {"kind": "assemble", "inputMessages": 3, "selectedMessages": 1, "inputBytes": 162457, "selectedBytes": 91, "tokenBudget": 99524}, {"kind": "assemble", "inputMessages": 1, "selectedMessages": 1, "inputBytes": 91, "selectedBytes": 91, "tokenBudget": 76067}, {"kind": "assemble", "inputMessages": 1, "selectedMessages": 1, "inputBytes": 91, "selectedBytes": 91, "tokenBudget": 75941}, {"kind": "commitTurn"}, {"kind": "maintain"}], "productRed": false, "ordinaryAssemblySummaryPresent": true, "finalizerAssemblySummaryPresent": true, "primaryEngineLifecycleCounts": {"assemble": 5, "commitTurn": 2, "maintain": 3, "bootstrap": 1}, "primaryRequests": 4, "primaryAuxRequests": 2, "productFixed": true, "cancelCliExit": 1, "activeCancelConfirmed": true, "cancelledOutputAbsent": true, "writePreservedAfterCancel": true, "requests": 5, "auxRequests": 3, "failures": [], "cancelWaiting": true, "cancelTransportClosed": true, "gatewayExit": 0, "portClosed": true, "shutdownClean": true}
PROOF_SUBCASE 2 EXIT 0
PROOF_SUBCASE 3 COMMAND ["python3", "/tmp/oc-186244-runtime-access/186244-base-state-compat.py", "--sha", "a037f29b1bad9717aca3a3db9559b941534e4efd", "--root", "/tmp/oc-186244-entry-compat-2", "--port", "19984"]
{"sha": "a037f29b1bad9717aca3a3db9559b941534e4efd", "baseSha": "63ba4974f67c1eba483f8b7121c2bf7416d75ae4", "scope": "actual named-base managed SQLite state copied after clean shutdown, reopened by exact candidate built CLI/Doctor/Gateway and ordinary model turn; no stable-release install/version upgrade or live channel claim", "builtCLI": "OpenClaw 2026.10.7 (a037f29)", "doctorExit": 0, "oldCommittedAnswerPresent": true, "newTurnVisibleAndPersisted": true, "oldWritePreserved": true, "ordinaryOldNoiseAbsent": true, "gatewayExit": 0, "primaryRequests": 1, "auxRequests": 1, "failures": [], "portClosed": true, "shutdownClean": true, "originalBaselineDbUnchanged": true}
PROOF_SUBCASE 3 EXIT 0
EXACT_HEAD_SUITE_PASS a037f29b1bad9717aca3a3db9559b941534e4efd

These byte counts use consistent JSON reserialization, not provider token accounting or billing. Provider usage values are synthetic. No real Discord, lossless-claw, OAuth, token-price or cache-savings acceptance is claimed. All three Gateways exited 0, closed their ports and reported clean shutdown; no Docker was used.

Regression, checks and independent review

The existing detached finalization regression failed on pre-fix code because omitted history reappeared in the finalizer. It now preserves tool receipts and the original transcript manager across empty retries. Earlier oversized-precheck and unclosed-user-turn fixture failures were separately classified and retained; they are not claimed as the product regression.

The implementation candidate passed 84 tests in eight relevant files (77.15s), including screenshot-heavy bounded current-request history, length/incomplete outcomes, unavailable context, delivery, silence, transport, detached custody and empty retries. The final test-only consolidation was rerun on this exact head: 46 tests in both changed suites plus the required runner sibling, three shards, exit 0 (26.05s). Changed-test lint and all core-test type shards passed; the production files are byte-identical to the previously reviewed and proven implementation.

The first Ready CI run 40600657717 exposed a test-line budget failure: the merge tree was already above the ceiling and this PR added 52 test lines. The final commit consolidates duplicate setup in the same two existing suites, shares source-view acceptance/rejection cases, and retains callback custody, frozen context, both transient-failure admission cases, receipt contents across empty retries, hidden prompts and subsequent real-user persistence. The complete PR now has zero net test-line growth. No baseline, config, ignore or formatter policy was changed. That first CI result remains a failure; the latest head's CI gate now passes.

The complete changed-file command exits 1 only on two global dead-export failures: extensions/knowledge/src/scribes-catalog.ts: runPrompt and ui/src/pages/activity/activity-page.test-support.ts: settleActivity. The same dead-export command was actually run on the exact named base and failed on the identical two exports. Those unrelated files were not changed; the full command is not reported green.

Canonical independent AutoReview of the exact candidate, pinned base, P0–P2, completed scoped-clean with no actionable findings (Codex gpt-6.1-sol, no fallback). It included the complete bounded selector, limits, snapshot/capture owners, finalization caller and harness lifecycle/selection contracts. Runtime proof above is separate from that review.

Exact-head hosted gates

Refreshed head a8cad32e618122fbe474a5102890fe34e5fc9b57 has a successful CI gate and exact-head ClawSweeper review: overall readiness 5/6, proof confidence 5/6, patch quality 5/6, no actionable findings. No failing jobs remain; one auxiliary auto-response job was cancelled.

Merge Risk

Two-way door: reverting restores the old finalization-context selection without a schema or persisted-format change. Blast radius is the built-in OpenClaw runtime's isolated post-tool final answers; an incorrect selection could omit necessary settled context or restore excluded history. Ordinary finalization, context-engine lifecycle ownership and durable transcript writes remain unchanged.

@clawsweeper

clawsweeper Bot commented Oct 27, 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-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes isolated final answers reuse the settled engine-selected conversation instead of reopening raw history.

Example: A completed workspace write receives an empty assistant response and triggers isolated finalization.

  • Before: The finalizer sends 52,085 bytes, including old history excluded by the context engine.
  • After: The finalizer sends 2,490 bytes, retaining the selected summary and write receipt with zero tools.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-approved repair with shipped Gateway proof, retained regression contracts, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The reviewed head was exercised through rebuilt Linux Gateways with real session RPCs, a committed workspace write, an empty post-tool response, a synthetic selected context engine, and a recording SSE provider; captured finalizer requests retain the summary and receipt while excluding raw canary history, offering zero tools, and adding no engine lifecycle calls.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A short recovery answer can unexpectedly resend large amounts of excluded conversation history and consume provider quota.
Reason: The maintainer approved this bounded-context repair and its separation from delivery admission; source and Gateway evidence support the user benefit.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a confirmed finalization-context bug with no actionable findings; current-head CI remains pending.

Priority: P1
Reviewed head: a8cad32e618122fbe474a5102890fe34e5fc9b57

Before merge

None.

Findings

None.

Agent review details

How this fits together

The built-in agent harness passes settled conversation context to embedded history preparation, which bounds and sanitizes the tool-free provider request while the original session manager retains transcript writes.

flowchart LR
 A[Engine selected conversation] --> B[Settled attempt snapshot]
 B --> C[Restricted finalization adapter]
 C --> D[Existing history preparation]
 D --> E[Tool free provider request]
 E --> F[Final answer]
 G[Original session manager] --> F
Loading

Technical review

Best possible solution:

Land the frozen-view handoff through the existing history owner once the reviewed head satisfies its normal CI gates.

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

Supplied built-Gateway comparisons reproduce excluded history returning on main and disappearing on the candidate through actual isolated finalization; this review executed no target code.

Is this the best way to solve the issue?

The smallest complete repair transports the existing frozen selected view to history preparation, preserving its bounds and transcript custody without restoring the live engine or introducing a second context owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 41b50b4dbcba.

Provenance checked

  • Restricted built-in finalization keeps the original intent (6eea20c: Finalize settled work through an isolated capability-free request without replaying completed effects.)
  • History preparation ownership keeps the original intent (cbcc1df: Keep history preparation separate while carrying canonical prepared attempt state through execution and recovery.)
  • Detached transcript custody keeps the original intent (8f924bf: Retain the receipt-bearing session manager across finalization and preserve hidden recovery prompts.)
  • Existing finalization tests keeps the original intent (test(core,plugins,ui): remove low-value tests (batch d605) #184459: Remove duplicate setup and low-value assertions while retaining distinct lifecycle and persistence contracts.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 8f924bf adds src/agents/harness/builtin-openclaw.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8f924bff5d68; files: src/agents/harness/builtin-openclaw.ts)

PR surface

Source +60, Tests 0. Total +60 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 65 5 +60
Tests 2 104 104 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 169 109 +60

Review metrics

Metric Value Why it matters
Production versus test LOC Production +65/-5; tests +104/-104 Production growth carries the private selected view and adapts it to the existing bounded selector; regression coverage is consolidated without net test growth.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The confirmed recovery-path bug restores excluded historical context and can consume substantial provider quota during active agent workflows.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-27T21:03:31.085Z sha c665be2 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-27T23:08:08.159Z sha f616ee3 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-27T23:56:30.204Z sha a037f29 :: needs maintainer review before merge. :: none

Reviewed October 27, 2026, 8:14 PM ET / October 28, 2026, 00:14 UTC (Revision 4).

@steipete

Copy link
Copy Markdown
Contributor

Thanks @ericcaiwx-star for picking up #186244. We had started on the same defect and stopped once we saw this draft, so this is yours. A few findings from our source audit that may save you a round:

  • Forwarding the selected context engine into the whole isolated finalizer is not safe as-is. The second attempt would then run engine bootstrap/maintenance (attempt-session-prepare.ts), install the mid-loop ingestion/afterTurn hook (attempt-setup.ts, tool-result-context-guard.ts), and repeat terminal ingestion/afterTurn/maintenance (attempt-finalize.ts). Reusing the already engine-assembled settled snapshot through the existing history-preparation owner, as this PR proposes, avoids all of that. If you do assemble fresh instead, keep the engine out of the finalizer lifecycle and expose it only at assembly, and skip ambient memory prompt preparation and engine system additions.
  • The exact current-turn split is already recorded by the prompt owner (attempt-prompt-build.ts) and carried with the settled model snapshot. Please don't infer it from the last user text or a tool-call ID. Compaction can invalidate that count; the usage-snapshot owner already treats it as unreliable after compaction, so the finalizer should too. Empty-finalizer retries should reuse the original bounded view rather than re-reading raw history.
  • A useful proof shape: a minimal synthetic context-engine plugin that keeps long raw history but assembles only one short summary plus the current settled receipts, a recording OpenAI-compatible provider that returns a harmless read and then an empty final (forcing isolated finalization), and lifecycle counters for assemble/bootstrap/maintain/ingest/afterTurn. Base should leak old canary text into the finalization request; the fix should send the bounded summary plus the current receipt, offer zero tools, and leave the lifecycle counters unchanged. Note that a plain read-only flow often ends in an ordinary tool-enabled continuation and never reaches isolated finalization, so check that the captured request really is the finalizer before drawing conclusions.

The already-delivered-message admission question in the issue is tracked separately in #179003 and doesn't need to be solved here.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M and removed size: XS labels Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The implementation and exact-head Linux Gateway proof, lifecycle/cancellation controls, and persisted-session compatibility evidence are now in the PR body for f616ee3a246c95c0d44521687495ab828a880516. Canonical independent P0–P2 review is scoped-clean. Already-delivered-message admission remains tracked separately in #179003, per the maintainer's scope clarification.

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 27, 2026
@ericcaiwx-star
ericcaiwx-star marked this pull request as ready for review October 27, 2026 23:13

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head a037f29b1bad9717aca3a3db9559b941534e4efd consolidates the same two existing test suites to zero net test-line growth after the first Ready CI exposed the budget failure. Production files are unchanged. The PR body now includes fresh exact-head full Linux build and all three real Gateway/summary/cancellation/persisted-session proof results, plus complete-context independent P0–P2 review with no findings. Current-head full CI is running at https://github.com/openclaw/openclaw/actions/runs/40604414302; it is not yet claimed passed. The repair still excludes the separate admission issue #179003.

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Independent current-main Gateway proof

Rechecked against main 4b27ee88cec9a78377a04b2e3a352ba7c503450e and PR production code at f616ee3a246c95c0d44521687495ab828a880516. The contributor's new head a037f29b1bad9717aca3a3db9559b941534e4efd changes only the two existing test files; those latest tests were adopted and validated separately.

The experiment used built Gateways in secretless Linux/Node 24.22.1 isolation, real sessions.create, chat.send, and agent.wait RPCs, a selected synthetic context engine, and a recording local Chat Completions SSE provider. Each session first saved about 48 KB of synthetic raw canary history. The next turn performed a real write to a task-owned workspace file and received an empty post-tool answer, forcing the isolated finalizer. Using a write is intentional: a plain read can admit an ordinary tool-enabled continuation instead.

Case Finalizer request JSON bytes Old raw canary Selected summary Current write receipt Offered tools
Main, run 1 52,100 present absent present 0
Main, run 2 52,100 present absent present 0
Candidate, run 1 2,505 absent present present 0
Candidate, run 2 2,505 absent present present 0

Both source requests excluded the old canary before finalization. Lifecycle records were unchanged between each settled tool-result request and its actual isolated-finalizer request: no extra bootstrap, maintenance, assemble, ingestion, afterTurn, or commitTurn calls. Auxiliary activity-summary requests were distinguished from finalizers by their system-role metadata prompt and were not counted in the table.

Normal-finalization controls on both revisions returned a visible answer directly after the write, retained the selected summary/current receipt, omitted the old canary, and never entered isolated finalization. All six measured turns completed with agent.wait status ok; each retained the two real user inputs and the answer in chat.history.

Maintainer audit points: the fix transports the frozen settled view, not the live engine; it adds no heuristic current-turn split or assembly lifecycle; the existing history owner applies its normal byte/event and tool-result bounds. The detached regression covers reusing the original view across an empty finalizer retry. Compaction remains under the existing snapshot/capture owner's rules. Already-delivered-message admission (#179003) stays out of scope.

Latest contributor head passed the two changed suites (11 tests across two routed shards), focused Oxlint, and Oxfmt in isolation. The retained selected-view regression failed on main because excluded history reappeared. Whole-PR delta: production +65/-5 (net +60), tests +104/-104 (net 0); no ceiling or baseline changed. The contributor independently supplied the same test-line repair while this experiment was running, so no redundant cleanup commit was added.

These are measured HTTP request bytes, not real-provider token usage or billing. Fixtures are synthetic; no live channel, OAuth, or third-party context-engine deployment claim is made.

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Refreshed main integration and Gateway proof

Merged current main 342da13c92e0af1add7936f9bc479394f01e426c into the latest contributor head a037f29b1bad9717aca3a3db9559b941534e4efd, producing a8cad32e618122fbe474a5102890fe34e5fc9b57.

The history owner merged cleanly. Both responsibilities remain: main's clearsTurnScopedSystemUpdates setting for Anthropic in-history updates (#186304), and this PR's bounded frozen selected-view input for isolated finalization. No current-turn inference, live-engine forwarding, or storage-owner change was introduced.

Rebuilt both refs in secretless Linux/Node 24.22.1 isolation and ran one fresh real built-Gateway turn per ref with the selected context-engine fixture, committed workspace write, empty post-tool answer and recording SSE provider:

Ref Isolated finalizer JSON bytes Old raw canary Selected summary Current write receipt Tools
Current main 52,085 present absent present 0
Merged candidate 2,490 absent present present 0

Both turns completed with agent.wait status ok, retained both user inputs, and added no context-engine lifecycle calls between the settled receipt request and isolated finalizer request. Counts are captured request bytes, not provider billing or token estimates.

The two focused finalization suites passed again (11 tests), as did main's bounded-context owner suite (8 tests), including cleared Anthropic runtime-context/prompt-update accounting. Focused lint and formatting passed. The PR still has zero net test-line growth and no ceiling change.

@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 1714e20 into openclaw:main Oct 28, 2026
129 of 130 checks passed
@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Landed in 1714e20. Thanks @ericcaiwx-star. Isolated final answers now use the context engine's selected view.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…86288)

fix(agents): use the context engine's selected view for isolated final answers

Isolated final-answer finalization rebuilt the request from the raw session history instead of the view the context engine had selected, so the finalizer request restored history the engine had excluded and could grow very large. Finalization now uses a private, frozen snapshot of the engine-selected view.

Evidence: built Gateway turns where the context engine excluded history and finalization ran isolated. On main the finalizer request was about 52 KB and contained the excluded raw history (three runs); with this change it was about 2.5 KB with the engine-selected summary and the current write receipt, and no excluded history (three runs, including on the head merged with current main). Finalizers offered no tools and added no context-engine lifecycle calls, and normal finalization works on both refs. Details: openclaw#186288 (comment). Production +65/-5.

Thanks @ericcaiwx-star.

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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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.

[Bug]: Isolated finalization after message-tool reply bypasses context engine and sends ~850k uncached tokens from raw history

3 participants