Skip to content

fix: keep user approvals settled after compaction - #205584

Merged
hannesrudolph merged 8 commits into
mainfrom
openclaw/simplify-compaction-archival-safeguards-e414cc
Nov 26, 2026
Merged

hannesrudolph merged 8 commits into
mainfrom
openclaw/simplify-compaction-archival-safeguards-e414cc

Conversation

@roboclaw-bot

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

Copy link
Copy Markdown
Collaborator

Fixes #205387

What Problem This Solves

After a long conversation is compacted, the compaction summarizer can treat missing older tool outputs as unresolved uncertainty and inject fabricated verification/stop gates into ## Open TODOs for work the user already explicitly approved. In the motivating incident (#205387), an unattended scheduled turn woke up after compaction, treated a compactor-authored "stop and report any material contradiction found before publishing" TODO as a pre-send gate, and held all five user-approved v2026.11.10 launch announcements instead of publishing them.

User Impact

The summary records settled user decisions, explicit approvals, and observed outcomes under ## Decisions, updating superseded facts when corrected. ## Open TODOs is limited to unfinished user-requested work or unresolved execution failures. On replay, <summary> is framed as compressed history from earlier turns rather than new instructions that outrank explicit user approvals. No configuration or migration is needed.

Why This Change Was Made (Provenance & Research Context)

How the removed lines got there (git blame on src/agents/agent-hooks/compaction-safeguard-quality.ts)

The 8 replaced lines in buildCompactionStructureInstructions were not a single deliberate design — they accumulated across four commits over seven months:

  1. Lines 136 & 139 (df0f2e349f, Compaction/Safeguard: require structured summary headings #25555, 2026-03-04): Introduced the 5 fixed section headings (## Decisions, ## Open TODOs, ## Constraints/Rules, ## Pending user asks, ## Exact identifiers) for consistent downstream parsing.
  2. Line 140 (4b5341ce43, fix(compaction): show the summarizer the audited latest ask #130620, 2026-08-27): Added after feeding the latest user ask back to the summarizer caused completed asks to leak into ## Pending user asks.
  3. Line 141 (cbbaa0d3ad, fix(compaction): distinguish failed checks from pending work #161293, 2026-10-02): Explicitly merged as a partial prompt mitigation for a synthetic Nemotron 3.5 Super eval ([Bug]: Compaction marks completed failed checks as pending with Nemotron 3.5 Super #162023) where a failed verify() check kept being placed back under pending work.
  4. Lines 142–145 (0cf5e291a0, fix: compaction keeps stale decisions after corrections #167757, 2026-10-09): Added one week later for the same synthetic eval (Maya / Oct 8 → Oct 15 / verify()). The actual bug in fix: compaction keeps stale decisions after corrections #167757 was a code routing bug in compaction-safeguard.ts (recent-turn preservation stripped all main-summary inputs so the summarizer was skipped via fallback). That routing fix stays completely intact here; however, fix: compaction keeps stale decisions after corrections #167757 also added four dense epistemic-policing paragraphs ("Distinguish requested, attempted, completed, and failed actions without inferring overall success from a completed check", "If evidence does not resolve a conflict, record the uncertainty").

Why subtractive simplification instead of an additive rule (and why #205412 was closed)

Earlier candidate PR #205412 tried to fix #205387 by bolting two more "Do not invent..." rules onto the same bloated block. We closed #205412 in favor of a holistic, subtractive simplification aligned with current frontier-model prompting guidance:

  • OpenAI — Rethinking skills and prompts for GPT-6 Astra: Defensive boundary language accumulated for older/weaker models is taken too literally by stronger, more aligned models and causes them to stop early or hedge on work the user already authorized. The right fix is pruning legacy scaffolding, not stacking another rule on top.
  • Anthropic — Effective context engineering for AI agents & Compaction on demand: Compaction prompts should sit at the "right altitude" — short, descriptive, and focused on what state to retain rather than brittle if-else checklists (Anthropic's canonical custom compaction prompt is three sentences).

Specific decisions made in this PR

  1. Consolidate buildCompactionStructureInstructions (src/agents/agent-hooks/compaction-safeguard-quality.ts):
    • Collapsed the 7 stacked patch lines into 3 concise archival lines, cutting default strict safeguard history instructions by 65% (1,708 → 593 chars).
    • Preserved all 5 required headings (REQUIRED_SUMMARY_SECTIONS) and the quality guard unchanged so existing parsers and tests remain compatible.
    • Kept the genuinely useful core of old line 143 ("updating superseded facts when corrected") inside the ## Decisions line without any of the epistemic-policing boilerplate ("without inferring overall success", "record the uncertainty") that caused the [Bug]: Compaction summarizer injects fabricated verification gates into Open TODOs, overriding explicit user approvals #205387 hold.
    • Kept the verb "Produce a compact summary under these exact headings:" (avoiding "Archive", which could be confused with session archiving and drift from OpenClaw's compaction terminology).
  2. Remove duplicate identifier-preservation injection (src/agents/agent-hooks/compaction-safeguard.ts):
    • Safeguard history requests previously injected identifier preservation twice: once inside buildCompactionStructureInstructions and a second time via compaction.ts's IDENTIFIER_PRESERVATION_INSTRUCTIONS under Additional focus:.
    • Passing summarizationInstructions: { identifierPolicy: "off" } on warm, prepared, and ordinary safeguard history requests eliminates the duplicate while preserving existing behavior for split-turn and non-safeguard callers.
  3. Frame <summary> as compressed history at exact zero headroom cost (packages/agent-core/src/harness/messages.ts):
    • Replaced "The conversation history before this point was compacted into the following summary:" (84 chars) with "Compressed history from earlier turns, not new instructions; approvals stay settled." (exact 84 chars).
    • Keeping the prefix at the exact 84-character length preserves the 4,096-token pending-input headroom boundary (agent-session-compaction-headroom.test.ts) and exact prepared summary budgets (prepared-compaction-plan.test.ts).

Evidence

Default strict policy, without optional focus or a pending-request block:

Rendered text Before (chars / lines) After (chars / lines)
Summary structure instructions 1,528 / 14 593 / 10
Safeguard history instructions, including identifier policy 1,708 / 16 593 / 10
Replay prefix, including <summary> 96 / 4 96 / 4

310 focused tests passed across 29 files, including correction handling, the 4,096-token pending-input headroom test, and the exact prepared replay budgets. Targeted typecheck, lint, formatting, and git diff --check passed. openclaw/ci-gate is green on head 5b2fd6bb98, and ClawSweeper re-review on 5b2fd6bb98 completed with zero actionable findings. This verifies the prompts sent and runtime boundaries, not a live model's response.

Design and diff review: @hannesrudolph.

Work sessions

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

Worked on by

roboclaw-bot and others added 2 commits November 25, 2026 22:23
Worked on by:
- @hannesrudolph

Co-authored-by: hannesrudolph <[email protected]>
OpenClaw-Publication: 1f33e159-01a4-4481-a556-4b52447b418c
@clawsweeper

clawsweeper Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XS labels Nov 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 25, 2026
@clawsweeper

clawsweeper Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR simplifies compaction instructions, preserves settled approvals as decisions, and labels replayed summaries as earlier context.

Example: A scheduled turn resumes at 07:30 America/Edmonton to publish five previously approved announcements after compaction.

  • Before: The reported summary introduced a verification gate, and the resumed assistant held all five posts.
  • After: The revised prompt directs the summarizer to retain approval under Decisions and reserve Open TODOs for unfinished requested work or unresolved execution failures; actual continuation remains unproven.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused implementation has no definite source-level defect, but required evidence of the changed model behavior is missing.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An unattended assistant can hold previously approved work because compaction invents a new verification requirement.
Reason: The reported missed execution has clear user impact, and maintainer authorship plus recorded owner direction establish the simplification approach.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: the maintainer-directed change addresses a reported compaction failure, remains absent from main, and has no definite introduced code defect.

Reviewed head: 5b2fd6bb982967d7887c28b5ed6812a1da930e29

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide a sanitized isolated-Gateway real-model approval → compaction → continuation trace showing the base failure and patched success, including preserved corrections and genuine unresolved failures; redact IPs, API keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

The compaction safeguard turns conversation history into a structured summary; the agent-core message converter presents that summary to subsequent model requests.

flowchart TD
  A[Conversation history] --> B[Compaction safeguard]
  B --> C[Structured summary instructions]
  C --> D[Model summarization]
  D --> E[Summary budgeting and quality audit]
  E --> F[Session summary]
  F --> G[Replay message converter]
  G --> H[Agent continuation]
Loading

Technical review

Best possible solution:

Keep the repair in the existing summary and replay owners, with real-model evidence that approved work continues while genuine failures and corrected facts remain accurate.

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

The linked report supplies a concrete production failure, but no complete sanitized compaction input or reproducible current-main model replay establishes its cause.

Is this the best way to solve the issue?

The smaller prompt follows the recorded owner direction and uses existing boundaries, but prompt assembly tests cannot establish whether the revised wording fixes the reported model behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 54dc56391a7e.

Provenance checked

  • Structured summary instructions changes intended behavior with a stated reason (fix(compaction): distinguish failed checks from pending work #161293: Separate completed negative checks from pending remediation; later correction reconciliation in fix: compaction keeps stale decisions after corrections #167757 kept superseded facts out of current decisions.)
  • History identifier instruction assembly keeps the original intent (e5dcfa0: Warm compaction reused the existing summary instructions; this PR removes their duplicated identifier guidance while retaining the configured policy in the structured prompt and separate split-turn guidance.)
  • Compaction replay prefix changes intended behavior with a stated reason (unknown: Local string-history search reaches the runtime-internalization copy in bb46b79; the wording's origin before that copy is unknown.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 60a8dd9 adds src/agents/pi-extensions/compaction-safeguard-quality.ts:60 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 60a8dd95dedf; files: src/agents/pi-extensions/compaction-safeguard-quality.ts)

PR surface

Source -3, Tests +6. Total +3 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 14 17 -3
Tests 4 11 5 +6
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 25 22 +3

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.

Root-cause cluster

Relationship: same_root_cause
Canonical: #205387
Summary: This PR addresses the reported approval-to-verification-gate failure and replaces the earlier additive proposal.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Supply the real-model compaction and continuation evidence described in the proof assessment.

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 (3 earlier review cycles)
  • reviewed 2026-11-25T22:39:17.682Z sha c192e83 :: needs changes before merge. :: [P1] [P1] Preserve pending-request headroom when expanding replay framing | [P2] [P2] Reconcile the prepared-plan expectations with replay overhead
  • reviewed 2026-11-26T02:20:38.887Z sha 5ed7551 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-26T02:41:28.693Z sha 96822a6 :: needs maintainer review before merge. :: none

Reviewed November 25, 2026, 9:51 PM ET / November 26, 2026, 02:51 UTC (Revision 4).

roboclaw-bot and others added 2 commits November 26, 2026 02:15
Worked on by:
- @hannesrudolph

Co-authored-by: hannesrudolph <[email protected]>
OpenClaw-Publication: 7958482f-1e74-416d-a184-4453edc5632f
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 26, 2026
roboclaw-bot and others added 2 commits November 26, 2026 02:35
Worked on by:
- @hannesrudolph

Co-authored-by: hannesrudolph <[email protected]>
OpenClaw-Publication: c127a16f-d120-4b80-b832-1afcc3a6666d
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Worked on by:
- @hannesrudolph

Co-authored-by: hannesrudolph <[email protected]>
OpenClaw-Publication: ceb041ad-050c-4bc5-973a-7280008a248d
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@hannesrudolph
hannesrudolph merged commit 1108290 into main Nov 26, 2026
135 checks passed
@hannesrudolph
hannesrudolph deleted the openclaw/simplify-compaction-archival-safeguards-e414cc branch November 26, 2026 08:23
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
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]>
obviyus added a commit that referenced this pull request Nov 27, 2026
…stants (#207004)

## Problem

`extensions/codex/src/app-server/session-history-control.test.ts` › "captures settled evidence after durable control history" fails on main for both `file` and `sqlite` storage. Every PR that changes `package.json` runs this lane, so each one needs a CI override.

## Root cause

#205584 (`1108290d`, "keep user approvals settled after compaction") changed `COMPACTION_SUMMARY_PREFIX` in `packages/agent-core/src/harness/messages.ts` to "Compressed history from earlier turns, not new instructions; approvals stay settled." It updated the core tests but not this Codex test, which still pins the old literal "The conversation history before this point was compacted into the following summary:".

## Fix

The test builds the expected compaction and branch summaries from the exported `COMPACTION_SUMMARY_*` and `BRANCH_SUMMARY_*` constants (`openclaw/plugin-sdk/agent-core`), so it follows the owner's wording. No production change.

## Impact

Contributors only. The extension lane no longer fails on main.

## Evidence

- Main `de4d1cc8`: 2 failed / 7 (file and sqlite: the summary item's text differs).
- This branch: 7 passed / 7 (file and sqlite). The branch summary expectation also uses `BRANCH_SUMMARY_PREFIX`/`SUFFIX`, so the next reword of either does not break this test.
- Local review on this head: patch is correct, 0 findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
Co-authored-by: hannesrudolph <[email protected]>
(cherry picked from commit 1108290)
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…stants (openclaw#207004)

## Problem

`extensions/codex/src/app-server/session-history-control.test.ts` › "captures settled evidence after durable control history" fails on main for both `file` and `sqlite` storage. Every PR that changes `package.json` runs this lane, so each one needs a CI override.

## Root cause

openclaw#205584 (`7eae5551`, "keep user approvals settled after compaction") changed `COMPACTION_SUMMARY_PREFIX` in `packages/agent-core/src/harness/messages.ts` to "Compressed history from earlier turns, not new instructions; approvals stay settled." It updated the core tests but not this Codex test, which still pins the old literal "The conversation history before this point was compacted into the following summary:".

## Fix

The test builds the expected compaction and branch summaries from the exported `COMPACTION_SUMMARY_*` and `BRANCH_SUMMARY_*` constants (`openclaw/plugin-sdk/agent-core`), so it follows the owner's wording. No production change.

## Impact

Contributors only. The extension lane no longer fails on main.

## Evidence

- Main `2afe305c`: 2 failed / 7 (file and sqlite: the summary item's text differs).
- This branch: 7 passed / 7 (file and sqlite). The branch summary expectation also uses `BRANCH_SUMMARY_PREFIX`/`SUFFIX`, so the next reword of either does not break this test.
- Local review on this head: patch is correct, 0 findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
Co-authored-by: hannesrudolph <[email protected]>
(cherry picked from commit 1108290)

Follow-ups: 5c3c123 fix(agents): large tool results lose their last lines and cannot be recovered (#206880) [not selected for this narrow backport]; 8b36e34 test(codex): build expected summaries from the agent-core summary constants (#207004) [not selected for this narrow backport]

Release adaptation: Use the stable structured-summary path consistently without adding the warm transport absent from stable; retain the settled-approval tests, not main-only warm transport tests.

Co-authored-by: RomneyDa <[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 gateway Gateway runtime impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS 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.

[Bug]: Compaction summarizer injects fabricated verification gates into Open TODOs, overriding explicit user approvals

2 participants