Skip to content

fix: make tool validation and truncation feedback actionable - #201795

Merged
roboclaw-bot merged 11 commits into
mainfrom
openclaw/swift-langoustine-5
Nov 19, 2026
Merged

roboclaw-bot merged 11 commits into
mainfrom
openclaw/swift-langoustine-5

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

When a tool call is rejected, a compact schema hint can hide the field names the agent needs. When a large result has many text blocks, the runtime can cut every truncation warning off before it says what happened or how to recover.

User Impact

Agents get the exact schema-inspection step after a validation failure. Oversized multi-block results keep whole leading records plus one readable recovery notice, without re-expanding previously sent results or dropping images that fit.

Why This Change Was Made

Reuse tool_describe in structured Tool Search and handle describe() in Code Mode rather than expanding the full schema in every error. When per-block notices do not fit, keep whole leading records and place one notice at the first omitted text position. This lets replay restore the exact text prefix alongside canonical non-text blocks, and lets the context guard retain a fitting image when text is intentionally omitted. Ordinary single-block truncation is unchanged.

Reported and co-authored by @jacobtomlinson.

Work sessions

Linked for team reference; these sessions aren’t public.

Evidence

Built CLI and latest-stable upgrade proof

The real openclaw agent --local --json CLI, not an in-process agent harness, ran in separate OS processes in an isolated profile with a loopback-only HTTP Responses fixture. The fixture scripts model decisions and records actual provider-bound requests; no external inference, live Gateway, or operator session data was used. The latest stable npm tarball [email protected] (e13cf15) matched npm's published SHA-512 integrity. The candidate runtime was built at 6e27254b9d9c09a9171d88b0a26d889b9c811604; a full-tree git diff --exit-code against the reviewed PR head was empty.

Case Verified observation
Schema recovery, 32,768-token model Four real Responses requests: dispatch_action rejected the unknown nested key and returned the exact tool_describe ID; inspection exposed displayPreference24 and filters.pageSize; the corrected call executed and the turn completed.
Mixed result, 65,536-token model with a 16,000-character tool-result cap The follow-up Responses request contained 127 of 1,000 record IDs, one readable truncation notice, and the original PNG bytes in one input_image. The turn completed.
Latest-stable SQLite upgrade and cold restart The stable CLI created a session at 131,072 tokens, then a separate stable CLI process reopened it at 65,536 and wrote a 15,971-character frozen projection. The candidate CLI ran doctor --fix --non-interactive on that same state, migrating the agent DB from schema 38 to 43. The saved projection digest was identical in the archived stable DB and upgraded DB. Two separately launched candidate CLI invocations reopened the same session at 131,072, saw the prior reply, and sent the same shortened tool output as stable at the tighter cap.
Redacted captures and fingerprints
schema: Use tool_describe with id "openclaw:feedback-proof:feedback_schema" for its input schema.
schema: late field=true; nested field=true; corrected retry executed=true; terminal=true
mixed: record IDs=127; input_image=1; original PNG bytes=true; readable notices=1; terminal=true

SQLite frozen projection: 15,971 characters; schema 38 → 43
SHA-256 of serialized checkpoint texts (stable and upgraded):
d33603fe2f5cb7cf19d1e6cdd3a56a766b25ad471b8a9493deca869fc6bb6c6e
SHA-256 of serialized function-call output (stable tightened, candidate resume, candidate cold restart):
8e36cc1fc764f70b36b60ccb729253f3c4a80412e23522bf9d0e259f84421460

The 32,768-token mixed-result CLI attempt stopped at the separate total-prompt precheck; the positive mixed-image CLI proof above used 65,536. A first candidate reopen before Doctor correctly refused the older DB schema; the upgrade proof used the supported Doctor path, not a manual migration. The proof covers existing stable-created state, a forward migration, and cold replay; it does not claim downgrade or updater-package installation coverage.

Original reproducer

Reran the same two synthetic tools in a 32,768-token mock agent loop, capturing the result handed to the next model call. Baseline: 8a23d7c11d37183b00f5bd0ba4c942bbfe03e116.

