Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(read-lifecycle): keep Reads fresh after a failed Edit or Write (#4461)

HetCreep4c3799fd8156
diff --git a/headroom/transforms/read_lifecycle.py b/headroom/transforms/read_lifecycle.py
index 71baa8e86..903722653 100644
--- a/headroom/transforms/read_lifecycle.py
+++ b/headroom/transforms/read_lifecycle.py
@@ -96,6 +96,16 @@ class ReadLifecycleResult:
ccr_hashes: list[str] = field(default_factory=list)
+def _rejected_before_running(content: Any) -> bool:
+ """True when a tool_result's text is a ``<tool_use_error>`` validation error."""
+ if isinstance(content, list):
+ content = next(
+ (b.get("text") for b in content if isinstance(b, dict) and b.get("type") == "text"),
+ None,
+ )
+ return isinstance(content, str) and content.lstrip().startswith("<tool_use_error>")
+
+
class ReadLifecycleManager:
"""Event-driven Read lifecycle management.
@@ -240,6 +250,7 @@ class ReadLifecycleManager:
Groups all Read/Edit/Write operations by file_path for lifecycle analysis.
"""
file_ops: dict[str, list[FileOperation]] = defaultdict(list)
+ failed_ids = self._failed_tool_use_ids(messages)
for tc_id, (name, file_path, offset, limit) in tool_metadata.items():
if not file_path:
@@ -247,7 +258,8 @@ class ReadLifecycleManager:
if name in _READ_TOOL_NAMES:
operation = "read"
- elif name in _MUTATING_TOOL_NAMES:
+ elif name in _MUTATING_TOOL_NAMES and tc_id not in failed_ids:
+ # A failed Edit/Write left the file unchanged, so earlier Reads stay valid.
operation = "edit"
else:
continue
@@ -271,6 +283,33 @@ class ReadLifecycleManager:
return dict(file_ops)
+ @staticmethod
+ def _failed_tool_use_ids(messages: list[dict[str, Any]]) -> set[str]:
+ """Ids of Anthropic tool_use blocks that were rejected before they ran.
+
+ Only an is_error tool_result whose text is a ``<tool_use_error>`` (the
+ harness's pre-execution validation, e.g. "String to replace not found")
+ proves the file was not touched. Any other error, such as a call that was
+ interrupted and "may have partially or fully completed", still counts as
+ an edit.
+ """
+ failed: set[str] = set()
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ if not (
+ isinstance(block, dict)
+ and block.get("type") == "tool_result"
+ and block.get("is_error")
+ ):
+ continue
+ tool_use_id = block.get("tool_use_id")
+ if isinstance(tool_use_id, str) and _rejected_before_running(block.get("content")):
+ failed.add(tool_use_id)
+ return failed
+
def _find_tool_call_msg_index(
self, messages: list[dict[str, Any]], tool_call_id: str
) -> int | None:
diff --git a/tests/test_transforms/test_read_lifecycle.py b/tests/test_transforms/test_read_lifecycle.py
index be27c5f7c..5c184378f 100644
--- a/tests/test_transforms/test_read_lifecycle.py
+++ b/tests/test_transforms/test_read_lifecycle.py
@@ -142,6 +142,7 @@ def make_anthropic_tool_result(tool_call_id: str, content: str) -> dict:
LARGE_CONTENT = "x" * 2000 # Well above min_size_bytes
SMALL_CONTENT = "tiny" # Below min_size_bytes
+REJECTED_EDIT = "<tool_use_error>String to replace not found in file.</tool_use_error>"
# =============================================================================
@@ -436,6 +437,94 @@ class TestAnthropicFormat:
user_msg = result.messages[1]
assert user_msg["content"][0]["content"] == LARGE_CONTENT
+ def test_failed_edit_does_not_make_read_stale(self):
+ """A tool_result with is_error means the edit did not happen."""
+ mgr = ReadLifecycleManager(ReadLifecycleConfig(enabled=True))
+
+ failed = make_anthropic_tool_result("e1", REJECTED_EDIT)
+ failed["content"][0]["is_error"] = True
+ messages = [
+ make_anthropic_read("r1", "/src/app.py"),
+ make_anthropic_tool_result("r1", LARGE_CONTENT),
+ make_anthropic_edit("e1", "/src/app.py"),
+ failed,
+ ]
+
+ result = mgr.apply(messages)
+ assert result.reads_stale == 0
+ assert result.reads_fresh == 1
+ assert result.messages[1]["content"][0]["content"] == LARGE_CONTENT
+
+ def test_successful_edit_after_failed_edit_still_makes_read_stale(self):
+ mgr = ReadLifecycleManager(ReadLifecycleConfig(enabled=True))
+
+ failed = make_anthropic_tool_result("e1", REJECTED_EDIT)
+ failed["content"][0]["is_error"] = True
+ messages = [
+ make_anthropic_read("r1", "/src/app.py"),
+ make_anthropic_tool_result("r1", LARGE_CONTENT),
+ make_anthropic_edit("e1", "/src/app.py"),
+ failed,
+ make_anthropic_edit("e2", "/src/app.py"),
+ make_anthropic_tool_result("e2", "edit success"),
+ ]
+
+ result = mgr.apply(messages)
+ assert result.reads_stale == 1
+
+ def test_interrupted_edit_still_makes_read_stale(self):
+ """An error that is not a pre-run rejection may have changed the file."""
+ mgr = ReadLifecycleManager(ReadLifecycleConfig(enabled=True))
+
+ failed = make_anthropic_tool_result(
+ "e1",
+ "Interrupted: the response that made this tool call was stopped while "
+ "the call was running; it may have partially or fully completed.",
+ )
+ failed["content"][0]["is_error"] = True
+ messages = [
+ make_anthropic_read("r1", "/src/app.py"),
+ make_anthropic_tool_result("r1", LARGE_CONTENT),
+ make_anthropic_edit("e1", "/src/app.py"),
+ failed,
+ ]
+
+ result = mgr.apply(messages)
+ assert result.reads_stale == 1
+
+ def test_rejected_edit_with_text_block_content_keeps_read_fresh(self):
+ mgr = ReadLifecycleManager(ReadLifecycleConfig(enabled=True))
+
+ failed = make_anthropic_tool_result("e1", "")
+ failed["content"][0]["content"] = [{"type": "text", "text": REJECTED_EDIT}]
+ failed["content"][0]["is_error"] = True
+ messages = [
+ make_anthropic_read("r1", "/src/app.py"),
+ make_anthropic_tool_result("r1", LARGE_CONTENT),
+ make_anthropic_edit("e1", "/src/app.py"),
+ failed,
+ ]
+
+ result = mgr.apply(messages)
+ assert result.reads_stale == 0
+ assert result.messages[1]["content"][0]["content"] == LARGE_CONTENT
+
+ def test_error_result_with_non_string_tool_use_id_is_ignored(self):
+ mgr = ReadLifecycleManager(ReadLifecycleConfig(enabled=True))
+
+ bad = make_anthropic_tool_result("e1", REJECTED_EDIT)
+ bad["content"][0]["tool_use_id"] = ["e1"]
+ bad["content"][0]["is_error"] = True
+ messages = [
+ make_anthropic_read("r1", "/src/app.py"),
+ make_anthropic_tool_result("r1", LARGE_CONTENT),
+ bad,
+ ]
+
+ result = mgr.apply(messages)
+ assert result.reads_fresh == 1
+ assert result.messages[1]["content"][0]["content"] == LARGE_CONTENT
+
class TestCCRStoreIntegration:
"""Lifecycle manager stores originals in CCR."""