Repository navigation
fix(compaction): count bashExecution and summary turns in pre-prompt overflow precheck - #97861
Conversation
…overflow precheck estimateMessageTokenPressure special-cased toolResult, tool, and assistant roles and otherwise read record.content. bashExecution stores its payload in command/output and branchSummary/compactionSummary store theirs in summary, so record.content was undefined and those turns scored as bare boundary overhead. The provider request expands them via convertToLlm into full user text, so bash-heavy sessions skipped the preflight overflow gate and submitted oversized prompts. Estimate each affected role from the exact text convertToLlm renders: bashExecutionToText for bash turns (zero for excludeFromContext records, which convertToLlm drops), and the summary prefix/suffix plus summary text for the two summary roles.
|
Codex review: needs maintainer review before merge. Reviewed June 29, 2026, 12:18 PM ET / 16:18 UTC. Summary PR surface: Source +31, Tests +85. Total +116 across 2 files. Reproducibility: yes. Source inspection shows current main estimates these roles from Review metrics: none identified. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Next step before merge
Security Review detailsBest possible solution: Land the focused estimator and regression-test fix after normal maintainer and CI gates, keeping provider-rendered text as the token-accounting contract. Do we have a high-confidence way to reproduce the issue? Yes. Source inspection shows current main estimates these roles from Is this the best way to solve the issue? Yes. The best local fix is to estimate the same provider-rendered text that AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 6de357ad4772. Label changesLabel justifications:
Evidence reviewedPR surface: Source +31, Tests +85. Total +116 across 2 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
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. How this review workflow works
|
…overflow precheck (openclaw#97861) estimateMessageTokenPressure special-cased toolResult, tool, and assistant roles and otherwise read record.content. bashExecution stores its payload in command/output and branchSummary/compactionSummary store theirs in summary, so record.content was undefined and those turns scored as bare boundary overhead. The provider request expands them via convertToLlm into full user text, so bash-heavy sessions skipped the preflight overflow gate and submitted oversized prompts. Estimate each affected role from the exact text convertToLlm renders: bashExecutionToText for bash turns (zero for excludeFromContext records, which convertToLlm drops), and the summary prefix/suffix plus summary text for the two summary roles. (cherry picked from commit 24626e5)
…overflow precheck (openclaw#97861) estimateMessageTokenPressure special-cased toolResult, tool, and assistant roles and otherwise read record.content. bashExecution stores its payload in command/output and branchSummary/compactionSummary store theirs in summary, so record.content was undefined and those turns scored as bare boundary overhead. The provider request expands them via convertToLlm into full user text, so bash-heavy sessions skipped the preflight overflow gate and submitted oversized prompts. Estimate each affected role from the exact text convertToLlm renders: bashExecutionToText for bash turns (zero for excludeFromContext records, which convertToLlm drops), and the summary prefix/suffix plus summary text for the two summary roles.
…tor (#97928) The in-loop context-overflow guard (installToolResultContextGuard) sizes transcript messages via estimateMessageChars, which only handled user, assistant, and toolResult roles. Harness roles (bashExecution, compactionSummary, branchSummary, custom) fell through to a flat 256-char return, causing the guard to undercount summary- and bash-dominated context by orders of magnitude. This is the sibling defect of the just-merged #97861 which fixed the same class in estimateMessageTokenPressure (the pre-prompt precheck). This commit applies the identical pattern to the live in-loop guard estimator. Fixes #97927
…tor (openclaw#97928) The in-loop context-overflow guard (installToolResultContextGuard) sizes transcript messages via estimateMessageChars, which only handled user, assistant, and toolResult roles. Harness roles (bashExecution, compactionSummary, branchSummary, custom) fell through to a flat 256-char return, causing the guard to undercount summary- and bash-dominated context by orders of magnitude. This is the sibling defect of the just-merged openclaw#97861 which fixed the same class in estimateMessageTokenPressure (the pre-prompt precheck). This commit applies the identical pattern to the live in-loop guard estimator. Fixes openclaw#97927
…overflow precheck (openclaw#97861) estimateMessageTokenPressure special-cased toolResult, tool, and assistant roles and otherwise read record.content. bashExecution stores its payload in command/output and branchSummary/compactionSummary store theirs in summary, so record.content was undefined and those turns scored as bare boundary overhead. The provider request expands them via convertToLlm into full user text, so bash-heavy sessions skipped the preflight overflow gate and submitted oversized prompts. Estimate each affected role from the exact text convertToLlm renders: bashExecutionToText for bash turns (zero for excludeFromContext records, which convertToLlm drops), and the summary prefix/suffix plus summary text for the two summary roles.
…tor (openclaw#97928) The in-loop context-overflow guard (installToolResultContextGuard) sizes transcript messages via estimateMessageChars, which only handled user, assistant, and toolResult roles. Harness roles (bashExecution, compactionSummary, branchSummary, custom) fell through to a flat 256-char return, causing the guard to undercount summary- and bash-dominated context by orders of magnitude. This is the sibling defect of the just-merged openclaw#97861 which fixed the same class in estimateMessageTokenPressure (the pre-prompt precheck). This commit applies the identical pattern to the live in-loop guard estimator. Fixes openclaw#97927
The in-loop context-overflow guard sizes each transcript message with estimateMessageChars, which special-cased only user/assistant/toolResult and returned a flat 256 for everything else. bashExecution, compactionSummary, branchSummary, and custom records all expand into full-text user messages via convertToLlm, so the guard undercounted summary- and bash-dominated transcripts and never tripped its last-resort overflow protection for them. Mirror the twin fix from openclaw#97861 (estimateMessageTokenPressure): read the exact text convertToLlm renders — bashExecutionToText for bash records (zero when excludeFromContext drops them) and the summary prefix/suffix plus summary text for the two summary roles. Custom messages render their content field, so use that length directly. Closes openclaw#97927.
…overflow precheck (openclaw#97861) estimateMessageTokenPressure special-cased toolResult, tool, and assistant roles and otherwise read record.content. bashExecution stores its payload in command/output and branchSummary/compactionSummary store theirs in summary, so record.content was undefined and those turns scored as bare boundary overhead. The provider request expands them via convertToLlm into full user text, so bash-heavy sessions skipped the preflight overflow gate and submitted oversized prompts. Estimate each affected role from the exact text convertToLlm renders: bashExecutionToText for bash turns (zero for excludeFromContext records, which convertToLlm drops), and the summary prefix/suffix plus summary text for the two summary roles. (cherry picked from commit 24626e5)
What Problem This Solves
The pre-prompt overflow precheck silently under-counts
bashExecutionturns, so a context that holds large!-bash output (a!catof a big file, build logs, test output) is scored as nearly empty.shouldPreemptivelyCompactBeforePromptreturnsroute: "fits",shouldCompact: false, and the oversized prompt is submitted to the provider, which then rejects it as a context overflow. Bash-heavy sessions skip the very gate meant to keep them under the model limit.The same under-count corrupts the persisted
SessionContextBudgetStatus(remainingPromptBudgetTokens) and the mid-turn tool-result guard, which both consume the same estimate, so the budget a user sees for these sessions is wildly wrong.Why This Change Was Made
Root cause is
estimateMessageTokenPressureinsrc/agents/embedded-agent-runner/run/preemptive-compaction.ts. It special-casestoolResult/tool/assistantand otherwise falls through totokens += estimateContentTokenPressure(record.content).A
BashExecutionMessagestores its payload incommand/outputand has nocontentfield (packages/agent-core/src/types.ts), sorecord.contentisundefinedand the estimator returns0. The whole turn scores as just the boundary overhead (about 29 tokens after the safety margin) no matter how large the output.The precheck runs on
normalizeMessagesForLlmBoundary(...), which does not callconvertToLlm, sobashExecutionreaches the gate raw. The actual provider request does expand it viaconvertToLlm->bashExecutionToTextintocommandplus the full output as real user text, so the provider sees the tokens the gate scored as ~29.branchSummaryandcompactionSummaryhit the same defect at lower magnitude: their payload is in asummaryfield, notcontent, so they too scored as bare overhead.before:
User Impact
Bash-heavy and summary-bearing sessions no longer skip preflight compaction and submit an oversized prompt. The precheck now scores these turns at their true provider-rendered size, so it routes to compaction or tool-result truncation before the request instead of relying on post-overflow recovery (a failed provider round-trip plus latency). The reported
remainingPromptBudgetTokensis now correct for these sessions.Evidence
Fix: estimate each affected role from the exact text
convertToLlmrenders for the provider.after:
excludeFromContextbash records return0becauseconvertToLlmdrops them from the provider request entirely.Why this is the right boundary
The estimate must reflect what the provider actually receives.
convertToLlmis the single function that renders these roles into provider text, so the estimator now reuses its exact renderers (bashExecutionToText, the summary prefix/suffix constants) rather than re-deriving sizes. All three affected roles are fixed in the same change; the remaining roles already route through the existingcontent/toolResult/assistantbranches and are unaffected.Verification
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.bashexec.test.ts- 4 passed with the patch; the bash and summary cases fail on pristine main (estimate 29, routefits).node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts- 16 passed (adjacent suite, no regression).node scripts/run-oxlint.mjs <changed files>- clean.oxfmt --check <changed files>- clean.node scripts/run-tsgo.mjs -p tsconfig.core.jsonand-p test/tsconfig/tsconfig.core.test.json- both clean.Real behavior proof
Behavior addressed: a session holding a large bash turn is scored as nearly empty by the pre-prompt overflow precheck, so it routes "fits" and submits an oversized prompt instead of compacting first.
Real environment tested: drove the real exported
estimateLlmBoundaryTokenPressure,shouldPreemptivelyCompactBeforePrompt, andconvertToLlmon pristine main 1052652 and on the patched tree with an identical two-message session (one user message plus onebashExecutionturn whose output renders to 337,507 provider tokens), under a 128000 context budget with a 16384 reserve. Nothing was mocked; the real estimator, router, and provider-text renderer all ran.Exact steps or command run after this patch: built the session, called
convertToLlmto measure the provider-rendered token size, then calledestimateLlmBoundaryTokenPressureandshouldPreemptivelyCompactBeforePrompton the same session and printed their fields.Evidence after fix:
Observed result after fix: the same 337507-token bash turn that was scored at 59 and waved through as "fits" is now scored at its real rendered size, so the gate reports an overflow of 293452 and routes to compaction before the prompt is submitted.
What was not tested: no live provider request was issued (the provider-side overflow is the documented downstream consequence); the full build was not run because no module/packaging boundary changed.