Python
fix(history): query every agent when agent_ids is omitted (#93)
u7-u714fcc6fe3805
diff --git a/hy_memory/client.py b/hy_memory/client.pyindex 0464496..9c75cad 100644--- a/hy_memory/client.py+++ b/hy_memory/client.py@@ -6157,9 +6157,10 @@ class HyMemoryClient:effective_agent_ids = agent_ids if agent_ids is not None else []if not effective_agent_ids:- # 查所有 agent 的历史:用 "user_id:" 前缀匹配- isolation_key = self._build_isolation_key(uid, "default")- return await self._history_store.get_recent(isolation_key, limit=limit)+ # 查所有 agent 的历史:isolation_key 前缀匹配。+ # 不能退回 "u:default" —— add() 的默认 agent 是 "default_agent",+ # 默认用法下会查空。+ return await self._history_store.get_recent_for_user(uid, limit=limit)else:# 查指定 agent 的历史all_results = []diff --git a/hy_memory/data/history_store.py b/hy_memory/data/history_store.pyindex 8fb6d7f..a547a69 100644--- a/hy_memory/data/history_store.py+++ b/hy_memory/data/history_store.py@@ -66,6 +66,11 @@ def _now_iso() -> str:return datetime.now(timezone.utc).isoformat()+def _escape_like(value: str) -> str:+ """Escape LIKE wildcards so a user id is matched literally."""+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")++class HistoryStore:"""SQLite 历史存储 - 记录所有内存操作的审计日志。@@ -261,6 +266,34 @@ class HistoryStore:)return [dict(row) for row in cursor.fetchall()]+ async def get_recent_for_user(+ self,+ user_id: str,+ limit: int = 50,+ ) -> List[Dict[str, Any]]:+ """获取某 user 下所有 agent 的最近操作。++ isolation_key 形如 ``"{user_id}:{agent_id}"``。user_id 里的 LIKE+ 通配符会被转义,保证只匹配这个 user,不会漏到 ``u1`` 之外。+ """+ prefix = _escape_like(f"{user_id}:") + "%"+ return await _run_in_sqlite_pool(+ self._get_recent_prefix_sync, prefix, limit,+ )++ def _get_recent_prefix_sync(+ self, pattern: str, limit: int,+ ) -> List[Dict[str, Any]]:+ with self._conn_lock:+ if self._conn is None:+ return []+ cursor = self._conn.execute(+ "SELECT * FROM memory_history WHERE isolation_key LIKE ? ESCAPE '\\' "+ "ORDER BY created_at DESC LIMIT ?",+ (pattern, limit),+ )+ return [dict(row) for row in cursor.fetchall()]+async def count(self, isolation_key: str = "") -> int:"""统计历史记录数量。diff --git a/tests/test_history_recent_for_user.py b/tests/test_history_recent_for_user.pynew file mode 100644index 0000000..3836c15--- /dev/null+++ b/tests/test_history_recent_for_user.py@@ -0,0 +1,60 @@+# -*- coding: utf-8 -*-+"""History queries without agent_ids must cover every agent of the user."""++import asyncio++from hy_memory.config import MemoryConfig+from hy_memory.data.history_store import HistoryStore+++def _store(tmp_path):+ config = MemoryConfig()+ config.history.db_path = str(tmp_path / "history.db")+ return HistoryStore(config)+++def test_get_recent_for_user_matches_all_agents(tmp_path):+ async def _run():+ store = _store(tmp_path)+ await store.initialize()+ try:+ keys = [+ "u1:default_agent",+ "u1:agent_b",+ "u10:default_agent",+ "u2:default_agent",+ ]+ for index, key in enumerate(keys):+ await store.record_add(+ memory_id=f"m{index}",+ content="x",+ layer="l1_raw",+ isolation_key=key,+ )+ rows = await store.get_recent_for_user("u1", limit=10)+ finally:+ await store.close()+ return [row["isolation_key"] for row in rows]++ assert set(asyncio.run(_run())) == {"u1:default_agent", "u1:agent_b"}+++def test_get_recent_for_user_escapes_like_wildcards(tmp_path):+ async def _run():+ store = _store(tmp_path)+ await store.initialize()+ try:+ await store.record_add(+ memory_id="m1", content="x", layer="l1_raw",+ isolation_key="u_1:default_agent",+ )+ await store.record_add(+ memory_id="m2", content="x", layer="l1_raw",+ isolation_key="uX1:default_agent",+ )+ rows = await store.get_recent_for_user("u_1", limit=10)+ finally:+ await store.close()+ return [row["isolation_key"] for row in rows]++ assert asyncio.run(_run()) == ["u_1:default_agent"]