Original probe Before After
27-field schema; wrong type or unknown root/nested property Expected input elides fields; no inspection step All three errors include tool_describe and the exact tool ID; inspection returns the missing keys and the corrected retry succeeds
1,000-record page / 1,000 text blocks 0 visible record IDs; every notice clipped 127 whole leading records and one readable recovery notice
1,000 records / one text block 126 record IDs and a readable warning Same
10 records / 10 text blocks All 10, no warning Same
Before and after: captured model-visible excerpts
Before: Invalid arguments for tool "openclaw:core:feedback_wide_schema": filters: must not have additional properties: "totallyUnrelated"; received [object] (object). Expected input: { collection: string; limit: number /* integer */; ... }.
Before: [... 125 more ch

After: Invalid arguments for tool "openclaw:core:feedback_wide_schema": filters: must not have additional properties: "totallyUnrelated"; received [object] (object). Expected input: { collection: string; limit: number /* integer */; ... }. Use tool_describe with id "openclaw:core:feedback_wide_schema" for its input schema.
After: [... 109125 more characters truncated; rerun with narrower args if needed]

ClawSweeper follow-up

Both findings from the initial review reproduced on the previous PR head 4dac7d4ea0c0 using 1,000 text records with an interleaved image. The re-review confirmed both code fixes and requested additional CLI and upgrade evidence; those captures are above.

Review probe Previous PR head Revised PR head
Tighten from 16,000 to 8,000 characters, then relax to 16,000 or restore a serialized checkpoint 127 → 63 → 127 records for both replay paths 127 → 63 → 63; the tightened output is byte-identical after relaxation and restore
Context guard with room for one image and a text prefix 0 images; 129 records 1 image; 66 records and one readable text-truncation notice

The original probe output was unchanged after the follow-up. 130 distinct focused tests passed, covering truncation, checkpoint replay, the context guard, schema recovery, and prefix stability. Scoped typed lint, core and agents-tools type checks, formatting, and git diff --check passed. Local autoreview found no actionable P0–P2 findings in the follow-up diff. Hosted CI is separate; this evidence update does not change CI or the PR head.

Worked on by

roboclaw-bot and others added 2 commits November 19, 2026 11:43
Worked on by:
- @jacobtomlinson

Co-authored-by: jacobtomlinson <[email protected]>
OpenClaw-Publication: cd7ed16f-26c4-8ec1-94ab-e525f6e80b0c
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Nov 19, 2026
@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 Nov 19, 2026
roboclaw-bot and others added 3 commits November 19, 2026 11:56
Worked on by:
- @jacobtomlinson

Co-authored-by: jacobtomlinson <[email protected]>
OpenClaw-Publication: fc7b69ad-8ad9-8b40-a881-dfdf5d2dec27
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds exact schema-inspection guidance to validation errors and preserves readable recovery notices in oversized multi-block tool results.

Example: A tool returns 1,000 text records under a 16,000-character result cap.

  • Before: Per-block truncation clips every notice and leaves no visible record IDs.
  • After: The supplied CLI capture shows 127 whole leading records and one readable truncation notice.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with shipped CLI evidence and stable-created frozenToolResults texts preserved through Doctor upgrade and cold replay; broad current-head CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Public terminal captures exercise the built agent CLI through a loopback Responses transport: exact schema inspection enables a corrected call, and mixed output retains records, one notice, and original PNG bytes; these establish runtime behavior without claiming model-inference quality.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Agents can receive validation failures without the missing schema fields or oversized results whose warnings are clipped beyond usefulness.
Reason: The maintainer-authored direction repairs demonstrated recovery failures using existing capabilities without adding configuration or public APIs.

Merge readiness

✅ Ready for maintainer review

This PR addresses concrete feedback failures with no actionable findings remaining; exact-head CI is still in progress.

Priority: P2
Reviewed head: c8ab15bc6ba1ee23276ac3cd29ec997ed03ccead

Before merge

None.

Findings

None.

Agent review details

How this fits together

Tool Search validates agent calls, while the embedded runner budgets returned content and restores frozen projections before sending subsequent provider requests.

flowchart TD
  A[Agent tool call] --> B[Catalog validation]
  B --> C[Schema recovery guidance]
  B --> D[Tool execution]
  D --> E[Shared result budgeting]
  F[Frozen projection checkpoint] --> E
  E --> G[Provider request]
Loading

Technical review

Best possible solution:

Retain the focused repair through existing validation, budgeting, and projection owners.

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

Base source proportionally clips per-block notices when their combined cost exceeds the cap and omits exact schema-recovery guidance; the supplied before/after captures exercise both failures.

Is this the best way to solve the issue?

The patch repairs the shared allocator and existing error formatter, preserves canonical non-text content and frozen replay, and adds distinct regressions without unnecessary production machinery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 44267df6c5ea.

Provenance checked

  • Multi-block weighted allocation changes intended behavior with a stated reason (69e8d40: Keep multilingual and multi-block output within one shared budget, including bounded notices.)
  • Context guard text and image selection keeps the original intent (5d88e18: Use the canonical allocator to preserve fitting actionable text and non-text content.)
  • Frozen projection merging keeps the original intent (037ad05: Reuse immutable projection wrappers while preserving provider bytes, canonical metadata, and replay identity.)
  • Catalog validation diagnostics keeps the original intent (1c93dbe: Provide bounded, redacted expected-versus-received diagnostics without changing accepted inputs or execution.)
  • Minimum retained-text budget keeps the original intent (bb46b79: The runtime internalization carried this existing helper forward; this commit does not establish its original introduction.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 037ad05 adds src/agents/embedded-agent-runner/tool-result-projection-message.ts:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 037ad0565c8f; files: src/agents/embedded-agent-runner/tool-result-projection-message.ts)
  • Mark Hall: Raw commit 1c93dbe adds src/agents/tool-search-recovery.ts:104 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1c93dbed0cce; files: src/agents/tool-search-recovery.ts)
  • Tyler Yust: Raw commit 0deb8b0 adds src/agents/pi-embedded-runner/tool-result-truncation.ts:102 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0deb8b0da187; files: src/agents/pi-embedded-runner/tool-result-truncation.ts)

