Skip to content

The agent that grows with you

fix(agent): route every model-visible elision through the non-imitable compression marker (#121548)

ahisblessed77b9ea0831f1
diff --git a/agent/compression_marker.py b/agent/compression_marker.py
index b2a4a292790..8a62fe8bf93 100644
--- a/agent/compression_marker.py
+++ b/agent/compression_marker.py
@@ -29,3 +29,47 @@ _COMPRESSION_MARKER_RE = re.compile(
.replace(re.escape("{omitted:,}"), r"\d[\d,]*")
.replace(re.escape("{total:,}"), r"\d[\d,]*")
)
+
+# #121548 — every OTHER model-visible elision (turn text, summaries, skill bodies, diagnostics)
+# mints this shorter marker instead of the open-coded bare truncation idiom those renderers used
+# to compose, which the model imitated from replayed context into new durable writes. The first
+# sentence is byte-identical to the args marker's, so _COMPRESSION_MARKER_RE — and therefore the
+# dispatch-boundary guard in ``agent.tool_dispatch_helpers`` — rejects a copied marker regardless
+# of which renderer leaked it; only the tool-call-specific second sentence is dropped so the
+# marker still fits small caps (the clarify summary cap is 199 chars).
+_ELISION_MARKER_TEMPLATE = (
+ _COMPRESSION_MARKER_PREFIX
+ + " {omitted:,} of {total:,} chars omitted here by Hermes's context compressor.⟫"
+)
+
+
+def _elision_marker(omitted: int, total: int) -> str:
+ """Render the non-imitable elision marker with per-instance byte counts."""
+ return _ELISION_MARKER_TEMPLATE.format(omitted=omitted, total=total)
+
+
+def elide(text: str, limit: int) -> str:
+ """Cap ``text`` at ``limit`` chars, marking the elision with ``_elision_marker``.
+
+ Every model-visible renderer must truncate through here (#121548). ``text`` is
+ returned unchanged when it already fits. Otherwise the result is ``head + marker``
+ with accurate omitted/total counts and never exceeds ``limit`` (sized against the
+ widest rendering the counts can take), unless ``limit`` cannot hold the marker at
+ all, in which case the marker alone is returned.
+ """
+ if len(text) <= limit:
+ return text
+ total = len(text)
+ head_len = limit - len(_elision_marker(omitted=total, total=total))
+ if head_len <= 0:
+ return _elision_marker(omitted=total, total=total)
+ kept = text[:head_len].rstrip()
+ return kept + _elision_marker(omitted=total - len(kept), total=total)
+
+
+def elide_middle(text: str, head: int, tail: int) -> str:
+ """Keep ``head`` chars from the start and ``tail`` from the end, eliding the middle."""
+ if len(text) <= head + tail:
+ return text
+ marker = _elision_marker(omitted=len(text) - head - tail, total=len(text))
+ return text[:head] + marker + text[-tail:]
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index e1717fe84c4..45f0a695245 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -15,7 +15,12 @@ from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Sequence, Tuple
from agent.image_eviction_policy import outbound_image_retire_count
-from agent.compression_marker import _COMPRESSION_MARKER_PREFIX, _COMPRESSION_MARKER_TEMPLATE
+from agent.compression_marker import (
+ _COMPRESSION_MARKER_PREFIX,
+ _COMPRESSION_MARKER_TEMPLATE,
+ elide,
+ elide_middle,
+)
from agent.auxiliary_client import (
AuxiliaryExplicitCancellation,
_coerce_llm_message,
@@ -1004,9 +1009,9 @@ def _build_verbatim_user_section(turns: List[Dict[str, Any]]) -> str:
break
text = content.strip()
if len(text) > _LEAN_USER_MESSAGE_MAX_CHARS:
- text = text[:_LEAN_USER_MESSAGE_MAX_CHARS].rstrip() + " …[truncated]"
+ text = elide(text, _LEAN_USER_MESSAGE_MAX_CHARS)
if len(text) > remaining:
- text = text[:remaining].rstrip() + " …[truncated]"
+ text = elide(text, remaining)
collected.append("> " + text.replace("\n", "\n> "))
used += len(text)
if not collected:
@@ -1267,7 +1272,7 @@ def _compact_fallback_turn(value: Any) -> str:
text = re.sub(r"\bgh[pousr]_[A-Za-z0-9_]{8,}\b", "[REDACTED]", text)
text = re.sub(r"\s+", " ", text).strip()
if len(text) > _FALLBACK_TURN_MAX_CHARS:
- text = text[: _FALLBACK_TURN_MAX_CHARS - 15].rstrip() + " ...[truncated]"
+ text = elide(text, _FALLBACK_TURN_MAX_CHARS)
return re.sub(r"\bgh[pousr]_[A-Za-z0-9_.-]+", "[REDACTED]", text)
@@ -1768,7 +1773,6 @@ def _sum_clarify(name, args, content, content_len, line_count):
# Strictly below _PRUNE_MIN_CHARS so the summary survives later prune passes via the
# min_prune_chars guard and skips the >=200-char dedup.
max_summary_chars = _PRUNE_MIN_CHARS - 1
- truncation_marker = "...[truncated]"
parsed = _json_dict(content)
response = parsed.get("user_response")
# Batch clarify (``questions=[...]``) nests each answer inside ``responses[].user_response``
@@ -1797,7 +1801,7 @@ def _sum_clarify(name, args, content, content_len, line_count):
serialized = json.dumps(response, ensure_ascii=False).encode("utf-8", errors="backslashreplace")
summary = response_prefix + serialized.decode("utf-8")
if len(summary) > max_summary_chars:
- summary = summary[: max_summary_chars - len(truncation_marker)].rstrip() + truncation_marker
+ summary = elide(summary, max_summary_chars)
return summary
return "[clarify] asked user a question"
@@ -3466,7 +3470,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
if role == "assistant" and content:
content = strip_think_blocks(None, content)
if len(content) > self._CONTENT_MAX:
- content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:]
+ content = elide_middle(content, self._CONTENT_HEAD, self._CONTENT_TAIL)
if role == "tool":
parts.append(f"[TOOL RESULT {msg.get('tool_call_id', '')}]: {content}")
continue
@@ -4432,7 +4436,7 @@ Write only the summary body. Do not include any preamble or prefix."""
continue
text = re.sub(r"\s+", " ", text)
if len(text) > _ACTIVE_TASK_MAX_CHARS:
- text = text[: _ACTIVE_TASK_MAX_CHARS - 15].rstrip() + " ...[truncated]"
+ text = elide(text, _ACTIVE_TASK_MAX_CHARS)
return (
f"User asked (deterministic, from compacted turns): {text!r}\n"
"Historical only; newer protected-tail messages after this summary win."
diff --git a/agent/lsp/reporter.py b/agent/lsp/reporter.py
index d942186fe72..939e9ae8cc6 100644
--- a/agent/lsp/reporter.py
+++ b/agent/lsp/reporter.py
@@ -9,6 +9,8 @@ from __future__ import annotations
import html
from typing import Any, Dict, List
+from agent.compression_marker import elide
+
# ERROR only by default — warnings/info/hints would flood the agent.
SEVERITY_NAMES = {1: "ERROR", 2: "WARN", 3: "INFO", 4: "HINT"}
DEFAULT_SEVERITIES = frozenset({1})
@@ -71,11 +73,8 @@ def report_for_file(
def truncate(s: str, *, limit: int = MAX_TOTAL_CHARS) -> str:
- """Hard-cap a formatted summary string."""
- if len(s) <= limit:
- return s
- marker = "\n…[truncated]"
- return s[: limit - len(marker)] + marker
+ """Hard-cap a formatted summary string with the non-imitable elision marker."""
+ return elide(s, limit)
__all__ = ["SEVERITY_NAMES", "DEFAULT_SEVERITIES", "MAX_PER_FILE", "format_diagnostic", "report_for_file", "truncate"]
diff --git a/agent/skill_preprocessing.py b/agent/skill_preprocessing.py
index 9d2e40e11b1..bc7048c7672 100644
--- a/agent/skill_preprocessing.py
+++ b/agent/skill_preprocessing.py
@@ -6,6 +6,7 @@ import re
import subprocess
from pathlib import Path
+from agent.compression_marker import elide
from hermes_cli._subprocess_compat import IS_WINDOWS, windows_hide_flags
logger = logging.getLogger(__name__)
@@ -82,7 +83,7 @@ def run_inline_shell(command: str, cwd: Path | None, timeout: int) -> str:
# "interpreter never ran the command" signature (WSL stub without a distro) — say so.
return f"[inline-shell exit {completed.returncode} with no output: {command}]"
if len(output) > _INLINE_SHELL_MAX_OUTPUT:
- output = output[:_INLINE_SHELL_MAX_OUTPUT] + "...[truncated]"
+ output = elide(output, _INLINE_SHELL_MAX_OUTPUT)
return output
diff --git a/agent/verification_stop.py b/agent/verification_stop.py
index c054af8fbca..b5e17b8df07 100644
--- a/agent/verification_stop.py
+++ b/agent/verification_stop.py
@@ -9,6 +9,8 @@ import tempfile
from pathlib import Path
from typing import Any, Iterable
+from agent.compression_marker import elide
+
_MAX_CHANGED_PATHS_IN_NUDGE = 8
@@ -150,7 +152,7 @@ def _status_detail(status: dict[str, Any]) -> str:
parts.append(f"last command `{command}`")
if summary:
if len(summary) > 1200:
- summary = summary[:1200].rstrip() + "\n... [truncated]"
+ summary = elide(summary, 1200)
parts.append(f"last output:\n{summary}")
return "\n".join(parts)
diff --git a/tests/agent/lsp/test_reporter.py b/tests/agent/lsp/test_reporter.py
index b4f788c857e..cd14c33ddf2 100644
--- a/tests/agent/lsp/test_reporter.py
+++ b/tests/agent/lsp/test_reporter.py
@@ -43,7 +43,9 @@ def _diag(line=0, col=0, sev=1, code="E001", source="ls", msg="oops"):
def test_truncate_above_limit_appends_marker():
s = "x" * 10000
out = truncate(s, limit=200)
- assert out.endswith("[truncated]")
+ # Non-imitable elision marker (#121548), not the old bare truncation idiom.
+ assert "HERMES-CONTEXT-COMPRESSION" in out
+ assert out.endswith("⟫")
assert len(out) <= 200
diff --git a/tests/agent/test_compression_marker.py b/tests/agent/test_compression_marker.py
new file mode 100644
index 00000000000..9b5d2f51811
--- /dev/null
+++ b/tests/agent/test_compression_marker.py
@@ -0,0 +1,78 @@
+"""#121548: model-visible elision mints the non-imitable compression marker.
+
+The bare bracketed truncation idiom those renderers used to compose was imitated
+from replayed context into new durable writes (see #83435/#83714). All elision now
+routes through ``agent.compression_marker.elide`` / ``elide_middle``, and this file
+pins both the helpers and the source-level invariant that the imitable idiom never
+returns to ``agent/`` strings.
+"""
+from __future__ import annotations
+
+import pathlib
+import tokenize
+
+from agent.compression_marker import (
+ _COMPRESSION_MARKER_PREFIX,
+ _COMPRESSION_MARKER_RE,
+ elide,
+ elide_middle,
+)
+
+AGENT_ROOT = pathlib.Path(__file__).resolve().parents[2] / "agent"
+IMITABLE_MARKERS = ("...[truncated]", "…[truncated]", "... [truncated]", "… [truncated]")
+
+
+class TestElide:
+ def test_text_that_fits_is_returned_unchanged(self):
+ assert elide("hello", 5) == "hello"
+ assert elide("hello", 100) == "hello"
+
+ def test_elided_text_is_capped_with_accurate_counts(self):
+ text = "x" * 5000
+ out = elide(text, 700)
+ assert len(out) <= 700
+ kept = out.split(_COMPRESSION_MARKER_PREFIX, 1)[0]
+ assert kept and kept == "x" * len(kept)
+ omitted = len(text) - len(kept)
+ assert f"{omitted:,} of 5,000 chars omitted" in out
+ assert out.endswith("⟫")
+
+ def test_result_never_exceeds_limit(self):
+ for limit in (150, 199, 700, 1400, 4000):
+ assert len(elide("z" * 100_000, limit)) <= limit
+
+ def test_minted_marker_is_caught_by_the_dispatch_boundary_guard(self):
+ """A copied marker must refuse a durable write regardless of which renderer leaked it."""
+ for out in (elide("y" * 4000, 199), elide_middle("y" * 4000, 100, 100)):
+ assert _COMPRESSION_MARKER_RE.search(out)
+
+
+class TestElideMiddle:
+ def test_keeps_head_and_tail_and_reports_the_middle(self):
+ text = "a" * 100 + "b" * 5000 + "c" * 100
+ out = elide_middle(text, 100, 100)
+ assert out.startswith("a" * 100)
+ assert out.endswith("c" * 100)
+ assert "5,000 of 5,200 chars omitted" in out
+
+ def test_short_text_is_returned_unchanged(self):
+ assert elide_middle("short", 3, 3) == "short"
+
+
+def test_no_imitable_truncation_marker_in_agent_strings():
+ """The imitable idiom must appear nowhere in agent/ strings — comments only.
+
+ Regression for the open-coded renderers: the marker is minted by the shared
+ helpers now, so any such literal in a string token is a new imitation surface.
+ """
+ offenders = []
+ for path in sorted(AGENT_ROOT.rglob("*.py")):
+ with tokenize.open(str(path)) as fh:
+ for tok in tokenize.generate_tokens(fh.readline):
+ if tok.type != tokenize.STRING:
+ continue
+ for literal in IMITABLE_MARKERS:
+ if literal in tok.string:
+ rel = path.relative_to(AGENT_ROOT.parent)
+ offenders.append(f"{rel}:{tok.start[0]}: {literal}")
+ assert not offenders, "imitable truncation markers in agent/ strings:\n" + "\n".join(offenders)
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index f180956190e..b5fca9fc370 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -133,10 +133,12 @@ class TestSummarizeToolResultClarify:
summary = _summarize_tool_result("clarify", "{}", content)
# Strictly below the prune floor so a later prune pass can never
- # re-summarize the preserved answer away (idempotency below).
- assert len(summary) == _PRUNE_MIN_CHARS - 1
+ # re-summarize the preserved answer away (idempotency below). The exact
+ # length varies with the digit width of the elision marker's counts.
+ assert len(summary) <= _PRUNE_MIN_CHARS - 1
assert summary.startswith('[clarify] user responded: "AAA')
- assert summary.endswith("...[truncated]")
+ assert _COMPRESSION_MARKER_PREFIX in summary
+ assert summary.endswith("⟫")
assert (
_summarize_tool_result("clarify", "{}", summary)
== "[clarify] asked user a question"
diff --git a/tests/agent/test_skill_inline_shell_output.py b/tests/agent/test_skill_inline_shell_output.py
index c9250565729..f791b324155 100644
--- a/tests/agent/test_skill_inline_shell_output.py
+++ b/tests/agent/test_skill_inline_shell_output.py
@@ -10,3 +10,12 @@ def test_silent_nonzero_exit_returns_marker(tmp_path):
def test_nonzero_exit_with_stderr_keeps_the_diagnostic(tmp_path):
assert run_inline_shell('printf "diag" >&2; exit 3', tmp_path, 5) == "diag"
+
+def test_long_output_is_elided_with_non_imitable_marker(tmp_path):
+ """#121548: inline-shell output is embedded into skill bodies on every load."""
+ from agent.skill_preprocessing import _INLINE_SHELL_MAX_OUTPUT
+
+ out = run_inline_shell("printf 'a%.0s' {1..5000}", tmp_path, 5)
+ assert len(out) <= _INLINE_SHELL_MAX_OUTPUT
+ assert "HERMES-CONTEXT-COMPRESSION" in out
+ assert out.endswith("⟫")