"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(memory): forget names the type when a title is shared (#1525)
Haozhe Wuacd1fb19eb88
diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.pyindex 01504fd59..f04cdcf24 100644--- a/agent/src/memory/persistent.py+++ b/agent/src/memory/persistent.py@@ -594,34 +594,58 @@ class PersistentMemory:logger.debug("FTS5 index_entry failed", exc_info=True)return path- def remove(self, name: str) -> bool:- """Remove a memory entry by name. Returns True if found and removed."""+ def remove(self, name: str, memory_type: str | None = None) -> bool:+ """Remove a memory entry by name.++ One title can exist under several memory types, each in its own file+ (``{memory_type}_{slug}.md``, #1525), so a bare title can be ambiguous.++ Args:+ name: Title of the entry to remove.+ memory_type: The entry's type; needed only when the title exists+ under more than one type.++ Returns:+ True if an entry was found and removed, False if none matched.++ Raises:+ ValueError: The title exists under several types and ``memory_type``+ was not given.+ """from src.config.accessor import get_env_config- for entry in self._scan_entries():- if entry.title == name:- with memory_lock(self._dir) as acquired:- if not acquired:- logger.warning("remove(%s): lock timeout", name)- entry.path.unlink(missing_ok=True)- self._rebuild_index()-- if get_env_config().memory.fts_index_enabled:- try:- from src.memory.search_index import get_shared_index- get_shared_index().remove_entry(entry.id)- except Exception:- logger.debug("FTS5 remove_entry failed", exc_info=True)-- if get_env_config().memory.links_enabled:- try:- from src.memory.semantic_links import SemanticLinker- SemanticLinker(self._dir).remove_relations(entry.path)- except Exception:- logger.debug("Failed to remove relations for %s", entry.path, exc_info=True)+ matches = [+ entry+ for entry in self._scan_entries()+ if entry.title == name and (memory_type is None or entry.memory_type == memory_type)+ ]+ if not matches:+ return False+ if len(matches) > 1:+ types = ", ".join(sorted(entry.memory_type for entry in matches))+ raise ValueError(f"memory {name!r} exists as {types}; name the memory_type to remove")+ entry = matches[0]+ with memory_lock(self._dir) as acquired:+ if not acquired:+ logger.warning("remove(%s): lock timeout", name)+ entry.path.unlink(missing_ok=True)+ self._rebuild_index()- return True- return False+ if get_env_config().memory.fts_index_enabled:+ try:+ from src.memory.search_index import get_shared_index+ get_shared_index().remove_entry(entry.id)+ except Exception:+ logger.debug("FTS5 remove_entry failed", exc_info=True)++ if get_env_config().memory.links_enabled:+ try:+ from src.memory.semantic_links import SemanticLinker+ SemanticLinker(self._dir).remove_relations(entry.path)+ except Exception:+ logger.debug("Failed to remove relations for %s", entry.path, exc_info=True)++ return Truedef _update_index(self, title: str, filename: str, description: str) -> None:"""Append or update an entry in MEMORY.md."""diff --git a/agent/src/tools/remember_tool.py b/agent/src/tools/remember_tool.pyindex 708129594..04b581d31 100644--- a/agent/src/tools/remember_tool.py+++ b/agent/src/tools/remember_tool.py@@ -44,7 +44,10 @@ class RememberTool(BaseTool):"memory_type": {"type": "string","enum": ["user", "feedback", "project", "reference"],- "description": "Memory category (default: project)",+ "description": (+ "Memory category (save: default project; forget: needed only when the "+ "title exists under more than one category)"+ ),},"query": {"type": "string",@@ -155,7 +158,10 @@ class RememberTool(BaseTool):title = kwargs.get("title", "")if not title:return json.dumps({"status": "error", "error": "title required"})- removed = self._memory.remove(title)+ try:+ removed = self._memory.remove(title, kwargs.get("memory_type"))+ except ValueError as exc:+ return json.dumps({"status": "error", "error": str(exc)})msg = f"Removed: {title}" if removed else f"Not found: {title}"return json.dumps({"status": "ok" if removed else "not_found", "message": msg})diff --git a/agent/tests/test_persistent_memory.py b/agent/tests/test_persistent_memory.pyindex 52dd32bf4..d1b81b8e2 100644--- a/agent/tests/test_persistent_memory.py+++ b/agent/tests/test_persistent_memory.py@@ -216,6 +216,27 @@ class TestAdd:assert "reference_kb-entry.md" in indexassert "user_kb-entry.md" in index+ def test_remove_names_the_type_when_a_title_is_shared(self, tmp_path: Path) -> None:+ # Sibling of the index fix: remove(title) used to delete whichever+ # same-title entry it scanned first.+ pm = PersistentMemory(memory_dir=tmp_path)+ pm.add("kb-entry", "raw material notes", "reference", description="reference doc")+ pm.add("kb-entry", "user preference notes", "user", description="user pref")++ with pytest.raises(ValueError, match="reference, user"):+ pm.remove("kb-entry")+ assert (tmp_path / "reference_kb-entry.md").exists()+ assert (tmp_path / "user_kb-entry.md").exists()++ assert pm.remove("kb-entry", "user") is True+ assert not (tmp_path / "user_kb-entry.md").exists()+ assert (tmp_path / "reference_kb-entry.md").exists()+ index = (tmp_path / "MEMORY.md").read_text(encoding="utf-8")+ assert "reference_kb-entry.md" in index and "user_kb-entry.md" not in index++ assert pm.remove("kb-entry") is True # no longer ambiguous+ assert pm.remove("kb-entry") is False+def test_cjk_names_get_distinct_filenames(self, tmp_path: Path) -> None:# Regression: previously every non-ASCII char was replaced with `_`, so# any two CJK-only names of the same length collapsed to the same slug