The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve structural record framing in lean summary sampling
joaomarcos04fe735c5747
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex b0300acd2cf..a1dea281be0 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -12,7 +12,7 @@ import reimport timeimport uuidfrom dataclasses import dataclass-from typing import Any, Dict, List, Optional, Tuple+from typing import Any, Dict, List, Optional, Sequence, Tuple, Unionfrom agent.image_eviction_policy import outbound_image_retire_countfrom agent.auxiliary_client import (@@ -3302,8 +3302,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginargs = args[:self._TOOL_ARGS_HEAD] + "..."return f" {fn.get('name', '?')}({args})"- def _serialize_for_summary(self, turns: List[Dict[str, Any]]) -> str:- """Serialize turns into labeled, redacted text for the summarizer."""+ def _serialize_records_for_summary(self, turns: List[Dict[str, Any]]) -> List[str]:+ """Serialize turns into a list of labeled, redacted records for the summarizer."""# Lazy import: agent_runtime_helpers pulls heavy transitive imports.from agent.agent_runtime_helpers import strip_think_blocksparts = []@@ -3320,12 +3320,16 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginif len(content) > self._CONTENT_MAX:content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:]if role == "tool":- parts.append(f"[TOOL RESULT {msg.get('tool_call_id', '')}]: {content}")+ parts.append(f"[TOOL RESULT {msg.get('tool_call_id', '')}]: {content.rstrip(chr(10))}")continueif role == "assistant" and msg.get("tool_calls", []):content += "\n[Tool calls:\n" + "\n".join(map(self._render_tool_call_for_summary, msg["tool_calls"])) + "\n]"- parts.append(f"[{role.upper()}]: {content}")- return "\n\n".join(parts)+ parts.append(f"[{role.upper()}]: {content.rstrip(chr(10))}")+ return parts++ def _serialize_for_summary(self, turns: List[Dict[str, Any]]) -> str:+ """Serialize turns into labeled, redacted text for the summarizer."""+ return "\n\n".join(self._serialize_records_for_summary(turns))def _fallback_anchors(self, turns_to_summarize: List[Dict[str, Any]]) -> Dict[str, list[str]]:"""Locally extractable anchors: user asks, actions, files, blockers, last dropped turns."""@@ -3545,16 +3549,19 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbreturn res@classmethod- def _sample_summary_input(cls, content: str) -> str:+ def _sample_summary_records(cls, records: Sequence[str]) -> str:"""Sample complete serialized records while retaining the character bound."""- if len(content) <= cls._SUMMARY_INPUT_MAX_CHARS:- return content+ if not records:+ return ""- records = content.split("\n\n")separator = "\n\n"- marker_template = "\n\n...[{elided:,} chars elided — recover via session_search]...\n\n"+ total_len = sum(len(r) for r in records) + len(separator) * (len(records) - 1)+ if total_len <= cls._SUMMARY_INPUT_MAX_CHARS:+ return separator.join(records)+n = max(1, min(cls._SAMPLED_INPUT_SLICES, len(records)))- marker_len = len(marker_template.format(elided=len(content)))+ marker_template = "\n\n...[{elided:,} chars elided — recover via session_search]...\n\n"+ marker_len = len(marker_template.format(elided=total_len))budget = max(cls._SUMMARY_INPUT_MAX_CHARS - marker_len * (n - 1), 1)target = max(1, budget // n)@@ -3566,8 +3573,13 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbselected: list[tuple[int, int]] = []for index, start in enumerate(starts):if index == len(starts) - 1:- start = max(0, len(records) - 1)+ # Anchor the last slice to the newest record at the end of the history.end = len(records)+ start = end - 1+ size = len(display_records[start])+ while start > 0 and size + len(separator) + len(display_records[start - 1]) <= target:+ start -= 1+ size += len(separator) + len(display_records[start])else:end = startsize = 0@@ -3586,12 +3598,14 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbcursor = 0for s, e in slices:if s > cursor:- elided = sum(map(len, records[cursor:s])) + len(separator) * (s - cursor)+ sep_count = (s - cursor) if cursor == 0 else (s - cursor + 1)+ elided = sum(len(records[i]) for i in range(cursor, s)) + len(separator) * sep_countparts.append(marker_template.format(elided=elided))parts.append(separator.join(display_records[s:e]))cursor = eif cursor < len(records):- elided = sum(map(len, records[cursor:])) + len(separator) * (len(records) - cursor - 1)+ sep_count = len(records) - cursor+ elided = sum(len(records[i]) for i in range(cursor, len(records))) + len(separator) * sep_countparts.append(marker_template.format(elided=elided))return "".join(parts)@@ -3617,6 +3631,29 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbresult = _render(selected)return result+ @classmethod+ def _sample_summary_input(+ cls,+ content: Union[str, Sequence[str]],+ records: Optional[Sequence[str]] = None,+ ) -> str:+ """Sample complete serialized records while retaining the character bound.++ Accepts either a sequence of serialized records (preserving record boundaries structurally)+ or a flat string for backward compatibility.+ """+ if records is not None:+ return cls._sample_summary_records(records)+ if not isinstance(content, str):+ return cls._sample_summary_records(content)+ if len(content) <= cls._SUMMARY_INPUT_MAX_CHARS:+ return content+ # Discard empty trailing fragments so an empty pseudo-record cannot become the tail anchor.+ records_list = [r for r in content.split("\n\n") if r.strip()]+ if not records_list:+ return content[:cls._SUMMARY_INPUT_MAX_CHARS]+ return cls._sample_summary_records(records_list)+def _fallback_to_main_for_compression(self, e: Exception, reason: str, failed_model: Optional[str] = None) -> None:@@ -3759,8 +3796,11 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb_collect_ghosted_skill_names(turns_to_summarize) + _extract_pruned_skill_names(self._previous_summary or "")))[:_MAX_PRUNED_SKILL_MARKERS]# Lean mode even-samples oversized input (one bounded request, never a second).- bound = self._sample_summary_input if getattr(self, "tail_mode", "lean") == "lean" else self._bound_summary_input- content_to_summarize = bound(self._serialize_for_summary(turns_to_summarize))+ if getattr(self, "tail_mode", "lean") == "lean":+ records = self._serialize_records_for_summary(turns_to_summarize)+ content_to_summarize = self._sample_summary_records(records)+ else:+ content_to_summarize = self._bound_summary_input(self._serialize_for_summary(turns_to_summarize))has_user_turn = getattr(self, "_summary_has_user_turn", None)if has_user_turn is None:has_user_turn = self._transcript_has_real_user_turn(turns_to_summarize)diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex 5cfd584c4a2..f71dce10fa5 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -1,6 +1,7 @@"""Tests for agent/context_compressor.py — compression logic, thresholds, truncation fallback."""import json+import reimport sqlite3import pytestimport time@@ -3352,6 +3353,110 @@ class TestSummaryPromptBounding:assert "oversized-mid" in sampledassert "...[record truncated:" in sampled+ def test_lean_sampling_preserves_multiparagraph_records_from_producer(self):+ """Messages with internal blank lines must be sampled as whole records, not split into pseudo-records."""+ cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARS+ compressor = ContextCompressor(+ model="test/model",+ threshold_percent=0.85,+ protect_first_n=2,+ protect_last_n=2,+ quiet_mode=True,+ tail_mode="lean",+ )+ # Create messages with multiple paragraphs separated by \n\n, aggregate exceeding cap+ messages = [+ {+ "role": "user" if i % 2 == 0 else "tool",+ "tool_call_id": f"call_{i:04d}" if i % 2 != 0 else None,+ "content": f"record-{i:04d} paragraph 1\n\nparagraph 2 filler " + ("x" * 600),+ }+ for i in range(500)+ ]+ messages.append({+ "role": "user",+ "content": "newest-user-msg para1\n\nnewest-user-msg para2 anchor",+ })++ records = compressor._serialize_records_for_summary(messages)+ sampled = compressor._sample_summary_records(records)++ assert len(sampled) <= cap+ # Every retained section between omission markers must start at an actual message boundary+ sections = [s.strip() for s in re.split(r"\n*\.\.\.\[[\d,]+ chars elided[^\n]*\.\.\.\n*", sampled) if s.strip()]+ for section in sections:+ assert section.startswith(("[USER]:", "[TOOL RESULT", "[ASSISTANT]:", "[SYSTEM]:")), (+ f"Retained record slice did not start at message boundary: {section[:40]!r}"+ )++ # The newest message must preserve its role label AND both paragraphs together+ assert "[USER]: newest-user-msg para1\n\nnewest-user-msg para2 anchor" in sampled++ def test_lean_sampling_newest_message_ending_in_blank_lines_anchors_record(self):+ """A newest message ending in blank lines must not produce an empty pseudo-record as tail anchor."""+ cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARS+ compressor = ContextCompressor(+ model="test/model",+ threshold_percent=0.85,+ protect_first_n=2,+ protect_last_n=2,+ quiet_mode=True,+ tail_mode="lean",+ )+ messages = [+ {"role": "user", "content": f"turn-{i:04d} " + ("y" * 600)}+ for i in range(400)+ ]+ messages.append({+ "role": "user",+ "content": "final prompt with trailing blank lines\n\n\n\n",+ })++ records = compressor._serialize_records_for_summary(messages)+ sampled = compressor._sample_summary_records(records)++ assert len(sampled) <= cap+ assert "final prompt with trailing blank lines" in sampled+ assert not sampled.rstrip().endswith("]...")++ def test_lean_sampling_omission_markers_account_separators_exactly(self):+ """Omission markers must account for record separators at gap boundaries without undercounting."""+ records = [f"[USER]: r{i:03d} " + ("z" * 10000) for i in range(30)]+ sampled = ContextCompressor._sample_summary_records(records)+ assert len(sampled) <= ContextCompressor._SUMMARY_INPUT_MAX_CHARS+ assert "chars elided" in sampled++ def test_generate_summary_lean_samples_structural_records(self):+ """_generate_summary in lean mode must feed complete multi-paragraph records to summarizer prompt."""+ compressor = ContextCompressor(+ model="test/model",+ threshold_percent=0.85,+ protect_first_n=2,+ protect_last_n=2,+ quiet_mode=True,+ tail_mode="lean",+ )+ messages = [+ {"role": "user", "content": f"msg-{i:04d} part1\n\npart2 " + ("w" * 500)}+ for i in range(400)+ ]+ messages.append({+ "role": "user",+ "content": "newest action item para1\n\nnewest action item para2",+ })+ resp = MagicMock()+ resp.choices = [MagicMock()]+ resp.choices[0].message = MagicMock()+ resp.choices[0].message.content = "## Historical Task Snapshot\nDone."++ with patch("agent.context_compressor.call_llm", return_value=resp) as mock_call:+ summary = compressor._generate_summary(messages)++ assert summary is not None+ assert mock_call.call_count == 1+ prompt = mock_call.call_args.kwargs["messages"][0]["content"]+ assert "[USER]: newest action item para1\n\nnewest action item para2" in prompt+def test_iterative_update_path_is_bounded(self):"""The iterative prompt (previous summary + new turns) must be boundedtoo — a pathological rehydrated handoff must not blow up the prompt."""