Skip to content

fix(agents): align mid-turn tool-result projection precheck - #101952

Closed
ZengWen-DT wants to merge 2 commits into
openclaw:mainfrom
ZengWen-DT:fix/101929-midturn-precheck-estimator
Closed

ZengWen-DT wants to merge 2 commits into
openclaw:mainfrom
ZengWen-DT:fix/101929-midturn-precheck-estimator

Conversation

@ZengWen-DT

@ZengWen-DT ZengWen-DT commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Refs #101929

What Problem This Solves

Mid-turn tool-result precheck estimated the raw in-memory tool-result history, while the next provider prompt path sends the post-truncation projection. When accumulated tool results exceed the live aggregate cap, the mid-turn signal can report route/reducible-char facts from a view that the provider-boundary prompt will not actually send.

This PR now addresses only that projection mismatch. It intentionally keeps the existing conservative 2 chars/token tool-result density policy for the normal pre-prompt estimator.

Why This Change Was Made

The mid-turn precheck now projects messages through resolveLiveToolResultAggregateMaxChars and truncateOversizedToolResultsInMessages before calling shouldPreemptivelyCompactBeforePrompt, using the same context-window-based aggregate cap as the provider prompt path. The global estimateLlmBoundaryTokenPressure tool-result density behavior is unchanged.

Risk note: this touches session-state context routing, so the tests cover the structured mid-turn signal, the aggregate-over-cap projection case, and the lower-budget overflow case where the signal must still fire.

User Impact

Tool-heavy agent sessions with history above the provider-boundary tool-result aggregate cap should get mid-turn routing based on the same bounded prompt view used for the next model call. This does not relax token-density safety for ordinary pre-prompt compaction decisions or for tool-result histories below the projection cap.

Evidence

Source/dependency checks:

  • Current OpenClaw source check: the pre-prompt/provider prompt path already calls truncateOversizedToolResultsInMessages before model submission, while the mid-turn precheck previously estimated the raw post-tool transcript.
  • OpenAI Codex dependency source checked locally: codex-rs/codex-api/src/common.rs:209, codex-rs/codex-api/src/common.rs:232, codex-rs/codex-api/src/endpoint/responses_websocket.rs:811, and codex-rs/core/src/client.rs:822, codex-rs/core/src/client.rs:1178, codex-rs/core/src/client.rs:1525, codex-rs/core/src/client.rs:1582. The request builders serialize the supplied input/messages and preserve websocket request fields; there is no hidden expansion that would make the mid-turn raw transcript a better estimator than OpenClaw's provider-boundary projection.

Focused validation:

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
Test Files  2 passed (2)
Tests  69 passed (69)
./node_modules/.bin/oxfmt --check --threads=1 src/agents/embedded-agent-runner/run/preemptive-compaction.ts src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts src/agents/embedded-agent-runner/tool-result-context-guard.ts src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
All matched files use the correct format.

git diff --check
# passed

Review:

.agents/skills/autoreview/scripts/autoreview --mode local --base upstream/main --output /tmp/openclaw-101952-autoreview.txt --json-output /tmp/openclaw-101952-autoreview.json
autoreview clean: no accepted/actionable findings reported
overall: patch is correct (0.78)

Live behavior proof:

OPENCLAW_CONFIG_PATH=<temp>/openclaw.json pnpm openclaw agent --local --json --agent main --session-id issue-101952-live-proof-1783490444 --model deepseek/deepseek-v4-flash --thinking off
OpenClaw 2026.6.11 (b134543)
config: contextTokens=80000; toolResultMaxChars=30000; reserveTokens=0; reserveTokensFloor=0; midTurnPrecheck.enabled=true; aggregateCapChars=160000
requested: 7 turns x 25,000 chars through the real exec tool; persisted session: 8 exec tool results after the mid-turn retry, total tool-result chars 200,480
[agent/embedded] [context-overflow-midturn-precheck] sessionKey=agent:main:explicit:issue-101952-live-proof-1783490444 provider=deepseek/deepseek-v4-flash route=compact_only estimatedPromptTokens=86486 promptBudgetBeforeReserve=80000 overflowTokens=6486 toolResultReducibleChars=0 effectiveReserveTokens=0 prePromptMessageCount=16 sessionFile=<redacted-user-state>/issue-101952-live-proof-1783490444.jsonl
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_5_DONE
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_6_DONE
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_7_DONE

The live proof used the real CLI, real DeepSeek provider transport, and real exec tool results. The important regression signal is the mid-turn route computed from the projected provider-boundary view: even after the tool-result projection there is still overflow, but toolResultReducibleChars=0, so the route is compact_only rather than a raw-history truncation route.

What was not tested:

  • I did not rerun the original live OpenAI/Codex OAuth scenario after narrowing this PR to projection alignment only.
  • The separate question of relaxing the global tool-result density estimator is intentionally left out of this PR and would need provider/tokenizer evidence plus token-dense plain-text/JSON negative controls.

AI-assisted: implementation and validation were AI-assisted; focused validation commands were run locally.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 8, 2026
@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 8, 2026, 2:16 AM ET / 06:16 UTC.

Summary
Adds a mid-turn precheck projection helper and focused tests so tool-heavy mid-turn routing estimates the aggregate-truncated provider-boundary view while preserving the conservative global estimator.

PR surface: Source +29, Tests +58. Total +87 across 2 files.

Reproducibility: yes. at source level: current main estimates mid-turn overflow from contextMessages while the later provider prompt path applies aggregate tool-result projection. The linked issue also includes concrete logs and billed-usage deltas, but I did not rerun the original cron scenario.

Review metrics: 1 noteworthy metric.

  • Shared estimator policy: 0 constants changed. The final diff no longer relaxes the shared tool-result token-density estimator, which was the maintainer concern on the earlier branch revision.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #101929
Summary: This PR is a candidate fix for the projection-mismatch half of the canonical mid-turn precheck overcount report; sibling PRs target the separate token-density constant policy.

Members:

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

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • none.

Risk before merge

  • [P1] This changes mid-turn session-state routing before provider submission, so an incorrect projection or route decision could compact too early or miss needed recovery in tool-heavy sessions.
  • [P1] The live proof uses DeepSeek rather than the original OpenAI/Codex OAuth setup, although the inspected Codex source supports estimating OpenClaw's supplied provider-boundary prompt shape.

Maintainer options:

  1. Land the projection-only path (recommended)
    Merge this branch after normal maintainer review and exact-head checks if maintainers accept the session-routing risk shown by the focused tests and live logs.
  2. Require original-provider replay
    Ask for an additional redacted OpenAI/Codex OAuth replay if maintainers want proof on the exact reported provider chain before merge.
  3. Pause for a combined policy decision
    Pause this PR only if maintainers want to decide the separate global tool-result density policy in the same landing path.

Next step before merge

  • No repair lane is appropriate because there is no narrow code defect left; the next action is normal maintainer review of the session-state routing risk and exact-head checks.

Security
Cleared: Cleared: the diff changes internal TypeScript agent routing and tests only, with no dependency, workflow, secret, package, lockfile, or supply-chain surface change.

Review details

Best possible solution:

Land one projection-only fix with exact-head checks and redacted runtime proof, then close or rebase the ratio-only alternatives against the canonical behavior.

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

Yes, at source level: current main estimates mid-turn overflow from contextMessages while the later provider prompt path applies aggregate tool-result projection. The linked issue also includes concrete logs and billed-usage deltas, but I did not rerun the original cron scenario.

Is this the best way to solve the issue?

Yes for the projection mismatch: projecting through the same aggregate cap before mid-turn route selection is the narrowest owner-boundary fix I found. The separate global estimator-density debate should remain out of this PR unless maintainers ask to combine it.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 19f7b72a7473.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Sufficient: the PR body includes redacted real CLI/provider/exec-tool logs showing the aggregate-over-cap mid-turn signal after the fix with route=compact_only and toolResultReducibleChars=0.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Sufficient: the PR body includes redacted real CLI/provider/exec-tool logs showing the aggregate-over-cap mid-turn signal after the fix with route=compact_only and toolResultReducibleChars=0.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The PR targets an active agent workflow bug where false mid-turn recovery can rewrite useful context and leave long tool-heavy turns without output.
  • merge-risk: 🚨 session-state: The diff changes the routing signal that decides whether tool-heavy session history is compacted or truncated before the next provider call.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Sufficient: the PR body includes redacted real CLI/provider/exec-tool logs showing the aggregate-over-cap mid-turn signal after the fix with route=compact_only and toolResultReducibleChars=0.
  • proof: sufficient: Contributor real behavior proof is sufficient. Sufficient: the PR body includes redacted real CLI/provider/exec-tool logs showing the aggregate-over-cap mid-turn signal after the fix with route=compact_only and toolResultReducibleChars=0.
Evidence reviewed

PR surface:

Source +29, Tests +58. Total +87 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 30 1 +29
Tests 1 62 4 +58
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 92 5 +87

What I checked:

Likely related people:

  • vincentkoc: Vincent is the live assignee, posted the maintainer scope correction this branch followed, is listed for Agents ownership, and merged adjacent agent compaction fixes. (role: assigned reviewer and adjacent owner; confidence: high; commits: d5d3cb1df66b, 5fc8f0ab37c2; files: src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/tool-result-context-guard.ts, CONTRIBUTING.md)
  • marchpure: The merged mid-turn compaction precheck PR added the feature family that now surfaces this route decision during tool loops. (role: introduced mid-turn guard path; confidence: high; commits: 23264c6255b2; files: src/agents/pi-embedded-runner/tool-result-context-guard.ts, src/agents/pi-embedded-runner/run/attempt.ts, src/config/zod-schema.agent-defaults.ts)
  • jalehman: CONTRIBUTING.md lists Josh Lehman for Compaction and Context Engine, the owner surfaces for this projection and routing decision. (role: adjacent context and compaction owner; confidence: medium; files: CONTRIBUTING.md, src/agents/embedded-agent-runner/tool-result-context-guard.ts, src/agents/embedded-agent-runner/run/preemptive-compaction.ts)
  • obviyus: Current-main blame for the affected files points to Ayaan Zaidi's recent commit that carried the current precheck, aggregate-cap, and estimator lines, though the commit title indicates a broad unrelated change. (role: recent area carrier; confidence: medium; commits: e3b43a0001fb; files: src/agents/embedded-agent-runner/tool-result-context-guard.ts, src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/run/preemptive-compaction.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.
