Skip to content

The agent that grows with you

fix(context-compressor): stop injecting an imitable truncation marker into replayed tool_calls

Daniel JB Clark262a6436faf0
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index df0b7b1bb80..2443a871967 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1347,6 +1347,27 @@ def evict_stale_outbound_tool_images(api_messages: List[Dict[str, Any]]) -> int:
return pruned
+# #83714 — the shrunk value is replayed back to the model as its OWN past
+# tool call on every subsequent turn. A bare, prose-shaped marker like
+# "...[truncated]" is exactly the kind of terse ellipsis abbreviation a
+# model is already inclined to produce, so a model conditioned on seeing
+# itself "get away with" that pattern in its own history will imitate it in
+# a *new* tool call — writing the literal marker into a file instead of the
+# real content (observed with deepseek-v4-pro; see PR #83752 for the
+# resulting file-corruption guard). This marker is deliberately NOT
+# prose-shaped: distinctive non-ASCII delimiters that don't occur in normal
+# code/text, an explicit "not real content" disclaimer, and a per-instance
+# character count that won't match the next omission point even if copied
+# verbatim — all raise the bar against a model treating this as a stylistic
+# convention worth reusing.
+_COMPRESSION_MARKER_TEMPLATE = (
+ "⟪HERMES-CONTEXT-COMPRESSION: {omitted:,} of {total:,} chars omitted here "
+ "by Hermes's context compressor. This is NOT part of the original tool "
+ "call and must never be reproduced in new output — always write full, "
+ "untruncated content.⟫"
+)
+
+
def _truncate_tool_call_args_json(args: str, head_chars: int = 200) -> str:
"""Shrink long string leaves in a tool-call arguments JSON blob, keeping it valid (providers 400 on malformed args)."""
try:
@@ -1356,7 +1377,12 @@ def _truncate_tool_call_args_json(args: str, head_chars: int = 200) -> str:
def _shrink(obj: Any) -> Any:
if isinstance(obj, str):
- return obj[:head_chars] + "...[truncated]" if len(obj) > head_chars else obj
+ if len(obj) > head_chars:
+ marker = _COMPRESSION_MARKER_TEMPLATE.format(
+ omitted=len(obj) - head_chars, total=len(obj)
+ )
+ return obj[:head_chars] + marker
+ return obj
if isinstance(obj, dict):
return {k: _shrink(v) for k, v in obj.items()}
if isinstance(obj, list):
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index cf67bfc3111..b07e7320dae 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -2370,7 +2370,7 @@ class TestTruncateToolCallArgsJson:
shrunk = shrink(original)
parsed = _json.loads(shrunk) # must not raise
assert parsed["path"] == "~/.hermes/skills/shopping/browser-setup-notes.md"
- assert parsed["content"].endswith("...[truncated]")
+ assert "HERMES-CONTEXT-COMPRESSION" in parsed["content"]
assert len(shrunk) < len(original)
@@ -2391,7 +2391,7 @@ class TestTruncateToolCallArgsJson:
assert parsed["enabled"] is True
assert parsed["timeout"] is None
assert parsed["items"] == [1, 2, 3]
- assert parsed["note"].endswith("...[truncated]")
+ assert "HERMES-CONTEXT-COMPRESSION" in parsed["note"]
@@ -2429,7 +2429,87 @@ class TestTruncateToolCallArgsJson:
# Must parse — otherwise downstream provider returns 400
parsed = _json.loads(shrunk)
assert parsed["path"] == "~/.hermes/skills/shopping/browser-setup-notes.md"
- assert parsed["content"].endswith("...[truncated]")
+ assert "HERMES-CONTEXT-COMPRESSION" in parsed["content"]
+
+
+class TestTruncationMarkerNotImitable:
+ """Regression tests for #83714.
+
+ A model replayed its own history containing the bare
+ ``"...[truncated]"`` marker and, in a later turn, imitated it —
+ writing the literal marker into a *new* tool call's ``new_string``
+ instead of real content, which the file tools then wrote straight to
+ disk (see PR #83752's write_file/patch_tool guard, the safety net for
+ when this still slips through). The compressor-side fix is to stop
+ injecting a marker that looks like something the model itself would
+ plausibly write.
+ """
+
+ def _helper(self):
+ from agent.context_compressor import _truncate_tool_call_args_json
+ return _truncate_tool_call_args_json
+
+ def test_old_bare_marker_no_longer_produced(self):
+ """The exact literal that caused #83714 must never come out of the
+ shrink helper again, in isolation or as a suffix."""
+ import json as _json
+ shrink = self._helper()
+ payload = _json.dumps({"path": "/f.py", "new_string": "y" * 600})
+ shrunk = _json.loads(shrink(payload))["new_string"]
+ assert "...[truncated]" not in shrunk
+ assert not shrunk.endswith("...[truncated]")
+
+ def test_marker_uses_distinctive_non_ascii_delimiters(self):
+ """The marker must be visually/structurally unlike prose a model
+ would naturally continue with — distinctive delimiters are one of
+ the deliberate anti-imitation properties (see
+ ``_COMPRESSION_MARKER_TEMPLATE``'s docstring)."""
+ import json as _json
+ shrink = self._helper()
+ payload = _json.dumps({"content": "x" * 1000})
+ shrunk = _json.loads(shrink(payload))["content"]
+ assert "⟪" in shrunk and "⟫" in shrunk
+
+ def test_marker_states_it_is_not_original_content(self):
+ import json as _json
+ shrink = self._helper()
+ payload = _json.dumps({"content": "x" * 1000})
+ shrunk = _json.loads(shrink(payload))["content"]
+ assert "NOT part of the original" in shrunk
+
+ def test_marker_carries_a_per_instance_char_count(self):
+ """The omitted/total counts vary per call, so a model that copies
+ the marker verbatim into an unrelated new tool call produces an
+ internally inconsistent (and thus more obviously wrong) string,
+ rather than a plausible-looking universal abbreviation token."""
+ import json as _json
+ shrink = self._helper()
+ # head_chars=200: a 300-char input omits 100, a 3000-char input omits 2800.
+ shrunk_short = _json.loads(shrink(_json.dumps({"c": "x" * 300})))["c"]
+ shrunk_long = _json.loads(shrink(_json.dumps({"c": "x" * 3000})))["c"]
+ assert shrunk_short != shrunk_long
+ assert "100 of 300 chars omitted" in shrunk_short
+ assert "2,800 of 3,000 chars omitted" in shrunk_long
+
+ def test_string_below_threshold_is_untouched(self):
+ """Strings at or under head_chars never get a marker at all — the
+ char-count check above only applies once shrinking actually kicks in."""
+ import json as _json
+ shrink = self._helper()
+ payload = _json.dumps({"c": "x" * 150})
+ parsed = _json.loads(shrink(payload))
+ assert parsed["c"] == "x" * 150
+
+ def test_shrunk_value_stays_a_plain_string(self):
+ """#11762 established that the shrunk JSON shape must match the
+ original (string leaf stays a string leaf) so strict providers
+ don't 400 on a type mismatch when the history is replayed. The
+ #83714 marker-text fix must not regress that invariant."""
+ import json as _json
+ shrink = self._helper()
+ payload = _json.dumps({"new_string": "z" * 500})
+ parsed = _json.loads(shrink(payload))
+ assert isinstance(parsed["new_string"], str)
class TestLazyContextResolution: