Skip to content

Align tool-result truncation more closely with PI - #61651

Merged
steipete merged 14 commits into
mainfrom
codex/pi-tool-result-alignment
Apr 6, 2026
Merged

steipete merged 14 commits into
mainfrom
codex/pi-tool-result-alignment

Conversation

@Takhoffman

@Takhoffman Takhoffman commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • align OpenClaw’s tool-result handling more closely with PI’s model: truncate tool results once, preserve stored history, and stop rewriting older tool results in live context
  • switch live and persisted truncation wording to PI-style [... N more characters truncated]
  • restore a reserve-based precheck before provider submission and make it cause-aware: when the prompt estimate is too large, choose the cheapest local recovery path first
  • keep a readable persisted-session repair fallback after compaction failure, including aggregate medium tool-result tails, without collapsing tool results to placeholder-only markers
  • keep a central ingress backstop for tool results because OpenClaw still needs uniform protection across tools and integration surfaces

Original behavior: OpenClaw before this PR

Tool executes
  |
  v
Raw tool result is stored in session/history
  |
  v
Next model call starts
  |
  v
transformContext guard runs
  |
  +--> If one tool result is too large:
  |       truncate that result for live context
  |
  +--> If total context is still too large:
  |       rewrite older tool results in-place
  |       trim them again under aggregate pressure
  |       and sometimes replace them with compaction markers
  |
  +--> If that still is not enough:
          trigger overflow / session compaction
          compact older history
          retry prompt

PI behavior (For reference)

Tool executes
  |
  v
Tool applies its own output limit
  |
  v
Bounded tool result is stored in session/history
  |
  v
Next model call starts
  |
  v
Build prompt from session history
  |
  +--> If prompt estimate fits within contextWindow - reserveTokens:
  |       send prompt unchanged
  |
  +--> If prompt estimate exceeds contextWindow - reserveTokens:
          compact older history into a summary
          keep recent messages and tool results together
          rebuild prompt from compacted history
          retry prompt

New behavior: OpenClaw after this PR

Tool executes
  |
  v
Central guard applies one-time truncation if needed
  (so every tool result has one uniform ingress cap before it reaches history)
  |
  v
Bounded tool result is stored in session/history
  |
  v
Next model call starts
  |
  v
Build prompt from session history
  |
  v
Reserve-based precheck estimates assembled prompt
against contextTokenBudget - reserveTokens
  |
  +--> If estimate fits:
  |       send prompt unchanged
  |
  +--> If estimate exceeds budget:
          classify likely pressure source
          |
          +--> compact_only:
          |       trigger existing session compaction early
          |       compact older history
          |       rebuild prompt from compacted session
          |       retry
          |
          +--> truncate_tool_results_only:
          |       readably truncate persisted recent tool-result tails
          |       skip provider call for this attempt
          |       retry with updated session history
          |
          +--> compact_then_truncate:
                  trigger existing session compaction early
                  compact older history
                  then readably truncate persisted recent tool-result tails
                  rebuild prompt from updated session history
                  retry
  |
  v
If a later provider attempt still reports overflow:
existing overflow handling remains the final fallback path
  |
  +--> try explicit overflow compaction
  +--> if still needed, try readable persisted-session tool-result truncation
  +--> otherwise return context overflow error

Aggregate tool-result fallback

Aggregate overflow means no single tool result is above the per-result limit, but the recent tool-result tail is still too large as a group.

Example:

  • tool result A is 18k chars
  • tool result B is 17k chars
  • tool result C is 16k chars
  • each one is individually valid, so the single-result guard leaves them alone
  • if that recent tail still explains the overflow, the new precheck can truncate it early without hitting the provider
  • if the estimate is mixed, OpenClaw compacts older history first and then truncates the recent tool-result tail before retry
  • if a later provider attempt still overflows, the existing overflow path remains as the final safety net

Important behavior:

  • this is readable truncation, not placeholder replacement
  • each rewritten tool result keeps real content plus the truncation suffix
  • mixed tails are handled in one persisted-session rewrite pass: if one tool result is individually oversized and the remaining medium tail is still over budget, OpenClaw truncates the oversized entry first and then still applies aggregate trimming to the remaining medium tail
  • the old live [compacted: ...] style behavior is not reintroduced
  • normal one-time truncation still keeps a readable floor, but persisted-session recovery truncation can now shrink all the way down to suffix-only when needed

How this differs from PI

  • PI mostly relies on tool-local output limits, while OpenClaw still keeps a central ingress backstop for tool results
  • the precheck is now PI-like in shape, but it still plugs into OpenClaw’s existing context engine and overflow handling rather than replacing that stack wholesale
  • OpenClaw also keeps a readable persisted-session repair fallback after compaction failure; PI does not appear to have an equivalent session rewrite path
  • this PR removes the OpenClaw-only live historical rewriting path while keeping recovery paths readable and bounded

Why not switch fully to PI in this PR

  • replacing OpenClaw’s full overflow/compaction behavior with PI’s exact implementation would still be a much larger behavioral change than this PR’s truncation and precheck cleanup
  • that would touch more runtime boundaries at once and make it harder to isolate regressions if context handling changes in production
  • this PR takes the lower-risk step: remove the custom live rewrite layer we do not want, restore a PI-like reserve-based precheck, add cause-aware local routing, keep the central ingress safety backstop, and preserve a readable session repair fallback where OpenClaw still needs one

Verification

  • pnpm exec vitest run src/agents/pi-embedded-runner/run/preemptive-compaction.test.ts src/agents/pi-embedded-runner/tool-result-truncation.test.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts --config vitest.config.ts --reporter verbose
  • pnpm exec oxlint src/agents/pi-embedded-runner/run/preemptive-compaction.ts src/agents/pi-embedded-runner/run/preemptive-compaction.test.ts src/agents/pi-embedded-runner/tool-result-truncation.ts src/agents/pi-embedded-runner/tool-result-truncation.test.ts src/agents/pi-embedded-runner/run/attempt.ts src/agents/pi-embedded-runner/run/types.ts src/agents/pi-embedded-runner/run.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts

Notes

  • the normal commit hook previously hit unrelated pre-existing repo type errors in src/auto-reply/reply/dispatch-from-config.reply-dispatch.test.ts and src/cli/update-cli/update-command.ts; this PR’s code changes were validated with the focused commands above

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Apr 6, 2026
@greptile-apps

greptile-apps Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR removes OpenClaw's live historical rewrite path (aggregate compaction/placeholder replacement) and replaces it with single-pass per-result truncation, adds a PI-style reserve-based precheck before provider submission with three cause-aware routes (compact_only, truncate_tool_results_only, compact_then_truncate), and aligns the truncation notice format to PI-style [... N more characters truncated]. The previously flagged format mismatch in subagent-announce.ts / system-prompt.test.ts is correctly resolved — both now match the formatContextLimitTruncationNotice output.

Confidence Score: 5/5

Safe to merge — no critical logic errors found; all new paths are bounded and fall back to existing safety nets.

All remaining findings are P2 or lower. The routing logic is mutually exclusive and well-tested: truncate_tool_results_only and shouldCompact cannot both fire in the same precheck result. The precheck error text (PREEMPTIVE_OVERFLOW_ERROR_TEXT) is correctly detected by isLikelyContextOverflowError via the context.*overflow regex. The truncateOversizedToolResultsInSessionManager synchronous path is correct for in-memory operations (no lock needed). The format fix from the prior thread is confirmed — both subagent-announce.ts and system-prompt.test.ts now use the no-comma form.

No files require special attention; run/preemptive-compaction.ts and the updated run/attempt.ts look correct and are well-covered by tests.

Greploops — Automatically fix all review issues by running /greploops in Claude Code. It iterates: fix, push, re-review, repeat until 5/5 confidence.
Use the Greptile plugin for Claude Code to query reviews, search comments, and manage custom context directly from your terminal.

Reviews (2): Last reviewed commit: "Add overflow recovery routing regression..." | Re-trigger Greptile

Comment thread src/agents/subagent-announce.ts Resolved
@Takhoffman Takhoffman changed the title Align tool-result truncation with pi semantics Align tool-result truncation and overflow handling with PI semantics Apr 6, 2026
@Takhoffman Takhoffman changed the title Align tool-result truncation and overflow handling with PI semantics Align tool-result truncation more closely with PI Apr 6, 2026
@Takhoffman Takhoffman changed the title Align tool-result truncation more closely with PI Align tool-result truncation and overflow precheck more closely with PI Apr 6, 2026
@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

I think Codex found a real regression here, unless I am missing a different overflow-recovery path now.

The issue is not the wording cleanup or the reserve-based precheck, it is patch 2 removing the persisted-session repair fallback entirely:

  • run.ts used to detect overflowed tool-result-heavy tails with sessionLikelyHasOversizedToolResults(...)
  • then call truncateOversizedToolResultsInSession(...)
  • then retry the prompt after rewriting persisted tool results

That whole branch is deleted in this PR, and the associated seam tests are deleted too.

What remains now is:

  • one-time per-tool truncation on ingress
  • a reserve-based precheck that asks compaction to happen earlier
  • provider overflow fallback if compaction succeeds or still gets tried

