Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(bot): Support actor-peer auth check (#2670)
DuTao35d5a92949fe
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex 1553faef2..04eff0bf0 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -6,6 +6,7 @@ import pytestfrom vikingbot.agent.context import ContextBuilderfrom vikingbot.agent.loop import _is_tool_result_successfrom vikingbot.agent.memory import MemoryStore+from vikingbot.agent.tools import ov_file as ov_file_modulefrom vikingbot.agent.tools.base import ToolContextfrom vikingbot.agent.tools.ov_file import (VikingGlobTool,@@ -14,7 +15,6 @@ from vikingbot.agent.tools.ov_file import (VikingMemoryCommitTool,VikingSearchTool,)-from vikingbot.agent.tools import ov_file as ov_file_modulefrom vikingbot.cli import commands as commands_modulefrom vikingbot.config import loader as config_loader_modulefrom vikingbot.config.schema import OpenVikingConfig, SessionKey@@ -48,8 +48,8 @@ class _DummyHTTPClient:async def initialize(self):return None- async def create_session(self, session_id=None):- return {"session_id": session_id or "s-1"}+ async def create_session(self, session_id=None, memory_policy=None):+ return {"session_id": session_id or "s-1", "memory_policy": memory_policy}async def session_exists(self, _session_id):return False@@ -60,14 +60,11 @@ class _DummyHTTPClient:async def batch_add_messages(self, session_id, messages):return {"session_id": session_id, "added": len(messages), "message_count": len(messages)}- async def commit_session(- self, session_id, keep_recent_count=0, telemetry=False, memory_policy=None- ):+ async def commit_session(self, session_id, keep_recent_count=0, telemetry=False):return {"session_id": session_id,"status": "committed","keep_recent_count": keep_recent_count,- "memory_policy": memory_policy,}def session(self, _session_id):@@ -169,6 +166,16 @@ def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):assert "agent_id" not in first.kwargs+def test_viking_client_actor_peer_id_sets_actor_header(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))++ client = VikingClient(actor_peer_id="sender with space")++ first = _DummyHTTPClient.instances[0]+ assert client.actor_peer_id == VikingClient._peer_id("sender with space")+ assert first.kwargs["actor_peer_id"] == client.actor_peer_id++def test_openviking_config_api_key_type_empty_values_are_inferred():assert OpenVikingConfig(api_key_type=None, api_key="user-key").api_key_type == "user"assert OpenVikingConfig(api_key_type="", api_key="user-key").api_key_type == "user"@@ -1262,6 +1269,30 @@ async def test_search_memory_uses_user_namespace_without_agent_scope(monkeypatchassert calls == ["viking://user/sender-1/memories/"]+async def test_search_memory_peer_ids_use_explicit_peer_uris(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))+ client = VikingClient()++ calls = []++ class _Result:+ memories = []++ async def _find(*, query, target_uri, limit):+ calls.append((query, target_uri, limit))+ return _Result()++ monkeypatch.setattr(client.client, "find", _find)++ await client.search_memory("hello", peer_ids=["sender-1", "sender-2"], limit=5)++ assert calls == [+ ("hello", "viking://user/peers/sender-1/memories/", 5),+ ("hello", "viking://user/peers/sender-2/memories/", 5),+ ]++@pytest.mark.asyncioasync def test_skill_memory_uri_uses_user_memory_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))@@ -1378,6 +1409,203 @@ async def test_viking_memory_context_keeps_legacy_users_separate_from_peers(]+async def test_viking_memory_context_creates_actor_scoped_client(monkeypatch, tmp_path):+ create_calls = []++ class _FakeClient:+ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ return []++ async def close(self):+ return None++ async def _fake_create(**kwargs):+ create_calls.append(kwargs)+ return _FakeClient()++ monkeypatch.setattr("vikingbot.agent.memory.load_config", lambda: _make_config("user"))+ monkeypatch.setattr("vikingbot.agent.memory.VikingClient.create", _fake_create)++ store = MemoryStore(tmp_path)++ await store.get_viking_memory_context(+ current_message="hello",+ workspace_id="workspace",+ sender_id="sender-1",+ )++ assert create_calls[0]["actor_peer_id"] == "sender-1"+++async def test_viking_memory_type_quota_actor_scope_keeps_per_type_limits(tmp_path):+ calls = []++ class _ActorClient:+ actor_peer_id = "sender-1"++ def _current_peer_memory_target_uri(self, peer_id):+ return f"viking://user/peers/{peer_id}/memories/"++ async def find(self, *, query, target_uri, context_type=None, limit):+ calls.append(+ {+ "query": query,+ "target_uri": target_uri,+ "context_type": context_type,+ "limit": limit,+ }+ )+ if target_uri.endswith("/events/"):+ return {+ "memories": [+ {+ "uri": "viking://user/peers/sender-1/memories/events/e1.md",+ "abstract": "event",+ "score": 0.9,+ },+ ]+ }+ return {"memories": []}++ store = MemoryStore(tmp_path)++ result = await store._search_viking_memory_by_type_quota(+ client=_ActorClient(),+ query="hello",+ peer_ids=["sender-1", "other"],+ quotas={"events": 1, "entities": 1, "preferences": 1},+ )++ assert calls == [+ {+ "query": "hello",+ "target_uri": "viking://user/peers/sender-1/memories/events/",+ "context_type": "memory",+ "limit": 1,+ },+ {+ "query": "hello",+ "target_uri": "viking://user/peers/sender-1/memories/entities/",+ "context_type": "memory",+ "limit": 1,+ },+ {+ "query": "hello",+ "target_uri": "viking://user/peers/sender-1/memories/preferences/",+ "context_type": "memory",+ "limit": 1,+ },+ ]+ assert [item["_recall_type"] for item in result] == ["events"]+++async def test_viking_peer_profiles_use_target_peer_actor_clients(monkeypatch, tmp_path):+ create_calls = []+ closed = []++ class _FakeClient:+ def __init__(self, actor_peer_id):+ self.actor_peer_id = actor_peer_id++ async def read_peer_profile(self, peer_id):+ return f"profile for {peer_id} via {self.actor_peer_id}"++ async def close(self):+ closed.append(self.actor_peer_id)++ async def _fake_create(**kwargs):+ create_calls.append(kwargs)+ return _FakeClient(kwargs.get("actor_peer_id"))++ monkeypatch.setattr("vikingbot.agent.memory.VikingClient.create", _fake_create)++ store = MemoryStore(tmp_path)+ result = await store.get_viking_peer_profiles(+ workspace_id="workspace",+ peer_ids=["speaker-a", "speaker-b"],+ use_peer_actor_scope=True,+ )++ assert [call["actor_peer_id"] for call in create_calls] == ["speaker-a", "speaker-b"]+ assert closed == ["speaker-a", "speaker-b"]+ assert "profile for speaker-a via speaker-a" in result+ assert "profile for speaker-b via speaker-b" in result+++async def test_viking_memory_context_uses_target_peer_actor_for_additional_peer_reads(+ monkeypatch, tmp_path+):+ create_actor_ids = []+ read_calls = []+ closed = []++ class _FakeClient:+ def __init__(self, actor_peer_id):+ self.actor_peer_id = actor_peer_id++ def _current_peer_memory_target_uri(self, peer_id):+ return f"viking://user/peers/{peer_id}/memories/"++ async def find(self, *, query, target_uri, context_type=None, limit):+ if target_uri.endswith("/events/"):+ return {+ "memories": [+ {+ "uri": (+ f"viking://user/peers/{self.actor_peer_id}/"+ "memories/events/e1.md"+ ),+ "score": 0.9,+ }+ ]+ }+ return {"memories": []}++ async def read_content(self, uri, level="read"):+ read_calls.append((self.actor_peer_id, uri, level))+ return f"content via {self.actor_peer_id}"++ async def close(self):+ closed.append(self.actor_peer_id)++ async def _fake_create(**kwargs):+ create_actor_ids.append(kwargs.get("actor_peer_id"))+ return _FakeClient(kwargs.get("actor_peer_id"))++ monkeypatch.setattr(+ "vikingbot.agent.memory.load_config",+ lambda: _make_config(+ "user",+ memory_recall_events_limit=2,+ memory_recall_entities_limit=0,+ memory_recall_preferences_limit=0,+ memory_recall_max_chars=1000,+ ),+ )+ monkeypatch.setattr("vikingbot.agent.memory.VikingClient.create", _fake_create)++ store = MemoryStore(tmp_path)+ result = await store.get_viking_memory_context(+ current_message="hello",+ workspace_id="workspace",+ sender_id="sender-1",+ peer_ids=["speaker-a"],+ )++ assert create_actor_ids == ["sender-1", "speaker-a", "speaker-a"]+ assert read_calls == [+ ("sender-1", "viking://user/peers/sender-1/memories/events/e1.md", "read"),+ ("speaker-a", "viking://user/peers/speaker-a/memories/events/e1.md", "read"),+ ]+ assert closed == ["speaker-a", "speaker-a", "sender-1"]+ assert "content via sender-1" in result+ assert "content via speaker-a" in result++@pytest.mark.asyncioasync def test_viking_memory_type_quota_groups_with_event_summaries_and_uris(monkeypatch, tmp_path@@ -1639,8 +1867,8 @@ async def test_openviking_search_uses_user_namespace(monkeypatch):calls = []- async def _search(query, target_uri=None, limit=20, user_id=None, peer_id=None):- calls.append((target_uri, user_id, peer_id))+ async def _search(query, target_uri=None, limit=20, user_id=None):+ calls.append((target_uri, user_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):@@ -1654,9 +1882,9 @@ async def test_openviking_search_uses_user_namespace(monkeypatch):assert "sender-1/memories" in resultassert calls == [- ("viking://resources/", None, None),- ("viking://user/sender-1/memories/", None, None),- ("viking://user/sender-1/skills/", None, None),+ ("viking://resources/", None),+ ("viking://user/sender-1/memories/", None),+ ("viking://user/sender-1/skills/", None),]@@ -1668,8 +1896,8 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkecalls = []- async def _search(query, target_uri=None, limit=20, user_id=None, peer_id=None):- calls.append((target_uri, user_id, peer_id))+ async def _search(query, target_uri=None, limit=20, user_id=None):+ calls.append((target_uri, user_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):@@ -1687,12 +1915,69 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkeassert "sender-1/memories" in resultassert calls == [- ("", None, "sender-0"),- ("viking://user/peers/sender-1/memories/", None, None),- ("viking://user/peers/sender-2/memories/", None, None),+ ("viking://resources/", None),+ ("viking://user/memories/", None),+ ("viking://user/skills/", None),+ ("viking://user/peers/sender-0/memories/", None),+ ("viking://user/peers/sender-1/memories/", None),+ ("viking://user/peers/sender-2/memories/", None),]+async def test_openviking_search_actor_client_uses_server_default_scope(monkeypatch):+ tool = VikingSearchTool()+ calls = []++ class _ActorClient:+ actor_peer_id = "sender-0"++ def should_sender_fanout(self):+ return True++ async def search(self, query, target_uri=None, limit=20, user_id=None):+ calls.append((target_uri, user_id))+ return {+ "memories": [+ {"uri": "viking://user/peers/sender-0/memories/a.md", "score": 0.9}+ ]+ }++ async def close(self):+ calls.append(("close", None))++ async def _fake_get_client(_tool_context):+ return _ActorClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ tool_context = SimpleNamespace(+ workspace_id="workspace",+ sender_id="sender-0",+ memory_peer_ids=["sender-1", "sender-2"],+ )+ result = await tool.execute(tool_context, query="hello")++ assert "sender-0/memories" in result+ assert calls == [("", None), ("close", None)]+++async def test_openviking_tool_sender_uses_actor_scoped_one_shot_client(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))+ tool = VikingSearchTool()++ result = await tool.execute(+ SimpleNamespace(workspace_id="workspace", sender_id="sender-1"),+ query="hello",+ )++ first = _DummyHTTPClient.instances[0]+ assert first.kwargs["actor_peer_id"] == "sender-1"+ assert first.closed is True+ assert "No results found" in result++@pytest.mark.asyncioasync def test_openviking_grep_default_memory_expands_current_peer(monkeypatch):tool = VikingGrepTool()@@ -1918,7 +2203,7 @@ async def test_context_loads_profiles_for_memory_peers(tmp_path):return "sender profile"async def get_viking_peer_profiles(self, **kwargs):- calls["peers"].append(kwargs["peer_ids"])+ calls["peers"].append(kwargs)return "\n".join(f"profile for {peer_id}" for peer_id in kwargs["peer_ids"])context = ContextBuilder(workspace=tmp_path, sender_id="sender-1")@@ -1932,7 +2217,14 @@ async def test_context_loads_profiles_for_memory_peers(tmp_path):)assert calls["sender"] == ["sender-1"]- assert calls["peers"] == [["speaker-a", "speaker-b"]]+ assert calls["peers"] == [+ {+ "workspace_id": "cli__default__chat-1",+ "peer_ids": ["speaker-a", "speaker-b"],+ "openviking_connection": None,+ "use_peer_actor_scope": True,+ }+ ]assert "sender profile" in system_promptassert "profile for speaker-a" in system_promptassert "profile for speaker-b" in system_promptdiff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 7096724c6..84fbe1e22 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -163,6 +163,7 @@ Skills with available="false" need dependencies installed first - you can try inworkspace_id=workspace_id,peer_id=self._sender_id,openviking_connection=self._openviking_connection,+ actor_peer_id=self._sender_id,)cost = round(_time.time() - start, 2)logger.info(@@ -183,6 +184,7 @@ Skills with available="false" need dependencies installed first - you can try inworkspace_id=workspace_id,peer_ids=additional_peer_ids,openviking_connection=self._openviking_connection,+ use_peer_actor_scope=bool(self._sender_id),)if profiles:parts.append(profiles)@@ -250,6 +252,7 @@ Skills with available="false" need dependencies installed first - you can try inquery=current_message,workspace_id=exp_workspace_id,openviking_connection=self._openviking_connection,+ actor_peer_id=sender_id,)cost = round(_time.time() - start, 2)logger.info(diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 2cd662a3e..068a55853 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -344,12 +344,17 @@ class AgentLoop:self,session_key: SessionKey,openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,):workspace_id = self._get_ov_workspace_id(session_key)- if openviking_connection:+ if openviking_connection or actor_peer_id:from vikingbot.openviking_mount.ov_server import VikingClient- return await VikingClient.create(workspace_id, connection=openviking_connection)+ return await VikingClient.create(+ workspace_id,+ connection=openviking_connection,+ actor_peer_id=actor_peer_id,+ )client = self._ov_clients.get(workspace_id)if client is None:@@ -433,6 +438,7 @@ class AgentLoop:session: Session,provider_name: str | None = None,openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,) -> list[dict[str, Any]]:if not self._ov_session_context_enabled():return session.get_history(provider_name=provider_name)@@ -446,8 +452,9 @@ class AgentLoop:client = await self._get_ov_client(session.key,openviking_connection=openviking_connection,+ actor_peer_id=actor_peer_id,)- if openviking_connection:+ if openviking_connection or actor_peer_id:request_client = clientcontext_payload = await client.get_session_context(session_id=session_id,@@ -1083,6 +1090,7 @@ class AgentLoop:session,provider_name=provider_name,openviking_connection=openviking_connection,+ actor_peer_id=msg.sender_id,)messages = await message_context.build_messages(history=history,@@ -1359,7 +1367,11 @@ class AgentLoop:# Build messages with the announce contentprovider_name = self.config.get_provider_name(self.model) if self.config else None- history = await self._build_prompt_history(session, provider_name=provider_name)+ history = await self._build_prompt_history(+ session,+ provider_name=provider_name,+ actor_peer_id=msg.sender_id,+ )messages = await self.context.build_messages(history=history,current_message=msg.content,diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 79fa41086..c0697c775 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -12,7 +12,6 @@ from vikingbot.config.loader import load_configfrom vikingbot.openviking_mount.ov_server import VikingClientfrom vikingbot.utils.helpers import ensure_dir-_LEGACY_MEMORY_RECALL_LIMIT = 30_TYPE_QUOTA_MEMORY_TYPES = ("events", "entities", "preferences")_TYPE_QUOTA_EVENT_CHAR_RATIO = 0.75@@ -141,6 +140,14 @@ class MemoryStore:def _memory_type_target(base_uri: str, memory_type: str) -> str:return f"{base_uri.rstrip('/')}/{memory_type.strip('/')}/"+ @staticmethod+ def _peer_id_from_memory_uri(uri: str) -> str | None:+ parts = [part for part in uri.strip("/").split("/") if part]+ for idx, part in enumerate(parts):+ if part == "peers" and idx + 1 < len(parts):+ return parts[idx + 1]+ return None+@classmethoddef _order_type_quota_memories(cls,@@ -165,6 +172,29 @@ class MemoryStore:ordered.extend(others)return cls._dedupe_memories(ordered)+ @classmethod+ def _select_type_quota_memories(+ cls,+ memories: list[Any],+ quotas: dict[str, int],+ ) -> list[Any]:+ memories = sorted(cls._dedupe_memories(memories), key=cls._get_score, reverse=True)+ selected: list[Any] = []+ for memory_type in _TYPE_QUOTA_MEMORY_TYPES:+ quota = max(0, int(quotas.get(memory_type, 0) or 0))+ if quota <= 0:+ continue+ type_memories = [+ memory+ for memory in memories+ if cls._infer_memory_type(memory) == memory_type+ ][:quota]+ selected.extend(+ cls._with_recall_metadata(memory, memory_type, rank)+ for rank, memory in enumerate(type_memories, start=1)+ )+ return cls._dedupe_memories(selected)+@staticmethoddef _type_quota_char_budgets(max_chars: int) -> dict[str, int]:max_chars = max(0, int(max_chars))@@ -244,6 +274,7 @@ class MemoryStore:type_char_budgets: dict[str, int] | None = None,preference_full_limit: int = 0,include_uri_entries: bool = True,+ read_content: Any | None = None,) -> str:"""Parse viking memory with score filtering and character limit.Automatically reads full content for memories that fit the relevant budget;@@ -276,7 +307,7 @@ class MemoryStore:grouped_memories: dict[str, list[str]] = {}total_chars = 0- type_chars = {memory_type: 0 for memory_type in _TYPE_QUOTA_MEMORY_TYPES}+ type_chars = dict.fromkeys(_TYPE_QUOTA_MEMORY_TYPES, 0)preference_full_count = 0seen_content_hashes = set()full_limit = len(filtered_memories) if full_limit is None else max(0, full_limit)@@ -298,7 +329,10 @@ class MemoryStore:content = ""try:- content = await client.read_content(uri, level="read")+ if read_content:+ content = await read_content(uri, level="read")+ else:+ content = await client.read_content(uri, level="read")except Exception as e:logger.warning(f"Failed to read content from {uri}: {e}")@@ -379,10 +413,16 @@ class MemoryStore:peer_ids: list[str] | None,quotas: dict[str, int],) -> list[Any]:- base_targets = client.build_current_memory_target_uris(- peer_ids=peer_ids,- include_self=not bool(peer_ids),- )+ if getattr(client, "actor_peer_id", None):+ try:+ base_targets = [client._current_peer_memory_target_uri(client.actor_peer_id)]+ except ValueError:+ base_targets = []+ else:+ base_targets = client.build_current_memory_target_uris(+ peer_ids=peer_ids,+ include_self=not bool(peer_ids),+ )if not base_targets:return []@@ -394,7 +434,14 @@ class MemoryStore:for base_target in base_targets:target_uri = self._memory_type_target(base_target, memory_type)try:- result = await client.find(query=query, target_uri=target_uri, limit=quota)+ find_kwargs = {+ "query": query,+ "target_uri": target_uri,+ "limit": quota,+ }+ if getattr(client, "actor_peer_id", None):+ find_kwargs["context_type"] = "memory"+ result = await client.find(**find_kwargs)except Exception as e:logger.warning(f"Failed to search {target_uri}: {e}")continue@@ -407,6 +454,62 @@ class MemoryStore:return self._dedupe_memories(all_memories)+ async def _search_actor_peer_memories_by_type_quota(+ self,+ query: str,+ workspace_id: str,+ openviking_connection: dict[str, Any] | None,+ base_client: VikingClient,+ peer_ids: list[str],+ quotas: dict[str, int],+ ) -> list[Any]:+ current_actor_peer_id = getattr(base_client, "actor_peer_id", None)+ normalized_peer_ids = VikingClient._dedupe_strings(+ [+ normalized_peer_id+ for normalized_peer_id in (VikingClient._peer_id(peer_id) for peer_id in peer_ids)+ if normalized_peer_id+ ]+ )++ async def search_peer(normalized_peer_id: str) -> list[Any]:+ peer_client = base_client+ should_close = False+ if normalized_peer_id != current_actor_peer_id:+ peer_client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ actor_peer_id=normalized_peer_id,+ )+ should_close = True++ try:+ return await self._search_viking_memory_by_type_quota(+ client=peer_client,+ query=query,+ peer_ids=[normalized_peer_id],+ quotas=quotas,+ )+ finally:+ if should_close:+ try:+ await peer_client.close()+ except Exception as e:+ logger.warning(f"Error closing VikingClient: {e}")++ results = await asyncio.gather(+ *(search_peer(peer_id) for peer_id in normalized_peer_ids),+ return_exceptions=True,+ )+ all_memories: list[Any] = []+ for result in results:+ if isinstance(result, Exception):+ logger.warning(f"Failed to search actor peer memories: {result}")+ continue+ all_memories.extend(result)++ return self._select_type_quota_memories(all_memories, quotas)+async def get_viking_memory_context(self,current_message: str,@@ -417,6 +520,7 @@ class MemoryStore:openviking_connection: dict[str, Any] | None = None,) -> str:client = None+ read_clients: dict[str, VikingClient] = {}try:ov_cfg = load_config().ov_serveradmin_user_id = (@@ -433,8 +537,12 @@ class MemoryStore:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ actor_peer_id=sender_id,)- search_peer_ids = [sender_id, *(peer_ids or [])] if sender_id else (peer_ids or None)+ if sender_id:+ search_peer_ids = [sender_id, *(peer_ids or [])]+ else:+ search_peer_ids = peer_ids or Nonetype_quotas = {"events": max(0, int(getattr(ov_cfg, "memory_recall_events_limit", 10))),"entities": max(0, int(getattr(ov_cfg, "memory_recall_entities_limit", 10))),@@ -443,12 +551,22 @@ class MemoryStore:recall_max_chars = max(1, int(getattr(ov_cfg, "memory_recall_max_chars", 6500)))use_type_quota = not user_idsif use_type_quota:- result = await self._search_viking_memory_by_type_quota(- client=client,- query=current_message,- peer_ids=search_peer_ids,- quotas=type_quotas,- )+ if getattr(client, "actor_peer_id", None):+ result = await self._search_actor_peer_memories_by_type_quota(+ query=current_message,+ workspace_id=workspace_id,+ openviking_connection=openviking_connection,+ base_client=client,+ peer_ids=search_peer_ids or [],+ quotas=type_quotas,+ )+ else:+ result = await self._search_viking_memory_by_type_quota(+ client=client,+ query=current_message,+ peer_ids=search_peer_ids,+ quotas=type_quotas,+ )else:result = await client.search_memory(query=current_message,@@ -468,6 +586,21 @@ class MemoryStore:if not use_type_quota:result = self._limit_memories(result, limit=_LEGACY_MEMORY_RECALL_LIMIT)+ async def read_memory_content(uri: str, level: str = "read") -> str:+ actor_peer_id = getattr(client, "actor_peer_id", None)+ memory_peer_id = self._peer_id_from_memory_uri(uri)+ if actor_peer_id and memory_peer_id and memory_peer_id != actor_peer_id:+ peer_client = read_clients.get(memory_peer_id)+ if not peer_client:+ peer_client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ actor_peer_id=memory_peer_id,+ )+ read_clients[memory_peer_id] = peer_client+ return await peer_client.read_content(uri, level=level)+ return await client.read_content(uri, level=level)+# Log raw search results for debuggingrecall_strategy = "type_quota" if use_type_quota else "global"memory_list = []@@ -492,12 +625,18 @@ class MemoryStore:_TYPE_QUOTA_PREFERENCE_FULL_LIMIT if use_type_quota else 0),include_uri_entries=True,+ read_content=read_memory_content,)return f"### user memories:\n{user_memory}"except Exception as e:logger.error(f"[READ_USER_MEMORY]: search error. {e}")return ""finally:+ for read_client in read_clients.values():+ try:+ await read_client.close()+ except Exception as e:+ logger.warning(f"Error closing VikingClient: {e}")if client:try:await client.close()@@ -509,6 +648,7 @@ class MemoryStore:query: str,workspace_id: str,openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,) -> str:"""用当前任务 query 检索 experience 记忆,注入到 system prompt。"""client = None@@ -517,6 +657,7 @@ class MemoryStore:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ actor_peer_id=actor_peer_id,)experiences = await client.search_experiences(query, limit=ov_cfg.exp_recall_limit)logger.info(@@ -546,12 +687,14 @@ class MemoryStore:workspace_id: str,user_id: str | None,openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,) -> str:client = Nonetry:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ actor_peer_id=actor_peer_id,)result = await client.read_user_profile(user_id)return result or ""@@ -570,6 +713,7 @@ class MemoryStore:workspace_id: str,peer_id: str | None,openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,) -> str:if not peer_id:return ""@@ -579,6 +723,7 @@ class MemoryStore:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ actor_peer_id=actor_peer_id or peer_id,)result = await client.read_peer_profile(peer_id)return result or ""@@ -597,21 +742,32 @@ class MemoryStore:workspace_id: str,peer_ids: list[str],openviking_connection: dict[str, Any] | None = None,+ use_peer_actor_scope: bool = False,) -> str:if not peer_ids:return ""client = Nonetry:- client = await VikingClient.create(- agent_id=workspace_id,- connection=openviking_connection,- )+ if not use_peer_actor_scope:+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )async def fetch_profile(peer_id: str) -> tuple[str, str]:+ peer_client = client+ should_close = Falsetry:+ if use_peer_actor_scope:+ peer_client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ actor_peer_id=peer_id,+ )+ should_close = Truestart_time = time.time()- profile = await client.read_peer_profile(peer_id)+ profile = await peer_client.read_peer_profile(peer_id)cost = round(time.time() - start_time, 2)logger.info(f"[READ_PEER_PROFILE]: peer_id={peer_id}, cost {cost}s, "@@ -621,6 +777,12 @@ class MemoryStore:except Exception as e:logger.error(f"[READ_PEER_PROFILE]: peer_id={peer_id}, error. {e}")return (peer_id, "")+ finally:+ if should_close and peer_client:+ try:+ await peer_client.close()+ except Exception as e:+ logger.warning(f"Error closing VikingClient: {e}")tasks = [fetch_profile(peer_id) for peer_id in peer_ids]results = await asyncio.gather(*tasks, return_exceptions=True)@@ -649,6 +811,7 @@ class MemoryStore:workspace_id: str,user_ids: list[str],openviking_connection: dict[str, Any] | None = None,+ actor_peer_id: str | None = None,) -> str:"""Get multiple user profiles concurrently.@@ -667,6 +830,7 @@ class MemoryStore:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ actor_peer_id=actor_peer_id,)async def fetch_profile(user_id: str) -> tuple[str, str]:diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex 78dc75c56..d04129872 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -27,10 +27,17 @@ class OVFileTool(Tool, ABC):return bool(getattr(tool_context, "openviking_connection", None))async def _get_client(self, tool_context: ToolContext):+ actor_peer_id = getattr(tool_context, "sender_id", None)if self._has_request_connection(tool_context):return await VikingClient.create(tool_context.workspace_id,connection=tool_context.openviking_connection,+ actor_peer_id=actor_peer_id,+ )+ if actor_peer_id:+ return await VikingClient.create(+ tool_context.workspace_id,+ actor_peer_id=actor_peer_id,)cache_key = str(tool_context.workspace_id or "__default__")client = self._clients.get(cache_key)@@ -40,8 +47,12 @@ class OVFileTool(Tool, ABC):return clientasync def _release_client(self, tool_context: ToolContext, client: VikingClient | None) -> None:- if client is not None and self._has_request_connection(tool_context):- await client.close()+ if client is not None and (+ self._has_request_connection(tool_context) or getattr(tool_context, "sender_id", None)+ ):+ close = getattr(client, "close", None)+ if callable(close):+ await close()@staticmethoddef _normalize_uri(uri: str | None) -> str:@@ -113,6 +124,13 @@ class OVFileTool(Tool, ABC):tool_context: ToolContext,uri: str | None,) -> list[str]:+ if getattr(client, "actor_peer_id", None):+ if self._is_default_root_uri(uri):+ return [uri or "viking://"]+ if self._is_default_memory_uri(client, uri):+ return [uri or self._current_memory_uri(client)]+ return [uri or ""]+if not self._is_default_memory_uri(client, uri):if not self._is_default_root_uri(uri):return [uri or ""]@@ -387,11 +405,12 @@ class VikingSearchTool(OVFileTool):if (not target_uri+ and not getattr(client, "actor_peer_id", None)and client.should_sender_fanout()and (memory_owner_user_ids or legacy_memory_user_ids)):user_ids = memory_owner_user_ids or legacy_memory_user_ids- search_requests = [{"target_uri": "viking://resources/", "peer_id": None}]+ target_uris = ["viking://resources/"]for user_id in self._dedupe_strings(list(user_ids or [])):memory_uri = client._memory_target_uri(user_id)skill_uri = (@@ -399,54 +418,44 @@ class VikingSearchTool(OVFileTool):if memory_uri.rstrip("/").endswith("/memories")else "viking://user/skills/")- search_requests.extend(- [- {"target_uri": memory_uri, "peer_id": None},- {"target_uri": skill_uri, "peer_id": None},- ]- )+ target_uris.extend([memory_uri, skill_uri])else:peer_ids = self._memory_peer_ids(tool_context)if not target_uri:- search_requests = (- [{"target_uri": "", "peer_id": peer_ids[0]}]- if peer_ids- else [{"target_uri": "", "peer_id": None}]- )- peer_memory_uris = self._peer_memory_uris(- client, tool_context, peer_ids=peer_ids[1:]- )- if peer_memory_uris:- search_requests.extend(- {"target_uri": peer_uri, "peer_id": None}- for peer_uri in peer_memory_uris+ if getattr(client, "actor_peer_id", None):+ target_uris = [""]+ elif peer_ids:+ target_uris = self._dedupe_strings(+ [+ "viking://resources/",+ self._current_memory_uri(client),+ self._current_skill_uri(client),+ *self._peer_memory_uris(+ client, tool_context, peer_ids=peer_ids+ ),+ ])else:- search_requests.extend(- {"target_uri": "viking://user/memories/", "peer_id": peer_id}- for peer_id in peer_ids[1:]- )- elif self._is_default_memory_uri(client, target_uri) and peer_ids:- memory_uris = self._dedupe_strings(+ target_uris = [""]+ elif (+ self._is_default_memory_uri(client, target_uri)+ and not getattr(client, "actor_peer_id", None)+ and peer_ids+ ):+ target_uris = self._dedupe_strings(["viking://user/memories/",*self._peer_memory_uris(client, tool_context, peer_ids=peer_ids),])- search_requests = [- {"target_uri": memory_uri, "peer_id": None}- for memory_uri in memory_uris- ]else:- search_requests = [{"target_uri": target_uri, "peer_id": None}]+ target_uris = [target_uri]- for request in search_requests:+ for search_target_uri in target_uris:search_kwargs = {- "target_uri": request["target_uri"],+ "target_uri": search_target_uri,"limit": 10,}- if request.get("peer_id") is not None:- search_kwargs["peer_id"] = request.get("peer_id")results = await client.search(query, **search_kwargs)filtered_items = self._filter_search_items(results, min_score=min_score)for item_type, items in filtered_items.items():diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 161d621fc..3cfa1fa95 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -43,6 +43,7 @@ class VikingClient:*,agent_id: Optional[str] = None,connection: Optional[Mapping[str, Any]] = None,+ actor_peer_id: Optional[str] = None,):if agent_id is None:agent_id = workspace_id@@ -70,13 +71,19 @@ class VikingClient:self._namespace_policy_loaded = Falseself._request_connection = self._normalize_connection(connection)self._request_role: str | None = None+ connection_actor_peer_id = (+ self._request_connection.get("actor_peer_id") if self._request_connection else None+ )+ self.actor_peer_id = self._peer_id(actor_peer_id) or self._peer_id(connection_actor_peer_id)if openviking_config.mode == "local":+ client_kwargs = {"url": openviking_config.server_url}+ self._apply_actor_peer_scope(client_kwargs)if agent_id is None or _is_session_key(agent_id):- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)+ self.client = ov.AsyncHTTPClient(**client_kwargs)self.agent_id = "default"else:- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)+ self.client = ov.AsyncHTTPClient(**client_kwargs)self.account_id = "default"self.user_id = "default"self.admin_user_id = "default"@@ -99,6 +106,7 @@ class VikingClient:remote_client_kwargs["account"] = openviking_config.account_idremote_client_kwargs["user"] = openviking_config.admin_user_id+ self._apply_actor_peer_scope(remote_client_kwargs)self.client = ov.AsyncHTTPClient(**remote_client_kwargs)if self._is_root_key_mode() and self.ov_path:@@ -115,7 +123,15 @@ class VikingClient:if not isinstance(connection, Mapping):return Nonenormalized: dict[str, Any] = {}- for key in ("api_key", "account_id", "user_id", "agent_id", "role", "server_url"):+ for key in (+ "api_key",+ "account_id",+ "user_id",+ "agent_id",+ "role",+ "server_url",+ "actor_peer_id",+ ):value = connection.get(key)if isinstance(value, str) and value.strip():normalized[key] = value.strip()@@ -159,6 +175,7 @@ class VikingClient:if request_role != "user" and self.admin_user_id:remote_client_kwargs["user"] = self.admin_user_id+ self._apply_actor_peer_scope(remote_client_kwargs)self.client = ov.AsyncHTTPClient(**remote_client_kwargs)async def _initialize(self):@@ -173,9 +190,15 @@ class VikingClient:*,agent_id: Optional[str] = None,connection: Optional[Mapping[str, Any]] = None,+ actor_peer_id: Optional[str] = None,):"""Factory method to create and initialize a VikingClient instance."""- instance = cls(workspace_id=workspace_id, agent_id=agent_id, connection=connection)+ instance = cls(+ workspace_id=workspace_id,+ agent_id=agent_id,+ connection=connection,+ actor_peer_id=actor_peer_id,+ )await instance._initialize()return instance@@ -252,6 +275,10 @@ class VikingClient:def _peer_id(value: Optional[str]) -> Optional[str]:return _peer_id_from_external_id(str(value)) if value is not None else None+ def _apply_actor_peer_scope(self, client_kwargs: Dict[str, Any]) -> None:+ if self.actor_peer_id:+ client_kwargs["actor_peer_id"] = self.actor_peer_id+async def _load_namespace_policy(self) -> None:if self._namespace_policy_loaded:return@@ -366,14 +393,14 @@ class VikingClient:deduped.append(value)return deduped- def build_memory_search_requests(+ def build_memory_search_target_uris(self,*,user_ids: Optional[List[str]] = None,owner_user_id: Optional[str] = None,peer_ids: Optional[List[str]] = None,- ) -> List[Dict[str, Optional[str]]]:- requests: List[Dict[str, Optional[str]]] = []+ ) -> List[str]:+ target_uris: List[str] = []normalized_user_ids = self._dedupe_strings([str(user_id).strip() for user_id in (user_ids or []) if str(user_id).strip()])@@ -387,23 +414,16 @@ class VikingClient:effective_owner_user_id = self._effective_user_id(owner_user_id) if owner_user_id else Nonefor user_id in normalized_user_ids:- requests.append({"target_uri": self._memory_target_uri(user_id), "peer_id": None})+ target_uris.append(self._memory_target_uri(user_id))- if effective_owner_user_id and (not requests or normalized_peer_ids):- requests.append(- {"target_uri": self._memory_target_uri(effective_owner_user_id), "peer_id": None}- )+ if effective_owner_user_id and (not target_uris or normalized_peer_ids):+ target_uris.append(self._memory_target_uri(effective_owner_user_id))if effective_owner_user_id:for peer_id in normalized_peer_ids:try:- requests.append(- {- "target_uri": self._peer_memory_target_uri(- effective_owner_user_id, peer_id- ),- "peer_id": None,- }+ target_uris.append(+ self._peer_memory_target_uri(effective_owner_user_id, peer_id))except ValueError as exc:logger.warning(@@ -411,21 +431,22 @@ class VikingClient:)elif normalized_peer_ids:for peer_id in normalized_peer_ids:- requests.append({"target_uri": "viking://user/memories/", "peer_id": peer_id})-- if not requests:- requests.append({"target_uri": self._memory_target_uri(None), "peer_id": None})-- deduped: List[Dict[str, Optional[str]]] = []- seen: set[tuple[str, str]] = set()- for request in requests:- target_uri = str(request.get("target_uri") or "")- peer_id = str(request.get("peer_id") or "")- key = (target_uri, peer_id)- if not target_uri or key in seen:+ try:+ target_uris.append(self._current_peer_memory_target_uri(peer_id))+ except ValueError as exc:+ logger.warning(f"Skip invalid current peer memory target peer_id={peer_id}: {exc}")++ if not target_uris:+ target_uris.append(self._memory_target_uri(None))++ deduped: List[str] = []+ seen: set[str] = set()+ for target_uri in target_uris:+ target_uri = str(target_uri or "")+ if not target_uri or target_uri in seen:continue- seen.add(key)- deduped.append({"target_uri": target_uri, "peer_id": request.get("peer_id")})+ seen.add(target_uri)+ deduped.append(target_uri)return dedupeddef _skill_memory_uri(self, skill_name: str, user_id: Optional[str] = None) -> str:@@ -435,13 +456,16 @@ class VikingClient:self,query: str,target_uri: Optional[str] = None,- peer_id: Optional[str] = None,+ context_type: Optional[str | list[str]] = None,+ filter: Optional[Dict[str, Any]] = None,limit: int = 10,):"""搜索资源"""kwargs: Dict[str, Any] = {"limit": limit}- if peer_id is not None:- kwargs["peer_id"] = peer_id+ if context_type is not None:+ kwargs["context_type"] = context_type+ if filter is not None:+ kwargs["filter"] = filterif target_uri:return await self.client.find(query, target_uri=target_uri, **kwargs)return await self.client.find(query, **kwargs)@@ -512,7 +536,6 @@ class VikingClient:target_uri: str | list[str] | None = None,limit: int = 10,user_id: Optional[str] = None,- peer_id: Optional[str] = None,) -> Dict[str, Any]:client = self.clientshould_close = False@@ -524,7 +547,6 @@ class VikingClient:query,target_uri=target_uri,limit=limit,- peer_id=self._peer_id(peer_id),)finally:if should_close:@@ -659,6 +681,7 @@ class VikingClient:client_kwargs["account"] = self.account_idclient_kwargs["user"] = self.admin_user_id+ self._apply_actor_peer_scope(client_kwargs)client = ov.AsyncHTTPClient(**client_kwargs)await client.initialize()return client, True@@ -674,7 +697,6 @@ class VikingClient:*,owner_user_id: Optional[str] = None,peer_ids: Optional[list[str]] = None,- peer_id: Optional[str] = None,) -> list[Any] | dict[str, list[Any]]:"""通过上下文消息检索用户 memory。"""@@ -699,13 +721,10 @@ class VikingClient:str(user_id).strip() for user_id in normalized_user_ids if str(user_id).strip()]- peer_values = [*(peer_ids or [])]- if peer_id:- peer_values.append(peer_id)normalized_peer_ids = self._dedupe_strings([pid- for pid in (self._peer_id(peer_value) for peer_value in peer_values)+ for pid in (self._peer_id(peer_value) for peer_value in (peer_ids or []))if pid])@@ -726,23 +745,21 @@ class VikingClient:if not user_exists:await self._initialize_user(effective_user_id)- search_requests = self.build_memory_search_requests(+ target_uris = self.build_memory_search_target_uris(user_ids=normalized_user_ids,owner_user_id=effective_owner_user_id,peer_ids=normalized_peer_ids,)- if not search_requests:+ if not target_uris:return []all_user_memories = []- for request in search_requests:+ for target_uri in target_uris:find_kwargs: Dict[str, Any] = {"query": query,- "target_uri": request["target_uri"],+ "target_uri": target_uri,"limit": limit,}- if request.get("peer_id") is not None:- find_kwargs["peer_id"] = self._peer_id(request.get("peer_id"))user_memory = await self.client.find(**find_kwargs)all_user_memories.extend(_extract_memories(user_memory))@@ -831,13 +848,15 @@ class VikingClient:client = self._user_clients.get(user_id)if client is None:- client = ov.AsyncHTTPClient(- url=self.openviking_config.server_url,- api_key=api_key,- account=self.account_id,- user=user_id,- profile_enabled=False,- )+ client_kwargs = {+ "url": self.openviking_config.server_url,+ "api_key": api_key,+ "account": self.account_id,+ "user": user_id,+ "profile_enabled": False,+ }+ self._apply_actor_peer_scope(client_kwargs)+ client = ov.AsyncHTTPClient(**client_kwargs)await client.initialize()self._user_clients[user_id] = clientreturn client@@ -948,12 +967,18 @@ class VikingClient:return ""async def ensure_session(- self, session_id: str, user_id: Optional[str] = None+ self,+ session_id: str,+ user_id: Optional[str] = None,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:client = await self._session_client_for_user(user_id)if await client.session_exists(session_id):return await client.get_session(session_id)- return await client.create_session(session_id=session_id)+ return await client.create_session(+ session_id=session_id,+ memory_policy=memory_policy,+ )async def get_session(self, session_id: str, user_id: Optional[str] = None) -> Dict[str, Any]:await self.ensure_session(session_id, user_id=user_id)@@ -1004,15 +1029,18 @@ class VikingClient:user_id: Optional[str] = None,memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:- await self.ensure_session(session_id, user_id=user_id)- client = await self._session_client_for_user(user_id)- return await client.commit_session(+ await self.ensure_session(session_id,- keep_recent_count=keep_recent_count,+ user_id=user_id,memory_policy=memory_policyif memory_policy is not Noneelse self.default_memory_policy(),)+ client = await self._session_client_for_user(user_id)+ return await client.commit_session(+ session_id,+ keep_recent_count=keep_recent_count,+ )async def commit(self,@@ -1025,6 +1053,14 @@ class VikingClient:):"""Append messages to a stable session and commit it."""session_user_id = self._effective_session_user_id(user_id)+ session_memory_policy = (+ memory_policy if memory_policy is not None else self.default_memory_policy()+ )+ await self.ensure_session(+ session_id,+ user_id=session_user_id,+ memory_policy=session_memory_policy,+ )appended = await self.append_messages(session_id,messages,@@ -1035,7 +1071,7 @@ class VikingClient:session_id,keep_recent_count=keep_recent_count,user_id=session_user_id,- memory_policy=memory_policy,+ memory_policy=session_memory_policy,)logger.debug(f"Committed OpenViking session {session_id}, "@@ -1096,7 +1132,6 @@ async def account_test():print(res)-if __name__ == "__main__":asyncio.run(main_test())# asyncio.run(account_test())diff --git a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py b/bot/vikingbot/tests/unit/test_openviking_peer_identity.pyindex e81bf1ff0..607b9ca47 100644--- a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py+++ b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py@@ -117,6 +117,14 @@ async def test_commit_uses_current_user_key_session_and_sender_peer(monkeypatch)client = _client(api_key_type="user")calls = {}+ async def fake_ensure_session(session_id, user_id=None, memory_policy=None):+ calls["ensure"] = {+ "session_id": session_id,+ "user_id": user_id,+ "memory_policy": memory_policy,+ }+ return {"session_id": session_id}+async def fake_append_messages(session_id,messages,@@ -142,6 +150,7 @@ async def test_commit_uses_current_user_key_session_and_sender_peer(monkeypatch)}return {"archived": True}+ monkeypatch.setattr(client, "ensure_session", fake_ensure_session)monkeypatch.setattr(client, "append_messages", fake_append_messages)monkeypatch.setattr(client, "commit_session", fake_commit_session)@@ -151,10 +160,15 @@ async def test_commit_uses_current_user_key_session_and_sender_peer(monkeypatch)peer_id="telegram:alice",)+ assert calls["ensure"]["user_id"] is None+ assert calls["ensure"]["memory_policy"] == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }assert calls["append"]["session_user_id"] is Noneassert calls["append"]["default_user_peer_id"] == TELEGRAM_ALICE_PEER_IDassert calls["commit"]["user_id"] is None- assert calls["commit"]["memory_policy"] is None+ assert calls["commit"]["memory_policy"] == calls["ensure"]["memory_policy"]@pytest.mark.asyncio@@ -162,6 +176,10 @@ async def test_commit_keeps_root_owner_user_explicit(monkeypatch):client = _client(api_key_type="root")calls = {}+ async def fake_ensure_session(session_id, user_id=None, memory_policy=None):+ calls["ensure"] = {"user_id": user_id, "memory_policy": memory_policy}+ return {"session_id": session_id}+async def fake_append_messages(session_id,messages,@@ -180,6 +198,7 @@ async def test_commit_keeps_root_owner_user_explicit(monkeypatch):calls["commit"] = {"user_id": user_id, "memory_policy": memory_policy}return {"archived": True}+ monkeypatch.setattr(client, "ensure_session", fake_ensure_session)monkeypatch.setattr(client, "append_messages", fake_append_messages)monkeypatch.setattr(client, "commit_session", fake_commit_session)@@ -189,10 +208,15 @@ async def test_commit_keeps_root_owner_user_explicit(monkeypatch):peer_id="telegram:alice",)+ assert calls["ensure"]["user_id"] == "bot-user"+ assert calls["ensure"]["memory_policy"] == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }assert calls["append"]["session_user_id"] == "bot-user"assert calls["append"]["default_user_peer_id"] == TELEGRAM_ALICE_PEER_IDassert calls["commit"]["user_id"] == "bot-user"- assert calls["commit"]["memory_policy"] is None+ assert calls["commit"]["memory_policy"] == calls["ensure"]["memory_policy"]@pytest.mark.asyncio@@ -200,16 +224,19 @@ async def test_commit_session_defaults_to_peer_only_memory(monkeypatch):client = _client(api_key_type="user")calls = {}- async def fake_ensure_session(session_id, user_id=None):- calls["ensure"] = {"session_id": session_id, "user_id": user_id}+ async def fake_ensure_session(session_id, user_id=None, memory_policy=None):+ calls["ensure"] = {+ "session_id": session_id,+ "user_id": user_id,+ "memory_policy": memory_policy,+ }return {"session_id": session_id}class FakeSessionClient:- async def commit_session(self, session_id, keep_recent_count=0, memory_policy=None):+ async def commit_session(self, session_id, keep_recent_count=0):calls["commit"] = {"session_id": session_id,"keep_recent_count": keep_recent_count,- "memory_policy": memory_policy,}return {"archived": True}@@ -222,7 +249,11 @@ async def test_commit_session_defaults_to_peer_only_memory(monkeypatch):await client.commit_session("session-1", keep_recent_count=2)- assert calls["commit"]["memory_policy"] == {+ assert calls["ensure"]["memory_policy"] == {"self": {"enabled": False},"peer": {"enabled": True},}+ assert calls["commit"] == {+ "session_id": "session-1",+ "keep_recent_count": 2,+ }