Skip to content

The agent that grows with you

fix(memory): forward committed entry identity to providers

ehz0ahd57c2a32541a
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index 20443b35ad3..3381e86d3ab 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -806,22 +806,35 @@ class MemoryManager:
"""Mirror a built-in memory tool call to external providers.
Gates on a committed write, expands single-op and batched ``operations`` shapes, keeps only
- mutating actions, and forwards ``old_text`` plus provenance from ``build_metadata`` (the loop
- knows session/task/tool-call identity; we do not).
+ mutating actions, and forwards ``old_text`` plus provenance from ``build_metadata``.
+ ``previous_content`` comes only from the committed store result, never the search
+ argument: a partial provider registry cannot safely resolve that argument itself.
"""
if not self._memory_tool_result_succeeded(tool_result):
return
+ result = json.loads(tool_result) if isinstance(tool_result, str) else tool_result
target = str(tool_args.get("target") or "memory")
operations = tool_args.get("operations")
- for op in operations if isinstance(operations, list) and operations else [tool_args]:
+ batched = isinstance(operations, list) and bool(operations)
+ for index, op in enumerate(operations if batched else [tool_args], start=1):
action = str(op.get("action") or "") if isinstance(op, dict) else ""
if action not in self._MIRRORED_MEMORY_ACTIONS:
continue
try:
metadata = dict(build_metadata() if build_metadata else {})
+ metadata.pop("previous_content", None)
old_text = op.get("old_text")
if old_text:
metadata["old_text"] = str(old_text)
+ field = {"replace": "replaced", "remove": "removed"}.get(action)
+ if field:
+ if batched:
+ entries = result.get(f"{field}_entries", {})
+ previous = entries.get(str(index), entries.get(index)) if isinstance(entries, dict) else None
+ else:
+ previous = result.get(f"{field}_entry")
+ if isinstance(previous, str) and previous:
+ metadata["previous_content"] = previous
self.on_memory_write(action, target, str(op.get("content") or op.get("new_text") or ""), metadata=metadata)
except Exception as e:
logger.debug("notify_memory_tool_write failed for op %s: %s", action, e)
diff --git a/agent/memory_provider.py b/agent/memory_provider.py
index f9f4bcd4f68..90078f5e5e5 100644
--- a/agent/memory_provider.py
+++ b/agent/memory_provider.py
@@ -193,7 +193,12 @@ class MemoryProvider(ABC):
def on_memory_write(self, action: str, target: str, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Mirror a built-in memory-tool write (``action``: add | replace | remove; ``target``:
- memory | user; ``metadata``: provenance such as write_origin, session_id, tool_name)."""
+ memory | user; ``metadata``: provenance such as write_origin, session_id, tool_name).
+ For replace/remove, ``metadata["previous_content"]`` is the full entry selected
+ under the native-store lock. Notifications follow a successful complete write
+ or batch; each batch operation sees the preceding operation's result. Older
+ callers may omit this field: ``old_text`` alone is not authoritative identity.
+ """
def backup_paths(self) -> List[str]:
"""Absolute paths of provider state OUTSIDE HERMES_HOME for ``hermes backup``/``import``
diff --git a/tests/agent/test_memory_write_bridge.py b/tests/agent/test_memory_write_bridge.py
index c328f107a70..efaff0c525c 100644
--- a/tests/agent/test_memory_write_bridge.py
+++ b/tests/agent/test_memory_write_bridge.py
@@ -102,3 +102,111 @@ def test_build_metadata_callback_is_merged_per_op():
"metadata": {"session_id": "s1", "tool_name": "memory"},
}
]
+
+
[email protected]('target', ['memory', 'user'])
[email protected]('batch,operations,previous', [
+ (False, [{'action': 'remove', 'old_text': 'Prefers tea'}], ['Prefers tea']),
+ (False, [{'action': 'replace', 'old_text': 'Prefers tea', 'content': 'Prefers coffee'}], ['Prefers tea']),
+ (True, [{'action': 'remove', 'old_text': 'Prefers tea'}], ['Prefers tea']),
+ (True, [{'action': 'replace', 'old_text': 'Prefers tea', 'new_text': 'Prefers coffee'}], ['Prefers tea']),
+ (True, [
+ {'action': 'add', 'content': 'Uses the blue notebook'},
+ {'action': 'replace', 'old_text': 'blue notebook', 'new_text': 'Uses the green notebook'},
+ {'action': 'remove', 'old_text': 'green notebook'},
+ ], [None, 'Uses the blue notebook', 'Uses the green notebook']),
+])
+def test_committed_entry_identity_comes_from_locked_store(
+ tmp_path, monkeypatch, target, batch, operations, previous
+):
+ from contextlib import contextmanager
+ from tools import memory_tool_store
+ from tools.memory_tool import MemoryStore, memory_tool
+
+ monkeypatch.setattr('tools.memory_tool.get_memory_dir', lambda: tmp_path)
+ store = MemoryStore()
+ store.load_from_disk()
+ store.add(target, 'Prefers tea')
+ store.add(target, 'Prefers tea with milk')
+ manager, provider = _manager_with_provider()
+ locked = False
+ lock = store._file_lock
+ match = memory_tool_store._find_unique_match
+
+ @contextmanager
+ def checked_lock(path):
+ nonlocal locked
+ with lock(path):
+ locked = True
+ try:
+ yield
+ finally:
+ locked = False
+
+ def checked_match(entries, old_text):
+ assert locked
+ assert provider.calls == []
+ return match(entries, old_text)
+
+ monkeypatch.setattr(store, '_file_lock', checked_lock)
+ monkeypatch.setattr(memory_tool_store, '_find_unique_match', checked_match)
+ args = {'target': target, **({'operations': operations} if batch else operations[0])}
+ result = memory_tool(store=store, **args)
+ assert json.loads(result)['success'] is True
+ assert not locked
+ assert provider.calls == []
+ reloaded = MemoryStore()
+ reloaded.load_from_disk()
+ assert reloaded._entries_for(target) == store._entries_for(target)
+
+ manager.notify_memory_tool_write(result, args, build_metadata=lambda: {'session_id': 'test'})
+ assert [call['action'] for call in provider.calls] == [op['action'] for op in operations]
+ assert [call['metadata'].get('previous_content') for call in provider.calls] == previous
+ assert all(call['metadata']['session_id'] == 'test' for call in provider.calls)
+ assert 'Prefers tea with milk' in store._entries_for(target)
+
+
[email protected]('failure', ['invalid_operation', 'over_budget', 'empty_store', 'disk_write'])
+def test_uncommitted_batch_emits_no_entry_metadata_or_notifications(tmp_path, monkeypatch, failure):
+ from tools.memory_tool import MemoryStore, memory_tool
+
+ monkeypatch.setattr('tools.memory_tool.get_memory_dir', lambda: tmp_path)
+ store = MemoryStore(memory_char_limit=100)
+ store.load_from_disk()
+ store.add('memory', 'Keep this entry')
+ path = store._path_for('memory')
+ before = path.read_bytes()
+ manager, provider = _manager_with_provider()
+ operations = [{'action': 'replace', 'old_text': 'Keep this', 'content': 'Changed entry'}]
+ if failure == 'invalid_operation':
+ operations.append({'action': 'remove', 'old_text': 'Absent entry'})
+ elif failure == 'over_budget':
+ operations.append({'action': 'add', 'content': 'x' * 101})
+ elif failure == 'empty_store':
+ operations.append({'action': 'remove', 'old_text': 'Changed entry'})
+ else:
+ def fail_write(*_args):
+ raise OSError('disk unavailable')
+ monkeypatch.setattr(store, '_write_file', fail_write)
+ args = {'target': 'memory', 'operations': operations}
+ if failure == 'disk_write':
+ with pytest.raises(OSError, match='disk unavailable'):
+ result = memory_tool(store=store, **args)
+ manager.notify_memory_tool_write(result, args)
+ else:
+ result = memory_tool(store=store, **args)
+ payload = json.loads(result)
+ assert payload['success'] is False
+ assert not any(key in payload for key in ('replaced_entries', 'removed_entries'))
+ manager.notify_memory_tool_write(result, args)
+ assert provider.calls == []
+ assert path.read_bytes() == before
+
+
+def test_previous_content_cannot_come_from_uncommitted_arguments():
+ manager, provider = _manager_with_provider()
+ args = {'action': 'remove', 'old_text': 'partial', 'previous_content': 'Untrusted argument'}
+ manager.notify_memory_tool_write(
+ {'success': True}, args, build_metadata=lambda: {'previous_content': 'Uncommitted metadata'}
+ )
+ assert provider.calls[0]['metadata'] == {'old_text': 'partial'}
diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.py
index 9e7c4317bb9..2e29c83767e 100644
--- a/tools/memory_tool_store.py
+++ b/tools/memory_tool_store.py
@@ -314,7 +314,7 @@ class MemoryStore:
f"of the entry you want to {'replace' if new_content else 'remove'}.", current_entries=entries))
replaced = entries[:idx] + ([] if new_content is None else [new_content]) + entries[idx + 1:]
if new_content is None:
- return replaced, "Entry removed."
+ return replaced, "Entry removed.", {"removed_entry": entries[idx]}
new_total = len(ENTRY_DELIMITER.join(replaced))
if new_total > limit:
return self._failure_with_entries(target, (
@@ -327,10 +327,10 @@ class MemoryStore:
@staticmethod
def _apply_batch_op(working: List[str], act: str, content: str, old_text: str,
pos: str) -> Tuple[Optional[str], Optional[str]]:
- """Apply one batch op to *working* in place; return ``(error message, replaced
- entry text)``. The first element is None on every success path; the second is
- the full entry a 'replace' overwrote (None on non-replace paths and on every
- error path), surfaced so the caller can show what was lost (#117952)."""
+ """Apply one batch op to *working*; return ``(error message, previous content)``.
+ Previous content is captured before each replace/remove, under the store lock.
+ It is published only after the entire batch has been validated and persisted.
+ """
if act == "add":
if not content:
return f"{pos}: content is required.", None
@@ -348,9 +348,9 @@ class MemoryStore:
return f"{pos}: '{old_text}' matched multiple distinct entries -- be more specific.", None
if idx is None:
return f"{pos}: no entry matched '{old_text}'.", None
- replaced_text = working[idx] if act == "replace" else None
+ previous_content = working[idx]
working[idx:idx + 1] = [content] if act == "replace" else []
- return None, replaced_text
+ return None, previous_content
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
@@ -369,17 +369,18 @@ class MemoryStore:
def _apply(entries, limit):
working = list(entries) # only committed if the whole batch validates
replaced = {} # op index -> full entry text its replace overwrote (#117952)
+ removed = {}
for i, op in enumerate(ops):
act = op.get("action")
- msg, replaced_text = self._apply_batch_op(
+ msg, previous_content = 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._batch_failure(target, msg)
- if replaced_text is not None:
+ if previous_content is not None:
# 1-based op position, matching the "Operation N" error numbering the
# model sees for failed ops in the same batch.
- replaced[i + 1] = replaced_text
+ (replaced if act == "replace" else removed)[i + 1] = previous_content
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
@@ -397,6 +398,8 @@ class MemoryStore:
f"{new_total:,}/{limit:,} chars -- over the limit. Remove or shorten more "
f"entries in the same batch, then retry."))
replaced_fields = {"replaced_entries": replaced} if replaced else {}
+ if removed:
+ replaced_fields["removed_entries"] = removed
return working, f"Applied {len(operations)} operation(s).", replaced_fields
return self._mutate(target, _apply)
diff --git a/website/docs/developer-guide/memory-provider-plugin.md b/website/docs/developer-guide/memory-provider-plugin.md
index d4ca52f5b9e..306eb646a54 100644
--- a/website/docs/developer-guide/memory-provider-plugin.md
+++ b/website/docs/developer-guide/memory-provider-plugin.md
@@ -161,9 +161,17 @@ workspace; absent or empty cwd remains unpinned.
| `sync_turn(user, assistant, *, session_id="", messages=None)` | After each completed turn | Persist conversation |
| `on_session_end(messages)` | Conversation ends | Final extraction/flush |
| `on_pre_compress(messages)` | Before context compression | Save insights before discard |
-| `on_memory_write(action, target, content)` | Built-in memory writes | Mirror to your backend |
+| `on_memory_write(action, target, content, metadata=None)` | Built-in memory writes | Mirror to your backend |
| `shutdown()` | Process exit | Clean up connections |
+For native `replace` and `remove`, `metadata["previous_content"]` contains the full
+entry selected under the native-store lock. Notifications are emitted only after
+the complete write or batch succeeds. Batch notifications preserve operation order;
+each operation's previous content reflects earlier operations in that batch.
+`old_text` is the caller's search text, not the identity of the changed entry.
+Older Hermes versions can omit `previous_content`. Providers that require exact
+identity should skip destructive mirroring when it is absent.
+
### Oversized prefetch results
External `prefetch()` results above the configured spill threshold are written