Skip to content

The agent that grows with you

fix(compression): salvage grown candidates before refusal

MindDragonLabsfb96247eaf1f
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 8c33b9be6c9..86baf5f1f34 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -350,6 +350,102 @@ _SUMMARY_END_MARKER = (
_MERGED_PRIOR_CONTEXT_HEADER = "[PRIOR CONTEXT — for reference only; not a new message]"
_MERGED_SUMMARY_DELIMITER = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]"
+_SALVAGE_TOOL_PLACEHOLDER = "[Old tool output cleared to save context space]"
+_SALVAGE_SUMMARY_MAX_CHARS = 8_000
+_SALVAGE_KEEP_RECENT_TOOLS = 2
+_SALVAGE_REASONING_KEYS = ("reasoning", "reasoning_content", "reasoning_details")
+
+
+def _looks_like_compaction_summary(msg: Dict[str, Any], content: str) -> bool:
+ # Only cap a standalone handoff. Merged carriers preserve a real tail ask
+ # in the same content string; truncating those could delete live user text.
+ if not content.rstrip().endswith(_SUMMARY_END_MARKER):
+ return False
+ if content.startswith(_MERGED_PRIOR_CONTEXT_HEADER):
+ return False
+ # Content heuristics alone must never authorize mutating a live user turn.
+ # Compressor-generated user-role summaries carry this private marker;
+ # ordinary user input does not.
+ if (
+ msg.get("role") == "user"
+ and not msg.get(COMPRESSED_SUMMARY_METADATA_KEY)
+ ):
+ return False
+ head = content[:280]
+ return (
+ bool(msg.get(COMPRESSED_SUMMARY_METADATA_KEY))
+ or "CONTEXT COMPACTION" in head
+ or "[CONTEXT COMPACTION]" in head
+ or "Conversation Summary" in head
+ )
+
+
+def salvage_grown_transcript(
+ original: List[Dict[str, Any]],
+ candidate: List[Dict[str, Any]],
+) -> Optional[List[Dict[str, Any]]]:
+ """Mechanically shrink a compression candidate, or return ``None``.
+
+ Already-compacted middles can be summarized slightly larger while retained
+ tool bodies, stale reasoning, or a synthetic todo snapshot tip the final
+ candidate over the input size. Work on copies and admit the salvage only
+ when the same rough estimator proves it is strictly smaller than the input.
+ """
+ if not candidate or not original:
+ return None
+ budget = estimate_messages_tokens_rough(original)
+ if budget <= 0:
+ return None
+
+ out: List[Dict[str, Any]] = []
+ tool_indices: List[int] = []
+ last_assistant_idx = -1
+ for msg in candidate:
+ if not isinstance(msg, dict):
+ out.append(msg)
+ continue
+ if msg.get("_todo_snapshot_synthetic") and msg.get("role") == "user":
+ continue
+ copied = dict(msg)
+ out.append(copied)
+ role = copied.get("role")
+ if role == "tool":
+ tool_indices.append(len(out) - 1)
+ elif role == "assistant":
+ last_assistant_idx = len(out) - 1
+
+ keep_tools = set(tool_indices[-_SALVAGE_KEEP_RECENT_TOOLS:])
+ for index, msg in enumerate(out):
+ if not isinstance(msg, dict):
+ continue
+ if msg.get("role") == "assistant" and index != last_assistant_idx:
+ for key in _SALVAGE_REASONING_KEYS:
+ msg.pop(key, None)
+ if msg.get("role") == "tool" and index not in keep_tools:
+ content = msg.get("content")
+ if isinstance(content, str) and len(content) > 200:
+ msg["content"] = _SALVAGE_TOOL_PLACEHOLDER
+ content = msg.get("content")
+ if (
+ isinstance(content, str)
+ and len(content) > _SALVAGE_SUMMARY_MAX_CHARS
+ and _looks_like_compaction_summary(msg, content)
+ ):
+ msg["content"] = (
+ content[:_SALVAGE_SUMMARY_MAX_CHARS].rstrip()
+ + "\n…[summary truncated so compaction can shrink]\n\n"
+ + _SUMMARY_END_MARKER
+ )
+
+ if not any(
+ isinstance(message, dict) and message.get("role") == "user"
+ for message in out
+ ):
+ return None
+ if estimate_messages_tokens_rough(out) < budget:
+ return out
+ return None
+
# Handoff prefixes that shipped in earlier releases. A summary persisted under
# one of these can be inherited into a resumed lineage (#35344); when it is
# re-normalized on re-compaction we must strip the OLD prefix too, otherwise the
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 77a8a4ab930..521c08d9289 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3386,6 +3386,25 @@ def compress_context(
# transcript stays untouched and durable.
_rough_in = estimate_messages_tokens_rough(messages)
_rough_out = estimate_messages_tokens_rough(compressed)
+ if _rough_out > _rough_in:
+ # Todo refresh and user-turn anchoring happen after the
+ # compressor's own size check, so they can tip a break-even
+ # candidate over. Give it one mechanical salvage pass.
+ from agent.context_compressor import salvage_grown_transcript
+
+ _salvaged = salvage_grown_transcript(messages, compressed)
+ if _salvaged is not None:
+ _salv_est = estimate_messages_tokens_rough(_salvaged)
+ if _salv_est < _rough_in:
+ logger.info(
+ "Compression salvage recovered a shrinking "
+ "transcript (session=%s, ~%s -> ~%s tokens)",
+ agent.session_id or "none",
+ f"{_rough_in:,}",
+ f"{_salv_est:,}",
+ )
+ compressed = _salvaged
+ _rough_out = _salv_est
if _rough_out > _rough_in:
logger.warning(
"Compression refused: compressed transcript would be "
diff --git a/tests/agent/test_salvage_grown_transcript.py b/tests/agent/test_salvage_grown_transcript.py
new file mode 100644
index 00000000000..920dd85a1c8
--- /dev/null
+++ b/tests/agent/test_salvage_grown_transcript.py
@@ -0,0 +1,119 @@
+"""Mechanical salvage for compression candidates that would grow."""
+
+from agent.context_compressor import (
+ COMPRESSED_SUMMARY_METADATA_KEY,
+ _SUMMARY_END_MARKER,
+ salvage_grown_transcript,
+)
+from agent.model_metadata import estimate_messages_tokens_rough
+
+
+def test_salvage_stubs_old_tools_and_drops_todo():
+ original = [
+ {"role": "user", "content": "go"},
+ {"role": "assistant", "content": "ok"},
+ {"role": "tool", "tool_call_id": "a", "content": "A" * 4000},
+ {"role": "tool", "tool_call_id": "b", "content": "B" * 4000},
+ {"role": "tool", "tool_call_id": "c", "content": "keep-latest"},
+ ]
+ grown = original + [
+ {
+ "role": "user",
+ "content": "Current todos:\n- [ ] x",
+ "_todo_snapshot_synthetic": True,
+ }
+ ]
+ assert estimate_messages_tokens_rough(grown) > estimate_messages_tokens_rough(original)
+
+ out = salvage_grown_transcript(original, grown)
+
+ assert out is not None
+ assert estimate_messages_tokens_rough(out) < estimate_messages_tokens_rough(original)
+ assert not any(m.get("_todo_snapshot_synthetic") for m in out)
+ tools = [m["content"] for m in out if m.get("role") == "tool"]
+ assert tools[-1] == "keep-latest"
+ assert any("cleared to save context space" in t for t in tools)
+
+
+def test_salvage_returns_none_when_nothing_can_shrink():
+ original = [{"role": "user", "content": "tiny"}]
+ huge = [{"role": "user", "content": "X" * 200_000}]
+
+ assert salvage_grown_transcript(original, huge) is None
+
+
+def test_salvage_caps_oversized_summary():
+ original = [
+ {"role": "user", "content": "ask " + ("o" * 12_000)},
+ {"role": "assistant", "content": "short reply"},
+ ]
+ grown = [
+ {
+ "role": "user",
+ "content": (
+ "[CONTEXT COMPACTION] "
+ + ("S" * 20_000)
+ + "\n\n"
+ + _SUMMARY_END_MARKER
+ ),
+ COMPRESSED_SUMMARY_METADATA_KEY: True,
+ },
+ {"role": "assistant", "content": "short reply"},
+ ]
+ assert estimate_messages_tokens_rough(grown) > estimate_messages_tokens_rough(original)
+
+ out = salvage_grown_transcript(original, grown)
+
+ assert out is not None
+ assert len(out[0]["content"]) < 12_000
+ assert "truncated so compaction can shrink" in out[0]["content"]
+ assert out[0]["content"].endswith(_SUMMARY_END_MARKER)
+
+
+def test_salvage_never_truncates_merged_summary_with_live_user_tail():
+ original = [{"role": "user", "content": "O" * 12_000}]
+ merged = [
+ {
+ "role": "user",
+ "content": (
+ "[CONTEXT COMPACTION] "
+ + ("S" * 20_000)
+ + "\n\n"
+ + _SUMMARY_END_MARKER
+ + "\n\nLIVE USER REQUEST"
+ ),
+ COMPRESSED_SUMMARY_METADATA_KEY: True,
+ }
+ ]
+
+ assert salvage_grown_transcript(original, merged) is None
+ assert merged[0]["content"].endswith("LIVE USER REQUEST")
+
+
+def test_salvage_does_not_cap_plain_user_text_quoting_summary_marker():
+ original = [{"role": "user", "content": "O" * 20_000}]
+ quoted = "ordinary user text " + ("Q" * 12_000) + "\n\n" + _SUMMARY_END_MARKER
+ candidate = [{"role": "user", "content": quoted}]
+
+ out = salvage_grown_transcript(original, candidate)
+
+ assert out is not None
+ assert out[0]["content"] == quoted
+ assert "truncated so compaction can shrink" not in out[0]["content"]
+
+
+def test_salvage_never_caps_unmarked_summary_shaped_live_user_text():
+ original = [{"role": "user", "content": "O" * 20_000}]
+ live_user_text = (
+ "[CONTEXT COMPACTION] "
+ + ("U" * 12_000)
+ + "\n\n"
+ + _SUMMARY_END_MARKER
+ )
+ candidate = [{"role": "user", "content": live_user_text}]
+
+ out = salvage_grown_transcript(original, candidate)
+
+ assert out is not None
+ assert out[0]["content"] == live_user_text
+ assert "truncated so compaction can shrink" not in out[0]["content"]
diff --git a/tests/run_agent/test_in_place_compaction.py b/tests/run_agent/test_in_place_compaction.py
index 21b41f19cd8..e78e63ce526 100644
--- a/tests/run_agent/test_in_place_compaction.py
+++ b/tests/run_agent/test_in_place_compaction.py
@@ -293,6 +293,60 @@ class TestInPlaceAntiGrowthGuard:
assert agent.session_id == sid
assert db.get_session(sid)["end_reason"] is None
+ def test_in_place_salvages_near_break_even_growth(self):
+ """Fat retained tool output + todo state should be salvaged and committed."""
+ from hermes_state import SessionDB
+ from agent.conversation_compression import compress_context
+ from agent.model_metadata import estimate_messages_tokens_rough
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ sid = "20260819_salvage"
+ _seed(db, sid, "salvage")
+ agent = _make_agent(db, sid, in_place=True)
+ agent._last_flushed_db_idx = 5
+
+ tool_calls = [
+ {"id": call_id, "function": {"name": "terminal", "arguments": "{}"}}
+ for call_id in ("c1", "c2", "c3")
+ ]
+ original = [
+ {"role": "user", "content": "do the work"},
+ {"role": "assistant", "content": "calling tools", "tool_calls": tool_calls},
+ {"role": "tool", "tool_call_id": "c1", "content": "OLD1 " + ("x" * 8000)},
+ {"role": "tool", "tool_call_id": "c2", "content": "OLD2 " + ("y" * 8000)},
+ {"role": "tool", "tool_call_id": "c3", "content": "keep-me " + ("z" * 100)},
+ {"role": "user", "content": "thanks"},
+ ]
+ grown = [
+ {"role": "user", "content": "[CONTEXT COMPACTION] " + ("S" * 200)},
+ {"role": "assistant", "content": "calling tools", "tool_calls": tool_calls},
+ {"role": "tool", "tool_call_id": "c1", "content": "OLD1 " + ("x" * 8000)},
+ {"role": "tool", "tool_call_id": "c2", "content": "OLD2 " + ("y" * 8000)},
+ {"role": "tool", "tool_call_id": "c3", "content": "keep-me " + ("z" * 100)},
+ {
+ "role": "user",
+ "content": "Current todos:\n- [ ] leftover",
+ "_todo_snapshot_synthetic": True,
+ },
+ ]
+ assert estimate_messages_tokens_rough(grown) > estimate_messages_tokens_rough(original)
+ compressor = getattr(agent, "context_compressor")
+ compressor.compress = (
+ lambda messages, current_tokens=None, focus_topic=None, force=False: grown
+ )
+
+ compressed, _sp = compress_context(
+ agent, original, approx_tokens=100_000, system_message="sys"
+ )
+
+ assert getattr(agent, "_last_compaction_in_place") is True
+ assert estimate_messages_tokens_rough(compressed) < estimate_messages_tokens_rough(original)
+ tool_bodies = [m.get("content") for m in compressed if m.get("role") == "tool"]
+ assert any(isinstance(body, str) and body.startswith("keep-me") for body in tool_bodies)
+ assert any("cleared to save context space" in (body or "") for body in tool_bodies)
+ assert not any(m.get("_todo_snapshot_synthetic") for m in compressed)
+
def test_in_place_still_commits_shrinking_compression(self):
"""The guard must not block legitimate compressions — a result SMALLER
than the input still commits in place (regression net for #83339)."""