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
fix(hermes): skip writes for non-primary agent contexts (#5353)
HMYDK3b9928ee40fb
diff --git a/examples/hermes-plugin/README.md b/examples/hermes-plugin/README.mdindex 28f74b407..afe331340 100644--- a/examples/hermes-plugin/README.md+++ b/examples/hermes-plugin/README.md@@ -378,3 +378,12 @@ client commits do not use the server scheduler's interval or retention settings.The plugin retains the existing `keep_recent_count: 0` commit behavior.The threshold is not a hard limit on extraction input: one turn canexceed it, and the server may include other context during extraction.++### Non-primary contexts++Hermes passes an `agent_context` to `initialize()`. Sessions started for scheduled+cron jobs, delegated subagents, or flush forks (`cron`, `subagent`, `flush`) are+non-primary: recall and profile reads keep working, but the provider skips turn+uploads, session commits, and memory mirroring, so fixed-prompt job output neither+lands in the memory bank nor spends server-side extraction budget. Interactive+sessions (and hosts that predate `agent_context`) keep the previous write behavior.diff --git a/examples/hermes-plugin/__init__.py b/examples/hermes-plugin/__init__.pyindex 710980b0f..0e1cefdfd 100644--- a/examples/hermes-plugin/__init__.py+++ b/examples/hermes-plugin/__init__.py@@ -121,6 +121,10 @@ _SESSION_START_SUFFIXES = ("memories/profile.md", "memories/preferences", "memor_SESSION_START_LIST_PARAMS = {"output": "agent", "recursive": True, "abs_limit": 512, "node_limit": 512}# Built-in memory tool `target` -> mirror subdir (user facts -> preferences, agent notes -> patterns)._MEMORY_WRITE_TARGET_SUBDIR_MAP = {"user": "preferences", "memory": "patterns"}+# Host contexts that must not write into OpenViking. Fixed-prompt output from scheduled+# jobs, delegated subagents, and flush forks has no memory value and would spend server-side+# extraction budget. Hermes delivers the context to initialize(); recall/read paths are unchanged.+_NON_PRIMARY_AGENT_CONTEXTS = frozenset({"cron", "subagent", "flush"})# OpenViking-generated summaries; non-.md sidecars are already rejected by the .md check._GENERATED_MEMORY_SUMMARY_FILENAMES = {".abstract.md", ".overview.md"}_LOCAL_OPENVIKING_HOSTS = {"localhost", "127.0.0.1", "::1"}@@ -1312,6 +1316,10 @@ class OpenVikingMemoryProvider(MemoryProvider):self._runtime_start_thread: Optional[threading.Thread] = Noneself._runtime_start_pending = Falseself._shutting_down = False # finalizers stop issuing network writes+ # Non-primary contexts (cron/subagent/flush) skip OpenViking writes; resolved in+ # initialize() from the host's agent_context.+ self._agent_context = "primary"+ self._writes_enabled = True@propertydef name(self) -> str:@@ -1506,6 +1514,14 @@ class OpenVikingMemoryProvider(MemoryProvider):self._user_id = _gateway_peer_id(self._gateway_platform, self._gateway_user_id_alt or self._gateway_user_id)self._turn_peer.set(None)self._hermes_home = str(kwargs.get("hermes_home") or "").strip() or str(get_hermes_home())+ self._agent_context = str(kwargs.get("agent_context") or "primary")+ self._writes_enabled = self._agent_context not in _NON_PRIMARY_AGENT_CONTEXTS+ if not self._writes_enabled:+ logger.debug(+ "OpenViking writes disabled for %s context (session %s)",+ self._agent_context,+ session_id,+ )self._acquire_run_lock()self._profile_prefetched_sessions.clear()@@ -2236,6 +2252,8 @@ class OpenVikingMemoryProvider(MemoryProvider):messages: Optional[List[Dict[str, Any]]] = None,turn_author: Optional[Dict[str, Any]] = None) -> None:"""Record the conversation turn in OpenViking's session (non-blocking)."""+ if not self._writes_enabled:+ returnif not self._ensure_client():returnuser_content = _derive_openviking_user_text(user_content)@@ -2624,6 +2642,8 @@ class OpenVikingMemoryProvider(MemoryProvider):def on_session_end(self, messages: List[Dict[str, Any]]) -> None:"""Commit the session (synchronously — it must land before process exit) totrigger extraction of profile/preferences/entities/events/cases/patterns."""+ if not self._writes_enabled:+ returnif not self._ensure_client():returnwith self._session_state_lock:@@ -2650,6 +2670,8 @@ class OpenVikingMemoryProvider(MemoryProvider):The new session never accumulates messages, and memory extraction never fires for it. Seehermes-agent#28296."""+ if not self._writes_enabled:+ returnnew_id = str(new_session_id or "").strip()if not new_id or not self._ensure_client():return@@ -2732,6 +2754,8 @@ class OpenVikingMemoryProvider(MemoryProvider):metadata: Optional[Dict[str, Any]] = None,) -> None:"""Mirror successful built-in memory mutations to OpenViking."""+ if not self._writes_enabled:+ returnif action not in {"add", "replace", "remove"} or not self._ensure_client():returnif action in {"add", "replace"} and not content:diff --git a/examples/hermes-plugin/tests/test_standalone.py b/examples/hermes-plugin/tests/test_standalone.pyindex 09cbd4ce9..dc3eb2873 100644--- a/examples/hermes-plugin/tests/test_standalone.py+++ b/examples/hermes-plugin/tests/test_standalone.py@@ -676,6 +676,35 @@ def test_session_switch_commits_below_live_threshold(external_provider, monkeypaassert provider._session_id == "new-sid"[email protected]("agent_context", ["cron", "subagent", "flush"])+def test_non_primary_contexts_skip_writes(external_provider, monkeypatch, agent_context):+ """cron/subagent/flush contexts stay read-only: no turn uploads, commits, or mirroring."""+ from unittest.mock import Mock++ home, provider, module, _ = external_provider(f"non-primary-{agent_context}")+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("OPENVIKING_ENDPOINT", "http://127.0.0.1:19531")+ monkeypatch.setattr(module, "_classify_runtime_openviking_health", lambda *_: ("healthy", ""))+ provider.initialize("live-sid", hermes_home=str(home))+ assert (provider._agent_context, provider._writes_enabled) == ("primary", True)+ provider.initialize("live-sid", hermes_home=str(home), agent_context=agent_context)+ assert (provider._agent_context, provider._writes_enabled) == (agent_context, False)++ provider._client = Mock()+ provider._client.get.return_value = {"pending_tokens": 20000}+ provider._ensure_client = lambda: True+ provider._new_client = lambda: provider._client+ provider._acquire_run_lock()+ _finish_turn(provider)+ provider.on_session_switch("new-sid")+ provider.on_session_end([])+ provider.on_memory_write("add", "user", f"not mirrored ({agent_context})")+ assert provider._drain_finalizers(timeout=5)++ assert provider._client.method_calls == []+ assert provider._pending_sessions() == []++def test_live_commit_does_not_block_next_turn_or_lose_its_pending_marker(external_provider, monkeypatch):from concurrent.futures import ThreadPoolExecutor