The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(memory): unify store flags and bypass stale availability cache
kshitijk4poor5a5d6b966d8c
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex d8a5bd75e9b..769a6469fee 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -1811,9 +1811,12 @@ def init_agent(_memory_toolset_requested = "memory" in (agent.enabled_toolsets or [])if not skip_memory or _memory_toolset_requested:try:+ from tools.memory_tool import get_builtin_memory_store_flags+mem_config = _agent_cfg.get("memory", {})- agent._memory_enabled = mem_config.get("memory_enabled", False)- agent._user_profile_enabled = mem_config.get("user_profile_enabled", False)+ agent._memory_enabled, agent._user_profile_enabled = get_builtin_memory_store_flags(+ _agent_cfg+ )agent._memory_nudge_interval = int(mem_config.get("nudge_interval", 10))if agent._memory_enabled or agent._user_profile_enabled:from tools.memory_tool import MemoryStorediff --git a/tests/agent/test_builtin_memory_disabled_surface.py b/tests/agent/test_builtin_memory_disabled_surface.pyindex d2771bf4638..6978232926e 100644--- a/tests/agent/test_builtin_memory_disabled_surface.py+++ b/tests/agent/test_builtin_memory_disabled_surface.py@@ -74,6 +74,23 @@ class TestBuiltinMemoryToolAvailability:"""No config file at all must not strip a working tool."""assert "memory" in _memory_tool_names()+ def test_missing_memory_flags_fail_open_consistently(self):+ from tools.memory_tool import get_builtin_memory_store_flags++ assert get_builtin_memory_store_flags({"memory": {}}) == (True, True)+ assert get_builtin_memory_store_flags({}) == (True, True)++ def test_config_flip_updates_tool_without_manual_cache_clear(self, hermes_home):+ _write_memory_config(+ hermes_home, memory_enabled=False, user_profile_enabled=False+ )+ assert "memory" not in _memory_tool_names()++ _write_memory_config(+ hermes_home, memory_enabled=True, user_profile_enabled=False+ )+ assert "memory" in _memory_tool_names()+def test_unreadable_config_fails_open(self, hermes_home, monkeypatch):"""A config read error must not silently remove the tool."""from tools import memory_tool as memory_tool_modulediff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex c2ba72dc0ed..b489511db61 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -32,6 +32,7 @@ from hermes_constants import get_hermes_homefrom typing import Dict, Any, List, Optional, Tuplefrom utils import atomic_write_text+from tools.registry import no_cache_check_fn# fcntl is Unix-only; on Windows use msvcrt for file lockingmsvcrt = None@@ -1143,31 +1144,38 @@ def memory_tool(return json.dumps(result, ensure_ascii=False)-def builtin_memory_stores_enabled() -> bool:- """Return whether either built-in store (MEMORY.md / USER.md) is enabled.-- ``agent_init`` only builds a ``MemoryStore`` when at least one of- ``memory.memory_enabled`` / ``memory.user_profile_enabled`` is true, so with- both off the tool dispatches against ``store=None`` and every call fails- with "Memory is not available".+def get_builtin_memory_store_flags(config: Optional[Dict[str, Any]] = None) -> Tuple[bool, bool]:+ """Return ``(memory_enabled, user_profile_enabled)`` from resolved config.- Fails open when config can't be read: an unreadable config must not strip a- tool that would otherwise work.+ ``agent_init`` uses this same predicate to decide whether to construct the+ ``MemoryStore`` that backs the tool. Missing or unreadable config fails open+ so availability checks do not remove a tool that would otherwise work."""- try:- from hermes_cli.config import load_config_readonly-- section = (load_config_readonly() or {}).get("memory")- if not isinstance(section, dict):- return True- return bool(section.get("memory_enabled", True)) or bool(- section.get("user_profile_enabled", True)- )- except Exception:- logger.debug("Could not read memory config for availability", exc_info=True)- return True+ if config is None:+ try:+ from hermes_cli.config import load_config_readonly++ config = load_config_readonly()+ except Exception:+ logger.debug("Could not read memory config for availability", exc_info=True)+ return True, True++ section = config.get("memory") if isinstance(config, dict) else None+ if not isinstance(section, dict):+ return True, True+ return (+ bool(section.get("memory_enabled", True)),+ bool(section.get("user_profile_enabled", True)),+ )+++def builtin_memory_stores_enabled() -> bool:+ """Return whether either built-in store (MEMORY.md / USER.md) is enabled."""+ memory_enabled, user_profile_enabled = get_builtin_memory_store_flags()+ return memory_enabled or user_profile_enabled+@no_cache_check_fndef check_memory_requirements() -> bool:"""Available unless both built-in memory stores are disabled in config."""return builtin_memory_stores_enabled()diff --git a/tools/registry.py b/tools/registry.pyindex 08104091149..472a96f41d4 100644--- a/tools/registry.py+++ b/tools/registry.py@@ -245,14 +245,14 @@ class _PluginOverridePolicy:# ---------------------------------------------------------------------------# check_fn TTL cache#-# check_fn callables like tools/terminal_tool.check_terminal_requirements-# probe external state (Docker daemon, Modal SDK install, playwright binary+# external state (Docker daemon, Modal SDK install, playwright binary# availability). For a long-lived CLI or gateway process, calling them on# every get_definitions() is pure waste — external state changes on human# timescales. Cache results for ~30 s so env-var flips via ``hermes tools``# or live credential file changes propagate within a turn or two without# requiring any explicit invalidation.#+## Transient-failure suppression (issue #21658 / #5304): these probes can flap.# A single ``subprocess.run([docker, "version"], timeout=5)`` that times out# under load returns False for one call, which would silently strip the entire@@ -273,10 +273,16 @@ _CHECK_FN_TTL_SECONDS = 30.0_CHECK_FN_FAILURE_GRACE_SECONDS = 60.0_CHECK_FN_CACHE_MAX = 512_check_fn_cache: Dict[tuple[Callable, Optional[str]], tuple[float, bool]] = {}-# Monotonic timestamp of the most recent True result per check_fn._check_fn_last_good: Dict[tuple[Callable, Optional[str]], float] = {}_check_fn_cache_lock = threading.Lock()CHECK_FN_CACHE_BYPASS = ""+_NO_CACHE_CHECK_FNS: Set[Callable] = set()+++def no_cache_check_fn(fn: Callable) -> Callable:+ """Mark a local, config-backed availability check as uncached."""+ _NO_CACHE_CHECK_FNS.add(fn)+ return fndef _prune_check_fn_caches(now: float) -> None:@@ -322,15 +328,18 @@ def check_fn_cache_scope() -> Optional[str]:def _check_fn_cached(fn: Callable) -> bool:- """Return bool(fn()), TTL-cached across calls.-- Exceptions are swallowed as False. A transient False/exception within- ``_CHECK_FN_FAILURE_GRACE_SECONDS`` of the last True is suppressed (the- last-good True is returned and the failure is NOT cached, so the next call- re-probes) to keep flaky external checks (Docker daemon busy, socket- contention, probe timeout) from silently stripping tools mid-session.- """+ """Return bool(fn()), TTL-cached across calls."""now = time.monotonic()+ if fn in _NO_CACHE_CHECK_FNS:+ try:+ return bool(fn())+ except Exception:+ logger.warning(+ "check_fn %s raised; dependent tools will be unavailable this turn",+ getattr(fn, "__qualname__", fn),+ exc_info=True,+ )+ return Falsescope = check_fn_cache_scope()if scope == CHECK_FN_CACHE_BYPASS:try: