The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): failed skill views and auto-load file lists are not reloaded or quoted
Tekniuma36fb64f2808
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 898f9116a39..6d7ffbb853e 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -873,8 +873,11 @@ def _extract_pruned_skill_names(text: str) -> list[str]: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+ """True for a ``skill_view`` that loaded nothing: the raw failure payload or its ``[skill_view] … FAILED`` stub."""+ if not isinstance(content, str):+ return False+ return bool(_result_failure_suffix(content)) or (+ content.startswith("[skill_view] ") and " FAILED" in content.split(" (", 1)[0])def _collect_ghosted_skill_names(turns: list[dict[str, Any]]) -> list[str]:@@ -894,7 +897,7 @@ def _collect_ghosted_skill_names(turns: list[dict[str, Any]]) -> list[str]: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):+ elif msg.get("role") == "tool" and not _skill_view_failed(content) and not is_demoted_stub(text):names.append(call_id_to_skill.get(str(msg.get("tool_call_id") or ""), ""))return [name for name in dict.fromkeys(names) if name]@@ -1724,8 +1727,9 @@ 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: 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+ failed = _result_failure_suffix(content)+ marker = "" if skill == "?" or failed else " " + _skill_pruned_marker(str(skill))+ return f"[skill_view] name={skill}{failed} ({content_len:,} chars)" + marker# Runtime notices that clarify producers persisted as user_response before per-responsediff --git a/agent/context_compressor_tail.py b/agent/context_compressor_tail.pyindex e38ae3bcb11..3e749b4c4af 100644--- a/agent/context_compressor_tail.py+++ b/agent/context_compressor_tail.py@@ -53,7 +53,9 @@ def demote_stale_tail_tools(skill-marker rows untouched. A demoted ``skill_view`` body carries the canonical reload marker, as itsPhase-1 stub does, so the model does not act on instructions it no longer has (#32106). Returns a new list(untouched rows shared, demoted copied) and the number of rows demoted."""- from agent.context_compressor import SKILL_PRUNED_MARKER_PREFIX, _is_summary_stub, _rewritten, _skill_pruned_marker+ from agent.context_compressor import (+ SKILL_PRUNED_MARKER_PREFIX, _is_summary_stub, _result_failure_suffix, _rewritten, _skill_pruned_marker,+ )rounds_seen = 0protected: set[int] = set()@@ -76,7 +78,7 @@ def demote_stale_tail_tools(continuestub = _lean_recovery_stub(msg.get("tool_name") or "", len(content), session_id)skills = _skill_view_names_by_call_id(messages) if skills is None else skills- if skill := skills.get(str(msg.get("tool_call_id") or "")):+ if (skill := skills.get(str(msg.get("tool_call_id") or ""))) and not _result_failure_suffix(content):stub += " " + _skill_pruned_marker(skill)result[i] = _rewritten(msg, stub)demoted += 1diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex 40787e490c6..93e09127b1f 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -138,7 +138,10 @@ def _describe_auto_loaded_skill_turn(content: str) -> Optional[str]:footer_end = content.rfind(_SKILL_DIR_NOTE_END)if footer_end == -1:return f"/{name}" if name else None- tail = content[footer_end + len(_SKILL_DIR_NOTE_END):]+ tail = content[footer_end + len(_SKILL_DIR_NOTE_END):].lstrip()+ while block_end := next((end for start, end in _TRAILING_BLOCK_ENDS if tail.startswith(start)), None):+ cut = tail.find(block_end)+ tail = tail[cut + len(block_end):].lstrip() if cut >= 0 else ""if not tail.strip():return f"/{name}" if name else Nonereturn " ".join(tail.split()) or None@@ -324,6 +327,11 @@ _SKILL_DIR_NOTE = ("`templates/config.yaml`) against that directory, then run them ""with the terminal tool using the absolute path.")+# Closing text of the optional blocks _build_skill_message appends after the directory note; the+# auto-load describer skips them so they are never read as the user's typed request.+_SUPPORTING_FILES_END = "/scripts/foo.js`)."+_TRAILING_BLOCK_ENDS = (("[Skill config (", "\n]"), ("[Skill setup note: ", "\n"),+ ("[This skill has supporting files", _SUPPORTING_FILES_END))_SETUP_SKIPPED_NOTE = ("Required environment setup was skipped. Continue loading the skill ""and explain any reduced functionality if it matters."@@ -384,7 +392,7 @@ def _build_skill_message(parts.append(f'\nLoad any of these with skill_view(name="{skill_view_target}", 'f'file_path="<path>"), or run scripts directly by absolute path '- f"(e.g. `node {skill_dir}/scripts/foo.js`)."+ f"(e.g. `node {skill_dir}{_SUPPORTING_FILES_END}")stable_prefix = Noneif user_instruction:diff --git a/tests/agent/test_ghost_skill_pruning.py b/tests/agent/test_ghost_skill_pruning.pyindex c94bb3f8329..c9cac8c11ef 100644--- a/tests/agent/test_ghost_skill_pruning.py+++ b/tests/agent/test_ghost_skill_pruning.py@@ -26,6 +26,7 @@ from agent.context_compressor import (SKILL_PRUNED_MARKER_PREFIX,SUMMARY_PREFIX,ContextCompressor,+ _collect_ghosted_skill_names,_extract_pruned_skill_names,_reinject_pruned_skill_markers,_skill_pruned_marker,@@ -84,7 +85,13 @@ class TestSkillPrunedMarkerEmit:)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)+ failed_stub = _summarize_tool_result("skill_view", '{"name":"nope"}', failed)+ assert SKILL_PRUNED_MARKER_PREFIX not in failed_stub+ # Neither the raw failure nor its stub is listed for reload at a later compaction.+ for content in (failed, failed_stub):+ turns = _skill_view_pair("call_nope", "nope")+ turns[1]["content"] = content+ assert _collect_ghosted_skill_names(turns) == []def test_marker_extractor_round_trips_the_emitted_marker(self):"""Emit and check sides share one canonical string.@@ -211,7 +218,7 @@ class TestMarkerSurvivesRealCompress:"1. Loaded some skills and worked on the report.")with (- patch.object(c, "_find_tail_cut_by_tokens", return_value=7),+ patch.object(c, "_find_tail_cut_by_tokens", return_value=9),patch("agent.context_compressor.call_llm", return_value=drop_response) as mock_call,@@ -261,10 +268,19 @@ class TestMarkerSurvivesRealCompress:body = "RULE: include INV-HERON.\n" + "skill body prose. " * 600invocation = _build_skill_message({"name": "probe-inv", "content": body}, Path("/skills/probe-inv"), note,user_instruction="remember PLUM-77")+ # A gateway auto-load turn whose skill lists supporting files: the request follows those blocks.+ auto = _build_skill_message(+ {"name": "gw-skill", "content": "gateway skill body", "linked_files": {"references": ["references/gw.md"]}},+ Path("/skills/gw-skill"),+ '[IMPORTANT: The "gw-skill" skill is auto-loaded. Follow its instructions for this session.]',+ ) + "\n\nhello from the gateway"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": "assistant", "content": "ok"},+ {"role": "user", "content": auto},+ {"role": "assistant", "content": "hi"},{"role": "user", "content": invocation},{"role": "assistant", "content": "INV-HERON noted. " + "w" * 400},{"role": "user", "content": "continue " + "c" * 400},@@ -273,7 +289,7 @@ class TestMarkerSurvivesRealCompress:{"role": "assistant", "content": "ack"},]with (- patch.object(c, "_find_tail_cut_by_tokens", return_value=6),+ patch.object(c, "_find_tail_cut_by_tokens", return_value=9),patch("agent.context_compressor.call_llm", return_value=self._mock_response("## Goal\nWork.")),):result = c.compress(msgs, force=True)@@ -282,6 +298,8 @@ class TestMarkerSurvivesRealCompress:assert "/probe-inv remember PLUM-77" in summary_textassert "skill body prose" not in summary_textassert "scripts/foo.js" not in summary_text # the scaffold footer's example path is not session work+ assert _skill_pruned_marker("gw-skill") in summary_text+ assert "> hello from the gateway" in summary_text and "references/gw.md" not in summary_textclass TestReinjectionBoundsAndRedaction: