Skip to content

The agent that grows with you

fix(compression): prune-only then full compaction keeps one Skill Safety Rule

Teknium06688515193a
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index ea73e5bb3e9..4e9883409db 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -5561,7 +5561,7 @@ Write only the summary body. Do not include any preamble or prefix."""
head/tail compress at all (#61932); tool-call arguments are never rewritten by pruning."""
compressed = self._assemble_head(messages, compress_start)
tail_messages = self._assemble_tail(messages, compress_end, scan.tail_start, scan.summary_indices)
- summary = with_skill_safety_rule(summary, [*compressed, *tail_messages])
+ summary, compressed, tail_messages = with_skill_safety_rule(summary, compressed, tail_messages)
summary_role, merge_into_tail, force_user_leading, first_tail_visible_idx = (
self._summary_placement(compressed, tail_messages, compress_start)
)
diff --git a/agent/context_compressor_tail.py b/agent/context_compressor_tail.py
index bc8bc493990..590e0ee0ec9 100644
--- a/agent/context_compressor_tail.py
+++ b/agent/context_compressor_tail.py
@@ -103,16 +103,25 @@ SKILL_SAFETY_RULE = (
)
-def with_skill_safety_rule(summary: str, kept_messages: list[dict[str, Any]]) -> str:
- """*summary* plus :data:`SKILL_SAFETY_RULE` when it or a message kept beside it carries a prune marker
- (summary-side ``## Pruned Skills`` markers, Phase-1 and lean-demoted ``skill_view`` stubs); else unchanged."""
+def with_skill_safety_rule(
+ summary: str, head: list[dict[str, Any]], tail: list[dict[str, Any]],
+) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]]]:
+ """``(summary, head, tail)`` carrying :data:`SKILL_SAFETY_RULE` exactly once when the summary or a kept row holds a
+ prune marker (summary-side ``## Pruned Skills`` markers, Phase-1 and lean-demoted ``skill_view`` stubs). A kept
+ prune-only stub's copy (:func:`with_pruned_row_skill_safety_rule`) moves onto the handoff: compaction is the
+ sanctioned rewrite, and the token-budget tail often keeps a stub the count-protected prune-only tail ruled."""
from agent.context_compressor import SKILL_PRUNED_MARKER_PREFIX, _content_text_for_contains
- if SKILL_SAFETY_RULE in summary:
- return summary
- texts = (summary, *(_content_text_for_contains(m.get("content")) for m in kept_messages if isinstance(m, dict)))
- if not any(SKILL_PRUNED_MARKER_PREFIX in text for text in texts):
- return summary
- return f"{summary}{_SKILL_SAFETY_SUFFIX}"
+
+ def unruled(rows):
+ return [{**m, "content": without_skill_safety_rule(m["content"])}
+ if isinstance(m, dict) and m.get("role") != "system" and isinstance(m.get("content"), str)
+ and SKILL_SAFETY_RULE in m["content"] else m for m in rows]
+
+ head, tail = unruled(head), unruled(tail)
+ texts = (summary, *(_content_text_for_contains(m.get("content")) for m in (*head, *tail) if isinstance(m, dict)))
+ if any(SKILL_SAFETY_RULE in text for text in texts) or not any(SKILL_PRUNED_MARKER_PREFIX in t for t in texts):
+ return summary, head, tail
+ return f"{summary}{_SKILL_SAFETY_SUFFIX}", head, tail
_SKILL_SAFETY_SUFFIX = f"\n\n{SKILL_SAFETY_RULE}"
diff --git a/tests/agent/test_compression_skill_safety_single_copy.py b/tests/agent/test_compression_skill_safety_single_copy.py
new file mode 100644
index 00000000000..3aa5f22b62a
--- /dev/null
+++ b/tests/agent/test_compression_skill_safety_single_copy.py
@@ -0,0 +1,53 @@
+"""A compacted transcript carries the Skill Safety Rule exactly once.
+
+Prune-only attaches the rule to a ``skill_view`` prune stub (it has no handoff to ride) and protects the tail by row
+count; a later full compaction keeps the tail by token budget, so that ruled stub can survive beside a handoff that
+gets the rule too.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from agent.context_compressor import SKILL_PRUNED_MARKER_PREFIX, ContextCompressor
+from agent.context_compressor_tail import SKILL_SAFETY_RULE
+
+
+def _texts(messages):
+ return "\n".join(str(m.get("content") or "") for m in messages)
+
+
+def _transcript():
+ messages = [{"role": "system", "content": "sys"}]
+ for i in range(30):
+ messages += [{"role": "user", "content": f"q{i} " + "facts " * 300},
+ {"role": "assistant", "content": f"a{i} " + "detail " * 1500}]
+ messages.append({"role": "user", "content": "build the pdf"})
+ calls = [("skill_view", '{"name":"pdf"}', "P" * 9000)]
+ calls += [("terminal", '{"cmd":"ls"}', ch * 9000) for ch in "AB"]
+ calls += [("terminal", '{"cmd":"ls"}', "ok")] * 5
+ for i, (tool, args, content) in enumerate(calls):
+ messages += [
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": f"c{i}", "type": "function", "function": {"name": tool, "arguments": args}}]},
+ {"role": "tool", "tool_call_id": f"c{i}", "content": content},
+ ]
+ messages += [{"role": "assistant", "content": "done"}, {"role": "user", "content": "latest ask"}]
+ return messages
+
+
+def test_prune_only_then_full_compaction_keeps_one_skill_safety_rule():
+ with patch("agent.context_compressor.get_model_context_length", return_value=1_000_000):
+ comp = ContextCompressor(
+ model="test/model", quiet_mode=True, threshold_percent=0.5, protect_first_n=2, protect_last_n=4,
+ proactive_prune_tokens=48_000, proactive_prune_min_result_chars=8_000,
+ )
+ pruned, count = comp.prune_tool_results_only(_transcript(), current_tokens=120_000)
+ assert count and _texts(pruned).count(SKILL_SAFETY_RULE) == 1
+
+ response = MagicMock()
+ response.choices = [MagicMock()]
+ response.choices[0].message.content = "## Goal\nOld chat.\n\n## Completed Actions\n1. talked."
+ with patch("agent.context_compressor.call_llm", return_value=response):
+ compacted = comp.compress(pruned, force=True)
+
+ assert SKILL_PRUNED_MARKER_PREFIX in _texts(compacted)
+ assert _texts(compacted).count(SKILL_SAFETY_RULE) == 1