Skip to content

The agent that grows with you

fix(compression): small and slash-invoked skills keep their reload marker across compaction

Teknium71e815def843
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index f8d3cbeae65..c3c72e6ac86 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -849,8 +849,6 @@ _PRUNE_MIN_CHARS = 200
# PR #44166 emitted ``[SKILL_PRUNED:`` but presence-checked ``[SKILL_PRUNED]``, making re-injection fire
# even when the marker had survived).
SKILL_PRUNED_MARKER_PREFIX = "[SKILL_PRUNED:"
-# Small skill_view results stay verbatim; shared by emit site and summarizer scan.
-_SKILL_VIEW_PRUNE_MIN_CHARS = 5000
# Bounds the re-injected "## Pruned Skills" block; newest-referenced win.
_MAX_PRUNED_SKILL_MARKERS = 20
@@ -874,8 +872,15 @@ def _extract_pruned_skill_names(text: str) -> list[str]:
return list(dict.fromkeys(m.group(1) for m in _SKILL_PRUNED_MARKER_RE.finditer(text or "")))
+def _skill_view_failed(content: Any) -> bool:
+ """True for a ``skill_view`` result that loaded nothing (``success: false``), so it carries no instructions to lose."""
+ return isinstance(content, str) and _json_dict(content).get("success") is False
+
+
def _collect_ghosted_skill_names(turns: list[dict[str, Any]]) -> list[str]:
- """Skill names about to be lost in compaction: demoted ``skill_view`` rows and raw, never-demoted bodies."""
+ """Skills about to be lost in compaction, whatever their size: marked or plain ``skill_view`` stubs, raw
+ ``skill_view`` bodies, and skills a ``/skill``, bundle or auto-load turn carried inline."""
+ from agent.skill_commands import skills_loaded_by_scaffold
call_id_to_skill: dict[str, str] = {}
for idx, skill in _skill_view_call_sites(turns):
for tc in turns[idx].get("tool_calls") or []:
@@ -885,8 +890,11 @@ def _collect_ghosted_skill_names(turns: list[dict[str, Any]]) -> list[str]:
names: list[str] = []
for msg in turns:
content = msg.get("content")
- names += _extract_pruned_skill_names(_content_text_for_contains(content))
- if msg.get("role") == "tool" and isinstance(content, str) and len(content) > _SKILL_VIEW_PRUNE_MIN_CHARS:
+ text = _content_text_for_contains(content)
+ names += _extract_pruned_skill_names(text)
+ if msg.get("role") == "user":
+ names += skills_loaded_by_scaffold(text)
+ elif msg.get("role") == "tool" and not _skill_view_failed(content):
names.append(call_id_to_skill.get(str(msg.get("tool_call_id") or ""), ""))
return [name for name in dict.fromkeys(names) if name]
@@ -940,6 +948,13 @@ def _synthetic_user_row(content: str) -> bool:
return content.lstrip().startswith(_SYNTHETIC_USER_ROW_PREFIXES)
+def _typed_user_text(content: str) -> str:
+ """A ``/skill``, bundle or auto-load turn as the user typed it (``/skill do X``); other text unchanged.
+ Its inline skill body is not the user's words — it is carried by a ``[SKILL_PRUNED: ...]`` marker instead."""
+ from agent.skill_commands import describe_skill_invocation, skills_loaded_by_scaffold
+ return (describe_skill_invocation(content, separator=" ") or "") if skills_loaded_by_scaffold(content) else content
+
+
def _build_verbatim_user_section(turns: list[dict[str, Any]]) -> str:
"""Compacted region's REAL user messages verbatim, newest-first under a char budget (straddler truncated); "" if none."""
collected: list[str] = []
@@ -947,7 +962,7 @@ def _build_verbatim_user_section(turns: list[dict[str, Any]]) -> str:
for msg in reversed(turns):
if msg.get("role") != "user":
continue
- content = _content_text_for_contains(msg.get("content"))
+ content = _typed_user_text(_content_text_for_contains(msg.get("content")))
if _synthetic_user_row(content):
continue
remaining = _LEAN_USER_MESSAGES_BUDGET_CHARS - used
@@ -1707,8 +1722,8 @@ def _sum_execute_code(name, args, content, content_len, line_count):
def _sum_skill_view(name, args, content, content_len, line_count):
skill = args.get("name", "?")
- # Ghost-skill defense: canonical marker says instructions are gone and how to reload.
- marker = " " + _skill_pruned_marker(str(skill)) if content_len > _SKILL_VIEW_PRUNE_MIN_CHARS else ""
+ # Ghost-skill defense: any loaded body, however small, leaves the marker saying it is gone and how to reload.
+ marker = "" if skill == "?" or _skill_view_failed(content) else " " + _skill_pruned_marker(str(skill))
return f"[skill_view] name={skill} ({content_len:,} chars)" + marker
@@ -4402,7 +4417,7 @@ Write only the summary body. Do not include any preamble or prefix."""
# display_kind notices are operational traffic, not user intent.
if msg.get("role") != "user" or cls._is_synthetic_compression_user_turn(msg) or msg.get("display_kind"):
continue
- text = _redact_compaction_text(_content_text_for_contains(msg.get("content")).strip())
+ text = _redact_compaction_text(_typed_user_text(_content_text_for_contains(msg.get("content"))).strip())
if not text:
continue
text = " ".join(text.split())
@@ -4429,7 +4444,7 @@ Write only the summary body. Do not include any preamble or prefix."""
for msg in reversed(messages):
if msg.get("role") != "user" or not _is_real_user_message(msg):
continue
- text = _redact_compaction_text(_content_text_for_contains(msg.get("content")).strip())
+ text = _redact_compaction_text(_typed_user_text(_content_text_for_contains(msg.get("content"))).strip())
if not text:
continue
if len(text) > _ACTIVE_TASK_MAX_CHARS:
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index 7a8035cfb00..40787e490c6 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -174,6 +174,28 @@ def describe_skill_invocation(content: Any, separator: str = " — ") -> Optiona
return label if name else None
+_AUTO_LOAD_HEADER_RE = re.compile(re.escape(_AUTO_LOAD_PREFIX) + r'([^"]*)' + _AUTO_LOAD_SUFFIX_RE.pattern)
+_BUNDLE_LOADED_RE = re.compile(r"^Skills loaded: (.+)$", re.MULTILINE)
+
+
+def skills_loaded_by_scaffold(content: Any) -> list[str]:
+ """Skill names a slash-skill, bundle/stacked or gateway auto-load turn carries inline; ``[]`` for any
+ other text. Only a complete activation header counts, so typed text that merely starts like one
+ (``[IMPORTANT: The "config" file is broken]``) is not mistaken for a skill load."""
+ if not isinstance(content, str):
+ return []
+ if content.startswith(_AUTO_LOAD_PREFIX):
+ return [m.group(1) for m in _AUTO_LOAD_HEADER_RE.finditer(content)] if _AUTO_LOAD_HEADER_RE.match(content) else []
+ if not content.startswith(_SKILL_INVOCATION_PREFIX):
+ return []
+ header = content.split("\n", 1)[0]
+ if _BUNDLE_MARKER in header:
+ loaded = _BUNDLE_LOADED_RE.search(content)
+ return [n.strip() for n in loaded.group(1).split(",") if n.strip()] if loaded else []
+ match = _SKILL_NAME_RE.match(content)
+ return [match.group(1)] if header.endswith(_SINGLE_SKILL_MARKER) and match and match.group(1) else []
+
+
def _cut_after(message: str, marker: str, stop_marker: str, find) -> Optional[str]:
"""Text between *marker* (located with ``find``) and *stop_marker*, stripped; None if absent/empty."""
marker_idx = find(marker)
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 60c07e473af..c1806e20e8f 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -222,7 +222,7 @@ class TestSummarizeToolResultSkillTools:
assert ok == f"[skills_list] category=devops 2 skills ({len(ok_content)} chars)"
assert failed.startswith("[skills_list] FAILED: skills dir unreadable")
# Control: skill_view really has a top-level ``name`` and keeps its stub.
- assert _summarize_tool_result("skill_view", json.dumps({"name": "github"}), "x" * 100) == "[skill_view] name=github (100 chars)"
+ assert _summarize_tool_result("skill_view", json.dumps({"name": "github"}), "x" * 100).startswith("[skill_view] name=github (100 chars)")
class TestSummarizeToolResultOutcome:
diff --git a/tests/agent/test_ghost_skill_pruning.py b/tests/agent/test_ghost_skill_pruning.py
index e2ff2a0346f..ba32dd9b311 100644
--- a/tests/agent/test_ghost_skill_pruning.py
+++ b/tests/agent/test_ghost_skill_pruning.py
@@ -18,6 +18,7 @@ Test patterns for the marker emit checks adapted from PR #32375
(@LeonSGP43) with credit.
"""
+import json
from unittest.mock import MagicMock, patch
from agent.context_compressor import (
@@ -75,12 +76,14 @@ class TestSkillPrunedMarkerEmit:
assert _skill_pruned_marker("docker-management") in summary
assert "reload with skill_view(name='docker-management')" in summary
- def test_small_skill_view_summary_not_marked(self):
+ def test_every_loaded_skill_view_is_marked_failed_views_are_not(self):
+ """Small skills lose their body to the stub too, so they get the marker; a failed view loaded nothing."""
summary = _summarize_tool_result(
"skill_view", '{"name":"docker-management"}', "x" * 1234
)
- assert summary == "[skill_view] name=docker-management (1,234 chars)"
- assert SKILL_PRUNED_MARKER_PREFIX not in summary
+ assert summary == "[skill_view] name=docker-management (1,234 chars) " + _skill_pruned_marker("docker-management")
+ failed = json.dumps({"success": False, "error": "Skill 'nope' not found. " + "Available: a, b. " * 30})
+ assert SKILL_PRUNED_MARKER_PREFIX not in _summarize_tool_result("skill_view", '{"name":"nope"}', failed)
def test_marker_extractor_round_trips_the_emitted_marker(self):
"""Emit and check sides share one canonical string.
@@ -248,6 +251,37 @@ class TestMarkerSurvivesRealCompress:
summary_text = self._summary_text_of(result)
assert _skill_pruned_marker("pdf") in summary_text
+ def test_slash_invoked_skill_is_marked_and_quoted_as_typed(self):
+ """A /skill turn carries its body inline: compaction lists the skill for reload and quotes only what
+ the user typed, never the skill body as "the user's actual words"."""
+ from agent.skill_commands import _build_skill_message
+ note = ('[IMPORTANT: The user has invoked the "probe-inv" skill, indicating they want '
+ "you to follow its instructions. The full skill content is loaded below.]")
+ body = "RULE: include INV-HERON.\n" + "skill body prose. " * 600
+ invocation = _build_skill_message({"name": "probe-inv", "content": body}, None, note,
+ user_instruction="remember PLUM-77")
+ c = _make_compressor(protect_first_n=1, protect_last_n=2, tail_mode="lean")
+ msgs = [
+ {"role": "system", "content": "System prompt"},
+ {"role": "user", "content": "start"},
+ {"role": "user", "content": invocation},
+ {"role": "assistant", "content": "INV-HERON noted. " + "w" * 400},
+ {"role": "user", "content": "continue " + "c" * 400},
+ {"role": "assistant", "content": "more work " + "z" * 500},
+ {"role": "user", "content": "latest ask"},
+ {"role": "assistant", "content": "ack"},
+ ]
+ with (
+ patch.object(c, "_find_tail_cut_by_tokens", return_value=6),
+ patch("agent.context_compressor.call_llm", return_value=self._mock_response("## Goal\nWork.")),
+ ):
+ result = c.compress(msgs, force=True)
+ summary_text = self._summary_text_of(result)
+ assert _skill_pruned_marker("probe-inv") in summary_text
+ assert "/probe-inv remember PLUM-77" in summary_text
+ assert "skill body prose" not in summary_text
+
+
class TestReinjectionBoundsAndRedaction:
# The cap is applied at the collection sites in _generate_summary /
# _build_static_fallback_summary; the helper itself is mechanical.