Review history (4 earlier review cycles)
  • reviewed 2026-07-08T01:56:41.306Z sha 270c148 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-08T02:10:45.555Z sha 270c148 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-08T05:27:35.238Z sha b134543 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-08T05:34:49.518Z sha b134543 :: needs real behavior proof before merge. :: none

@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. P1 High-priority user-facing bug, regression, or broken workflow. labels Jul 8, 2026
@vincentkoc vincentkoc self-assigned this Jul 8, 2026
@vincentkoc

Copy link
Copy Markdown
Member

The linked failure is real, but this branch currently combines two different fixes and the regression does not prove the projection half.

run/preemptive-compaction.ts removes the conservative tool-result ratio from estimateLlmBoundaryTokenPressure, which is used by the normal pre-prompt path as well as the mid-turn guard. That is broader than the PR title and changes the global compaction safety policy while tool-result-char-estimator.ts still intentionally models tool results at 2 chars/token.

More importantly, the new “fits after boundary projection” case uses 250,000 tool-result chars with a 200,000-token context window and toolResultMaxChars=16,000. Current resolveLiveToolResultAggregateMaxChars returns max(16,000 * 4, 200,000 * 4 * 0.5) = 400,000, so that test does not aggregate-truncate anything. It only proves the 2-to-4 chars/token policy change.

Please split or tighten this before merge: either prove the local mid-turn projection alignment with a case above the actual 400,000-char aggregate cap while retaining the existing density safety policy, or separately justify the global estimator relaxation with provider/tokenizer evidence and token-dense plain-text/JSON negative controls. The current branch is not a low-risk estimator alignment as written.

@ZengWen-DT ZengWen-DT changed the title fix(agents): align mid-turn tool-result precheck estimates fix(agents): align mid-turn tool-result projection precheck Jul 8, 2026
@ZengWen-DT

Copy link
Copy Markdown
Contributor Author

Thanks, tightened this along the first option.

Changes pushed in b134543:

  • Removed the global estimator relaxation from the final PR diff; estimateLlmBoundaryTokenPressure keeps the existing conservative 2 chars/token tool-result policy.
  • Updated the mid-turn projection regression to use 40 × 12,500-char tool results, so raw tool-result text is 500,000 chars and is above the actual 400,000-char aggregate cap for a 200,000-token window with toolResultMaxChars=16,000.
  • The test now proves route selection runs on the projected provider-boundary view by expecting compact_only with toolResultReducibleChars=0 after projection, instead of claiming the global density policy changed.
  • Updated the PR title/body to make this projection-only and changed Closes to Refs; the separate global estimator relaxation would need its own provider/tokenizer evidence and negative controls.

Validation rerun:

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
Test Files  2 passed (2)
Tests  69 passed (69)
./node_modules/.bin/oxfmt --check --threads=1 src/agents/embedded-agent-runner/run/preemptive-compaction.ts src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts src/agents/embedded-agent-runner/tool-result-context-guard.ts src/agents/embedded-agent-runner/tool-result-context-guard.test.ts
All matched files use the correct format.

git diff --check
# passed

Autoreview also came back clean: no accepted/actionable findings, overall patch is correct (0.78).

@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed 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. labels Jul 8, 2026
@ZengWen-DT

Copy link
Copy Markdown
Contributor Author

Added the requested live behavior proof to the PR body.

Summary of the redacted run:

OPENCLAW_CONFIG_PATH=<temp>/openclaw.json pnpm openclaw agent --local --json --agent main --session-id issue-101952-live-proof-1783490444 --model deepseek/deepseek-v4-flash --thinking off
OpenClaw 2026.6.11 (b134543)
config: contextTokens=80000; toolResultMaxChars=30000; reserveTokens=0; reserveTokensFloor=0; midTurnPrecheck.enabled=true; aggregateCapChars=160000
persisted session: 8 real exec tool results, total tool-result chars 200,480
[agent/embedded] [context-overflow-midturn-precheck] ... provider=deepseek/deepseek-v4-flash route=compact_only estimatedPromptTokens=86486 promptBudgetBeforeReserve=80000 overflowTokens=6486 toolResultReducibleChars=0 effectiveReserveTokens=0 prePromptMessageCount=16 ...
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_5_DONE
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_6_DONE
finalAssistantVisibleText: OPENCLAW_101952_SEGMENT_7_DONE

This is the real CLI/provider/tool path with payloads and local state paths redacted. It shows the aggregate-over-cap mid-turn check using the projected provider-boundary view: after projection, overflow remains, but there are no further tool-result chars to reduce, so the route is compact_only.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 Jul 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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: 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