Skip to content

The agent that grows with you

fix(memory): omit current_entries on batch abort

686f6c61840c41e9a2b8
diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.py
index 80334d964d2..70199b2ede3 100644
--- a/tests/tools/test_memory_tool.py
+++ b/tests/tools/test_memory_tool.py
@@ -258,11 +258,38 @@ class TestMemoryConsolidationGracefulDegrade:
for _ in range(cap):
r = store.apply_batch("memory", bad_batch)
assert r["success"] is False
- assert "current_entries" in r # still actionable under cap
+ assert "current_entries" not in r
+ assert "No operations were applied" in r["error"]
r = store.apply_batch("memory", bad_batch)
assert r["success"] is False
assert r["done"] is True
assert "continue with your reply" in r["error"]
+ assert "current_entries" not in r
+
+ def test_apply_batch_abort_does_not_echo_store(self, store):
+ """A failed consolidation must not pay the whole MEMORY.md back (#97316)."""
+ store.add("memory", "fact A that is unique and long enough to matter")
+ store.add("memory", "fact B stays in the store after the abort")
+ result = store.apply_batch(
+ "memory",
+ [{"action": "remove", "old_text": "this substring is not in any entry"}],
+ )
+ assert result["success"] is False
+ assert "current_entries" not in result
+ payload = json.dumps(result)
+ assert "fact A that is unique" not in payload
+ assert "fact B stays in the store" not in payload
+ assert "No operations were applied" in result["error"]
+ assert store.memory_entries == [
+ "fact A that is unique and long enough to matter",
+ "fact B stays in the store after the abort",
+ ]
+
+ def test_single_replace_still_echoes_entries_on_miss(self, store):
+ store.add("memory", "fact A")
+ result = store.replace("memory", "nonexistent", "new")
+ assert result["success"] is False
+ assert result["current_entries"] == ["fact A"]
def test_success_and_turn_boundary_reset_failure_budget(self, store):
store.add("memory", "real entry")
@@ -794,7 +821,8 @@ class TestBatchRefusesToEmptyNonEmptyStore:
result = store.apply_batch(target, [{"action": "remove", "old_text": seed}])
assert result["success"] is False
- assert "current_entries" in result # actionable, counts toward degrade budget
+ assert "current_entries" not in result # batch abort never echoes the store (#97316)
+ assert "usage" in result # still counts toward the degrade budget
assert "remove" in result["error"] # points at the deliberate-wipe path
assert path.read_text(encoding="utf-8") == before # nothing written
diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.py
index 0bca1556020..6f998e620e8 100644
--- a/tools/memory_tool_store.py
+++ b/tools/memory_tool_store.py
@@ -214,6 +214,13 @@ class MemoryStore:
return self._consolidation_failure(
_error(message, current_entries=self._entries_for(target), usage=self._usage(target)))
+ def _batch_failure(self, target: str, message: str) -> Dict[str, Any]:
+ """Batch-abort failure WITHOUT ``current_entries``: the store did not change and the
+ caller already holds the inventory, so echoing it made each consolidation retry
+ grow the context it was invoked to shrink (#97316)."""
+ return self._consolidation_failure(
+ _error(message + " No operations were applied (batch is all-or-nothing).", usage=self._usage(target)))
+
def _mutate(self, target: str, mutate, *, skip_drift: bool = False) -> Dict[str, Any]:
"""Lock, re-read from disk, run ``mutate(entries, limit)`` -> ``(new_entries, message)``
or an error dict, then persist and return the success response. The reload aborts
@@ -328,7 +335,8 @@ class MemoryStore:
def apply_batch(self, target: str, operations: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Apply add/replace/remove ops atomically against the FINAL budget, so one call
can free space and add entries. All-or-nothing: any malformed / unmatched op or
- an over-limit result writes NOTHING and returns the first failure plus live state."""
+ an over-limit result writes NOTHING and returns the first failure. Aborts do not
+ echo ``current_entries`` — the store is unchanged and the model already has it."""
if not operations:
return _error("operations list is empty.")
ops = [op or {} for op in operations]
@@ -345,24 +353,23 @@ class MemoryStore:
msg = self._apply_batch_op(working, act, (op.get("content") or op.get("new_text") or "").strip(),
(op.get("old_text") or "").strip(), f"Operation {i + 1} ({act or 'unknown'})")
if msg:
- return self._failure_with_entries(target, msg + " No operations were applied (batch is all-or-nothing).")
+ return self._batch_failure(target, msg)
if entries and not working:
# #103419: a consolidation batch that removes the last entry would
# commit an empty file as a normal successful write. Refuse; single
# remove() is the deliberate-wipe path.
label = self._path_for(target).name
- return self._failure_with_entries(target, (
+ return self._batch_failure(target, (
f"Refusing to empty {label}: this batch would remove every entry from a "
- f"previously non-empty store. Nothing was applied (batch is all-or-nothing). "
- f"Keep at least one entry — merge overlapping entries into a shorter one instead "
- f"of removing the last one (see current_entries below). To delete the final entry "
- f"deliberately, use single remove() calls."))
+ f"previously non-empty store. Keep at least one entry — merge overlapping "
+ f"entries into a shorter one instead of removing the last one. To delete the "
+ f"final entry deliberately, use single remove() calls."))
new_total = len(ENTRY_DELIMITER.join(working)) # budget check against the FINAL state only
if new_total > limit:
- return self._failure_with_entries(target, (
+ return self._batch_failure(target, (
f"After applying all {len(operations)} operations, memory would be at "
f"{new_total:,}/{limit:,} chars -- over the limit. Remove or shorten more "
- f"entries in the same batch (see current_entries below), then retry."))
+ f"entries in the same batch, then retry."))
return working, f"Applied {len(operations)} operation(s)."
return self._mutate(target, _apply)