But if compaction returns nothing to compact and the recent tail still overflows because of several medium tool results, I do not see a remaining repair path that rewrites the stored session and retries. In main, that was exactly what the deleted fallback handled.

So I do not think this is safe to land yet as-is. I would either:

  1. keep the session rewrite fallback for now, or
  2. add a replacement path proving aggregate recent-tool-result overflow is still recoverable before merging.

The deleted tests around aggregate overflow / retry-after-session-rewrite were doing real work here, so I would not treat them as dead code.

@Takhoffman
Takhoffman marked this pull request as draft April 6, 2026 05:18
@Takhoffman Takhoffman changed the title Align tool-result truncation and overflow precheck more closely with PI Align tool-result truncation and precheck routing more closely with PI Apr 6, 2026
@Takhoffman
Takhoffman marked this pull request as ready for review April 6, 2026 12:13
@Takhoffman Takhoffman changed the title Align tool-result truncation and precheck routing more closely with PI Align tool-result truncation more closely with PI Apr 6, 2026
@Takhoffman

Copy link
Copy Markdown
Contributor Author

My most recent commits address the repair path concerns and also handle the aggregate tool result scenario.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a533a930a3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b08a9384ae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e543f4765a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +51 to +54
const promptBudgetBeforeReserve = Math.max(
1,
Math.floor(params.contextTokenBudget) - Math.max(0, Math.floor(params.reserveTokens)),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clamp reserve subtraction before precheck overflow routing

When reserveTokens is greater than contextTokenBudget, this computes promptBudgetBeforeReserve as 1, so almost any non-empty prompt is treated as overflow before the provider is called. In that case the run enters compaction/truncation recovery even for fresh sessions with no reducible history, which can surface a false context-overflow failure instead of attempting the model call; this is especially likely on lower-window models where configured/default reserve can exceed the model budget. Cap the effective reserve used for this precheck (or skip this precheck branch) when reserve exceeds the context budget.

Useful? React with 👍 / 👎.

Comment on lines +84 to +87
const suffixFactory: (truncatedChars: number) => string =
typeof options.suffix === "function"
? options.suffix
: () => options.suffix ?? DEFAULT_SUFFIX(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the real truncated count in default truncation suffixes

The default suffix factory ignores its truncatedChars argument and always falls back to DEFAULT_SUFFIX(1), so messages can report "... 1 more characters truncated" even when thousands of characters were removed. This also makes suffix-length budgeting optimistic by assuming a one-digit count. Use the passed count in the fallback (e.g. DEFAULT_SUFFIX(truncatedChars)) so truncation notices and sizing are accurate.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/pi-tool-result-alignment branch from 59f1d18 to 8a05763 Compare April 6, 2026 12:59
@steipete
steipete deleted the codex/pi-tool-result-alignment branch April 6, 2026 13:01

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Landed.

Verification:

  • pnpm test src/agents/pi-embedded-runner/tool-result-truncation.test.ts src/agents/pi-embedded-runner/tool-result-context-guard.test.ts src/agents/pi-embedded-runner/run/preemptive-compaction.test.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts
  • pnpm lint
  • pnpm tsgo and pnpm build were red on unrelated repo-main drift while landing, so I kept the gate focused to the touched PI overflow surfaces.

Land SHA: 99c66a1e8f302a130cced7f35038365e3e2c61c1
Merge SHA: 4a91b4f3a5265e63531e0423d99c70eba6e6e913

Thanks @Takhoffman.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 99c66a1e8f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +667 to +672
if (preflightRecovery?.handled) {
log.info(
`[context-overflow-precheck] early recovery route=${preflightRecovery.route} ` +
`completed for ${provider}/${modelId}; retrying prompt`,
);
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor abort before retrying handled preflight recovery

This unconditional continue retries the loop whenever preflightRecovery.handled is true, even if the attempt was already canceled (aborted set from abortSignal in runEmbeddedAttempt). In that case the run can ignore a user cancel for another iteration and keep mutating session history (for example, after early tool-result truncation), instead of exiting promptly. Gate this fast-path on a non-aborted/non-timeout attempt so cancellation semantics are preserved.

Useful? React with 👍 / 👎.

steipete added a commit to leoleedev/openclaw that referenced this pull request Apr 6, 2026
steipete added a commit to leoleedev/openclaw that referenced this pull request Apr 6, 2026
Mlightsnow pushed a commit to Mlightsnow/openclaw that referenced this pull request Apr 6, 2026
Mlightsnow pushed a commit to Mlightsnow/openclaw that referenced this pull request Apr 6, 2026
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 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 maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants