Skip to content

fix(compaction): count bashExecution and summary turns in pre-prompt overflow precheck - #97861

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
yetval:fix/preemptive-compaction-bashexec-undercount
Jun 29, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
yetval:fix/preemptive-compaction-bashexec-undercount

Conversation

@yetval

@yetval yetval commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

The pre-prompt overflow precheck silently under-counts bashExecution turns, so a context that holds large !-bash output (a !cat of a big file, build logs, test output) is scored as nearly empty. shouldPreemptivelyCompactBeforePrompt returns route: "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 estimateMessageTokenPressure in src/agents/embedded-agent-runner/run/preemptive-compaction.ts. It special-cases toolResult/tool/assistant and otherwise falls through to tokens += estimateContentTokenPressure(record.content).

A BashExecutionMessage stores its payload in command/output and has no content field (packages/agent-core/src/types.ts), so record.content is undefined and the estimator returns 0. 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 call convertToLlm, so bashExecution reaches the gate raw. The actual provider request does expand it via convertToLlm -> bashExecutionToText into command plus the full output as real user text, so the provider sees the tokens the gate scored as ~29.

branchSummary and compactionSummary hit the same defect at lower magnitude: their payload is in a summary field, not content, so they too scored as bare overhead.

before:

  tokens += estimateContentTokenPressure(record.content);
  return tokens;

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 remainingPromptBudgetTokens is now correct for these sessions.

Evidence

Fix: estimate each affected role from the exact text convertToLlm renders for the provider.

after:

  if (record.role === "bashExecution") {
    if (record.excludeFromContext === true) {
      return 0;
    }
    tokens += estimateStringTokenPressure(
      bashExecutionToText(record as unknown as BashExecutionMessage),
    );
    return tokens;
  }

  if (record.role === "branchSummary") {
    const summary = typeof record.summary === "string" ? record.summary : "";
    tokens += estimateStringTokenPressure(BRANCH_SUMMARY_PREFIX + summary + BRANCH_SUMMARY_SUFFIX);
    return tokens;
  }

  if (record.role === "compactionSummary") {
    const summary = typeof record.summary === "string" ? record.summary : "";
    tokens += estimateStringTokenPressure(
      COMPACTION_SUMMARY_PREFIX + summary + COMPACTION_SUMMARY_SUFFIX,
    );
    return tokens;
  }

excludeFromContext bash records return 0 because convertToLlm drops them from the provider request entirely.

Why this is the right boundary

The estimate must reflect what the provider actually receives. convertToLlm is 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 existing content/toolResult/assistant branches 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, route fits).
  • 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.json and -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, and convertToLlm on pristine main 1052652 and on the patched tree with an identical two-message session (one user message plus one bashExecution turn 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 convertToLlm to measure the provider-rendered token size, then called estimateLlmBoundaryTokenPressure and shouldPreemptivelyCompactBeforePrompt on the same session and printed their fields.
Evidence after fix:

# BEFORE (pristine main 1052652a71)
provider_tokens_in_request    = 337507
precheck_estimated_tokens     = 59
decision.route                = fits
decision.shouldCompact        = false
decision.overflowTokens       = 0
decision.estimatedPromptTokens= 59
# AFTER (this patch, identical inputs)
provider_tokens_in_request    = 337507
precheck_estimated_tokens     = 405068
decision.route                = compact_only
decision.shouldCompact        = true
decision.overflowTokens       = 293452
decision.estimatedPromptTokens= 405068

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.

…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.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jun 29, 2026
@clawsweeper

clawsweeper Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 29, 2026, 12:18 PM ET / 16:18 UTC.

Summary
The PR updates preemptive compaction token estimation to count bashExecution, branchSummary, and compactionSummary provider-rendered text, and adds focused regression tests.

PR surface: Source +31, Tests +85. Total +116 across 2 files.

Reproducibility: yes. Source inspection shows current main estimates these roles from record.content while provider conversion renders command/output and summary; the PR body also includes before/after live output from the real exported helpers.

Review metrics: none identified.

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Next step before merge

  • No repair lane is needed; the PR has no concrete automated follow-up beyond normal maintainer review and CI gates.

Security
Cleared: The diff only changes internal TypeScript token-estimation logic plus colocated tests, with no dependency, workflow, secret, or supply-chain surface added.

Review details

Best 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 record.content while provider conversion renders command/output and summary; the PR body also includes before/after live output from the real exported helpers.

Is this the best way to solve the issue?

Yes. The best local fix is to estimate the same provider-rendered text that convertToLlm sends, rather than moving the whole precheck to a broader conversion path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 6de357ad4772.

Label changes

Label justifications:

  • P2: The PR fixes a real agent-runtime overflow precheck bug with limited but user-visible impact in bash-heavy or summary-bearing sessions.
  • 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. Sufficient (live_output): The PR body includes copied before/after live output from the real exported estimator, router, and provider conversion helpers on identical inputs.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes copied before/after live output from the real exported estimator, router, and provider conversion helpers on identical inputs.
Evidence reviewed

PR surface:

Source +31, Tests +85. Total +116 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 32 1 +31
Tests 1 85 0 +85
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 117 1 +116

What I checked:

Likely related people:

  • fuller-stack-dev: Authored merged work that added context-pressure preflight handling for tool-heavy sessions on the predecessor embedded-runner path. (role: introduced related preflight behavior; confidence: medium; commits: 2962db32fea7; files: src/agents/pi-embedded-runner/run/preemptive-compaction.ts, src/agents/pi-embedded-runner/run/preemptive-compaction.test.ts)
  • yetval: Authored a recently merged compaction token-accounting fix for image-heavy sessions, and this PR is another focused token-estimator correction. (role: recent area contributor; confidence: high; commits: c0639098dd69, c68993e94656; files: packages/agent-core/src/harness/compaction/compaction.ts, src/agents/embedded-agent-runner/run/preemptive-compaction.ts)
  • vincentkoc: Recent history shows refactors around the preemptive compaction route and merges of adjacent token-estimation fixes. (role: recent area contributor and merger; confidence: medium; commits: ff49b7fab106, 18aa3276554c, c0639098dd69; files: src/agents/embedded-agent-runner/run/preemptive-compaction.ts, packages/agent-core/src/harness/compaction/compaction.ts, src/utils/cjk-chars.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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

@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. P2 Normal backlog priority with limited blast radius. labels Jun 29, 2026
@vincentkoc
vincentkoc merged commit 24626e5 into openclaw:main Jun 29, 2026
141 of 147 checks passed
Rorqualx pushed a commit to Rorqualx/cortex that referenced this pull request Jun 29, 2026
…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)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jun 30, 2026
…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.
vincentkoc pushed a commit that referenced this pull request Jul 1, 2026
…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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 1, 2026
…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
chenyangjun-xy pushed a commit to chenyangjun-xy/openclaw that referenced this pull request Jul 1, 2026
…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.
chenyangjun-xy pushed a commit to chenyangjun-xy/openclaw that referenced this pull request Jul 1, 2026
…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
ly-wang19 added a commit to ly-wang19/openclaw that referenced this pull request Jul 1, 2026
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.
wheakerd pushed a commit to wheakerd/clawdbot that referenced this pull request Jul 15, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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