PR surface

Source +66, Tests +166, Docs +1, Other 0. Total +233 across 11 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 6 106 40 +66
Tests 3 166 0 +166
Docs 1 3 2 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 11 276 43 +233

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Unreadable truncation notices and incomplete validation guidance impair agent recovery in bounded tool workflows.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 (2 earlier review cycles)
  • reviewed 2026-11-19T12:07:34.325Z sha 4dac7d4 :: needs changes before merge. :: [P2] Preserve compacted results through frozen projection replay | [P2] Keep fitting images when the context guard compacts text
  • reviewed 2026-11-19T13:48:59.578Z sha 7a7470e :: blocked before merge. :: none

Reviewed November 19, 2026, 10:12 AM ET / 15:12 UTC (Revision 3).

roboclaw-bot and others added 3 commits November 19, 2026 13:40
Worked on by:
- @jacobtomlinson

Co-authored-by: jacobtomlinson <[email protected]>
OpenClaw-Publication: 0add01a0-079b-8383-b1d0-624a4713e4c3
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Nov 19, 2026
@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Nov 19, 2026
roboclaw-bot and others added 3 commits November 19, 2026 15:06
Worked on by:
- @jacobtomlinson

Co-authored-by: jacobtomlinson <[email protected]>
OpenClaw-Publication: fca8f024-bb61-81d3-a65b-2053246258a8
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 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: 🐚 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. labels Nov 19, 2026
@roboclaw-bot
roboclaw-bot merged commit 877064c into main Nov 19, 2026
127 checks passed
@roboclaw-bot
roboclaw-bot deleted the openclaw/swift-langoustine-5 branch November 19, 2026 15:24
obviyus added a commit that referenced this pull request Nov 27, 2026
…ecovered (#206880)

## What Problem This Solves

When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back.

Production signal (a production deployment, 2.76 days of Gateway logs):
- 102 `[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)` lines, up to 96 results in one session.
- 310 context-overflow diagnostics in the same window, driven by long sessions full of tool output.

Reproduced on main (`ab296c23d2c4`) through the real record path (`guardSessionManager`, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result:

| | main | this PR |
|---|---|---|
| Characters the model sees | 63,973 | 63,961 |
| Last line kept | no | yes |
| Full output recoverable | no (dropped) | yes, 180,015 chars in a file |
| Notice | `[... 116116 more characters truncated; rerun with narrower args if needed]` | `[... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]` |

## Fix

The bound has one owner, at record time:
- `boundToolResult` (`src/agents/embedded-agent-runner/tool-result-bound.ts`) runs once at the end of `afterToolCall` (`run/attempt-setup.ts`), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin.
- It keeps the head and the tail and puts the notice at the cut. The full text goes to an owner-only file through the existing `writePrivateTempFile` (tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule as `exec` and `web_fetch` output files. A tool that already saved its own file (`exec`, `web_fetch`) keeps that file, and the notice names it.
- The budget comes from the transcript guard's registry, so the existing synchronous cap leaves a bounded result byte for byte. Prefix stability holds, because a recorded result never changes after it is recorded.
- If the file write fails, the result passes on unchanged, and the existing transcript cap bounds it with head, tail and the character count.

Deleted:
- `context-truncation-notice.ts`: the "rerun with narrower args" notice and its `sessions_send` variant.
- `hasImportantTail`, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split.

Fixed on the way (exposed by the shorter notice):
- The aggregate planner sized notices with a count of 1, so a notice carrying a real count could be cut. That dropped the spill path from a disclosed `Full output:` pointer. It now sizes the notice for the largest count it can show.
- A multi-block result made only of short records keeps whole leading records with one notice (#201795) instead of cutting every record.

## User impact

- Gateway and one-shot (`agent --local`) users on the embedded runtime. Both run `installEmbeddedAttemptContextGuards` (`src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515`).
- A large tool result keeps its last lines (errors, totals, exit status), and the model can read the omitted middle from the named file instead of rerunning the tool.
- No config change. Results within budget are unchanged.
- Not covered: the Codex app-server and Claude CLI runtimes, which do not run this loop.

## Evidence

- `src/agents/tool-result-bounds.test.ts`: one case per tool family through the real guard registry:
  - exec (`buildExecForegroundResult`), MCP (`projectMcpCallToolResult`) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point);
  - web_fetch reuses its own spill file;
  - read reaches the middle of a 180k one-line spill page by page, and no page needs a second spill;
  - a failed spill write falls back to head, tail and the count, with no path.
- `run/attempt-context-guards.test.ts`: the installed `afterToolCall` bounds the result an earlier hook returned and restores the previous hook on removal.
- Touched suites pass (8 files), and `agent-tools.prefix-stability` passes. All core test typecheck shards pass.
- The prompt-cache prefix-stability journeys fail the same way on the merge base `ab296c23d2c4`, so these failures are not from this change:
  - They expect a summary marker ("compacted into the following summary") that #205584 replaced.
  - Google also counts 2 compactions in its overflow run where the test expects 1 (`expected 2 to be 1`, reproduced on the base).
  - The breaks they report are the allowed compactions; no tool-result bytes change after they are recorded.
- On main, the same contract test fails 5 of 5 families (63,973 of 180,015 characters kept, tail lost, no file).
- **End to end, real model.** Isolated `openclaw agent --local` (scratch HOME, state and config), `openai/gpt-5.4-mini` on the embedded runtime. The agent runs `seq 1 60000 | sed 's/$/ padding padding padding/'` through `exec`, calls no other tool, and replies with the last line of the output:
  - main `ab296c23d2c4`: `UNKNOWN` (the recorded result kept only the head of exec's retained window);
  - this PR: `60000 padding padding padding`. The notice points at exec's own output file; no second file is written.
- Review fixes, each with a test that is red on the earlier head:
  - a notice that gains a digit no longer pushes head+tail over the cap;
  - the separator newlines are reserved at the caller's weight (the context guard counts 2 per char), so a dense single-line result keeps its tail.
- Workspace-only host sessions cannot open tmpdir paths with `read`; exec and web_fetch spill paths are in the same position on main. Letting `read` open this session's own spill paths is the follow-up PR.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
…ecovered (#206880)

## What Problem This Solves

When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back.

Production signal (a production deployment, 2.76 days of Gateway logs):
- 102 `[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)` lines, up to 96 results in one session.
- 310 context-overflow diagnostics in the same window, driven by long sessions full of tool output.

Reproduced on main (`ab296c23d2c4`) through the real record path (`guardSessionManager`, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result:

| | main | this PR |
|---|---|---|
| Characters the model sees | 63,973 | 63,961 |
| Last line kept | no | yes |
| Full output recoverable | no (dropped) | yes, 180,015 chars in a file |
| Notice | `[... 116116 more characters truncated; rerun with narrower args if needed]` | `[... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]` |

## Fix

The bound has one owner, at record time:
- `boundToolResult` (`src/agents/embedded-agent-runner/tool-result-bound.ts`) runs once at the end of `afterToolCall` (`run/attempt-setup.ts`), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin.
- It keeps the head and the tail and puts the notice at the cut. The full text goes to an owner-only file through the existing `writePrivateTempFile` (tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule as `exec` and `web_fetch` output files. A tool that already saved its own file (`exec`, `web_fetch`) keeps that file, and the notice names it.
- The budget comes from the transcript guard's registry, so the existing synchronous cap leaves a bounded result byte for byte. Prefix stability holds, because a recorded result never changes after it is recorded.
- If the file write fails, the result passes on unchanged, and the existing transcript cap bounds it with head, tail and the character count.

Deleted:
- `context-truncation-notice.ts`: the "rerun with narrower args" notice and its `sessions_send` variant.
- `hasImportantTail`, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split.

Fixed on the way (exposed by the shorter notice):
- The aggregate planner sized notices with a count of 1, so a notice carrying a real count could be cut. That dropped the spill path from a disclosed `Full output:` pointer. It now sizes the notice for the largest count it can show.
- A multi-block result made only of short records keeps whole leading records with one notice (#201795) instead of cutting every record.

## User impact

- Gateway and one-shot (`agent --local`) users on the embedded runtime. Both run `installEmbeddedAttemptContextGuards` (`src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515`).
- A large tool result keeps its last lines (errors, totals, exit status), and the model can read the omitted middle from the named file instead of rerunning the tool.
- No config change. Results within budget are unchanged.
- Not covered: the Codex app-server and Claude CLI runtimes, which do not run this loop.

## Evidence

- `src/agents/tool-result-bounds.test.ts`: one case per tool family through the real guard registry:
  - exec (`buildExecForegroundResult`), MCP (`projectMcpCallToolResult`) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point);
  - web_fetch reuses its own spill file;
  - read reaches the middle of a 180k one-line spill page by page, and no page needs a second spill;
  - a failed spill write falls back to head, tail and the count, with no path.
- `run/attempt-context-guards.test.ts`: the installed `afterToolCall` bounds the result an earlier hook returned and restores the previous hook on removal.
- Touched suites pass (8 files), and `agent-tools.prefix-stability` passes. All core test typecheck shards pass.
- The prompt-cache prefix-stability journeys fail the same way on the merge base `ab296c23d2c4`, so these failures are not from this change:
  - They expect a summary marker ("compacted into the following summary") that #205584 replaced.
  - Google also counts 2 compactions in its overflow run where the test expects 1 (`expected 2 to be 1`, reproduced on the base).
  - The breaks they report are the allowed compactions; no tool-result bytes change after they are recorded.
- On main, the same contract test fails 5 of 5 families (63,973 of 180,015 characters kept, tail lost, no file).
- **End to end, real model.** Isolated `openclaw agent --local` (scratch HOME, state and config), `openai/gpt-5.4-mini` on the embedded runtime. The agent runs `seq 1 60000 | sed 's/$/ padding padding padding/'` through `exec`, calls no other tool, and replies with the last line of the output:
  - main `ab296c23d2c4`: `UNKNOWN` (the recorded result kept only the head of exec's retained window);
  - this PR: `60000 padding padding padding`. The notice points at exec's own output file; no second file is written.
- Review fixes, each with a test that is red on the earlier head:
  - a notice that gains a digit no longer pushes head+tail over the cap;
  - the separator newlines are reserved at the caller's weight (the context guard counts 2 per char), so a dense single-line result keeps its tail.
- Workspace-only host sessions cannot open tmpdir paths with `read`; exec and web_fetch spill paths are in the same position on main. Letting `read` open this session's own spill paths is the follow-up PR.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 5c3c123)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…ecovered (openclaw#206880)

## What Problem This Solves

When a tool returns more text than its context budget, OpenClaw keeps only the start, discards the rest, and tells the model to "rerun with narrower args". The end of the output, where commands print errors, totals and exit status, is lost unless a keyword list happens to match it. MCP and plugin tools have no other copy, so the model cannot get the cut text back.

Production signal (a production deployment, 2.76 days of Gateway logs):
- 102 `[tool-result-truncation] Truncated N tool result(s) for prompt history (maxChars=64000 …)` lines, up to 96 results in one session.
- 310 context-overflow diagnostics in the same window, driven by long sessions full of tool output.

Reproduced on main (`856cbaecaad8`) through the real record path (`guardSessionManager`, 200k-token window). The fixture is a 180,015-character plain log, the same for exec, read, web_fetch, an MCP result and a plugin result:

| | main | this PR |
|---|---|---|
| Characters the model sees | 63,973 | 63,961 |
| Last line kept | no | yes |
| Full output recoverable | no (dropped) | yes, 180,015 chars in a file |
| Notice | `[... 116116 more characters truncated; rerun with narrower args if needed]` | `[... 116221 chars omitted. Full output: <path> (page it with read offset/limit)]` |

## Fix

The bound has one owner, at record time:
- `boundToolResult` (`src/agents/embedded-agent-runner/tool-result-bound.ts`) runs once at the end of `afterToolCall` (`run/attempt-setup.ts`), after tool-result hooks and before the result is first sent. It applies to every executed tool: core, MCP and plugin.
- It keeps the head and the tail and puts the notice at the cut. The full text goes to an owner-only file through the existing `writePrivateTempFile` (tmpdir, 0600; staged in the workspace for sandboxed sessions), the same rule as `exec` and `web_fetch` output files. A tool that already saved its own file (`exec`, `web_fetch`) keeps that file, and the notice names it.
- The budget comes from the transcript guard's registry, so the existing synchronous cap leaves a bounded result byte for byte. Prefix stability holds, because a recorded result never changes after it is recorded.
- If the file write fails, the result passes on unchanged, and the existing transcript cap bounds it with head, tail and the character count.

Deleted:
- `context-truncation-notice.ts`: the "rerun with narrower args" notice and its `sessions_send` variant.
- `hasImportantTail`, a keyword regex that decided whether the tail survived, and the head-only branch it guarded. Head+tail is now unconditional for any window over 4,000 characters. Smaller windows keep a whole prefix, so short records are not split.

Fixed on the way (exposed by the shorter notice):
- The aggregate planner sized notices with a count of 1, so a notice carrying a real count could be cut. That dropped the spill path from a disclosed `Full output:` pointer. It now sizes the notice for the largest count it can show.
- A multi-block result made only of short records keeps whole leading records with one notice (openclaw#201795) instead of cutting every record.

## User impact

- Gateway and one-shot (`agent --local`) users on the embedded runtime. Both run `installEmbeddedAttemptContextGuards` (`src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:515`).
- A large tool result keeps its last lines (errors, totals, exit status), and the model can read the omitted middle from the named file instead of rerunning the tool.
- No config change. Results within budget are unchanged.
- Not covered: the Codex app-server and Claude CLI runtimes, which do not run this loop.

## Evidence

- `src/agents/tool-result-bounds.test.ts`: one case per tool family through the real guard registry:
  - exec (`buildExecForegroundResult`), MCP (`projectMcpCallToolResult`) and plugin: head, tail, spill file with the full text, and the recorded bytes equal to the bound bytes (fixed point);
  - web_fetch reuses its own spill file;
  - read reaches the middle of a 180k one-line spill page by page, and no page needs a second spill;
  - a failed spill write falls back to head, tail and the count, with no path.
- `run/attempt-context-guards.test.ts`: the installed `afterToolCall` bounds the result an earlier hook returned and restores the previous hook on removal.
- Touched suites pass (8 files), and `agent-tools.prefix-stability` passes. All core test typecheck shards pass.
- The prompt-cache prefix-stability journeys fail the same way on the merge base `856cbaecaad8`, so these failures are not from this change:
  - They expect a summary marker ("compacted into the following summary") that openclaw#205584 replaced.
  - Google also counts 2 compactions in its overflow run where the test expects 1 (`expected 2 to be 1`, reproduced on the base).
  - The breaks they report are the allowed compactions; no tool-result bytes change after they are recorded.
- On main, the same contract test fails 5 of 5 families (63,973 of 180,015 characters kept, tail lost, no file).
- **End to end, real model.** Isolated `openclaw agent --local` (scratch HOME, state and config), `openai/gpt-5.4-mini` on the embedded runtime. The agent runs `seq 1 60000 | sed 's/$/ padding padding padding/'` through `exec`, calls no other tool, and replies with the last line of the output:
  - main `856cbaecaad8`: `UNKNOWN` (the recorded result kept only the head of exec's retained window);
  - this PR: `60000 padding padding padding`. The notice points at exec's own output file; no second file is written.
- Review fixes, each with a test that is red on the earlier head:
  - a notice that gains a digit no longer pushes head+tail over the cap;
  - the separator newlines are reserved at the caller's weight (the context guard counts 2 per char), so a dense single-line result keeps its tail.
- Workspace-only host sessions cannot open tmpdir paths with `read`; exec and web_fetch spill paths are in the same position on main. Letting `read` open this session's own spill paths is the follow-up PR.

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 docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

1 participant