The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hindsight): keep scopeless daemon worker from clobbering profile env key
red47112c24ed4b6eae
diff --git a/plugins/memory/hindsight/README.md b/plugins/memory/hindsight/README.mdindex fc9e166ea2d..06382a43215 100644--- a/plugins/memory/hindsight/README.md+++ b/plugins/memory/hindsight/README.md@@ -123,6 +123,13 @@ Config file: `~/.hermes/hindsight/config.json`The LLM API key is stored in `~/.hermes/.env` as `HINDSIGHT_LLM_API_KEY`.+The embedded daemon is a subprocess that cannot see the per-turn secret+scope, so it reads the key from `~/.hindsight/profiles/<profile>.env`+(materialized owner-only at setup and on config change). Key resolution+order is explicit config → secret scope → the on-disk profile env, and the+rewrite path is fail-closed: a build with no key never clobbers a profile+file that already holds one.+## ToolsAvailable in `hybrid` and `tools` memory modes:diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pyindex c35b1894935..a035edd13bb 100644--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@ -36,6 +36,7 @@ from .embedded import (_RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,_check_local_runtime, _embedded_llm_api_key, _embedded_profile_env_path,_export_port_health_grace_timeout, _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,+ _may_rewrite_profile_env,)from .settings import (_DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,@@ -816,11 +817,24 @@ class HindsightMemoryProvider(MemoryProvider):client = self._get_client()profile = self._config.get("profile", "hermes")# Profile .env out of sync with config -> rewrite and restart a running daemon.+ # Fail-closed on key material: when this process holds no key (no secret+ # scope on this thread) but the file does, a rewrite would destroy the+ # only key copy the daemon subprocess can read. Skip the write AND the+ # stop: restarting the daemon now would boot it keyless, which is the+ # exact outage this guards against. _get_client() above already passed+ # whatever key WAS available into the in-process client kwargs.if _load_simple_env(_embedded_profile_env_path(self._config)) != _build_embedded_profile_env(self._config):- _materialize_embedded_profile_env(self._config)- if client._manager.is_running(profile):- _log("\n=== Config changed, restarting daemon ===\n")- client._manager.stop(profile)+ if _may_rewrite_profile_env(self._config):+ _materialize_embedded_profile_env(self._config)+ if client._manager.is_running(profile):+ _log("\n=== Config changed, restarting daemon ===\n")+ client._manager.stop(profile)+ else:+ logger.warning(+ "Hindsight profile env for %r holds an LLM API key this process cannot see "+ "(no secret scope); leaving the file untouched so the daemon keeps its key.",+ profile)+ _log("\n=== Profile env has a key this process cannot see; left untouched ===\n")client._ensure_started()_log("\n=== Daemon started successfully ===\n")except Exception as e:diff --git a/plugins/memory/hindsight/embedded.py b/plugins/memory/hindsight/embedded.pyindex a155c67fc18..780836f6b25 100644--- a/plugins/memory/hindsight/embedded.py+++ b/plugins/memory/hindsight/embedded.py@@ -11,7 +11,7 @@ import sysfrom pathlib import Pathfrom typing import Any-from agent.secret_scope import get_secret+from agent.secret_scope import UnscopedSecretError, get_secretfrom .settings import _DEFAULT_IDLE_TIMEOUT, _daemon_llm_provider, _parse_int_setting@@ -110,8 +110,50 @@ def _embedded_profile_env_path(config: dict[str, Any]) -> Path:return Path.home() / ".hindsight" / "profiles" / f"{profile}.env"+def _on_disk_llm_api_key(config: dict[str, Any]) -> str:+ """The key currently persisted in the profile env file ("" when absent)."""+ with contextlib.suppress(Exception):+ return _load_simple_env(_embedded_profile_env_path(config)).get("HINDSIGHT_API_LLM_API_KEY", "") or ""+ return ""++def _embedded_llm_api_key(config: dict[str, Any]) -> str:- return config.get("llmApiKey") or config.get("llm_api_key") or get_secret("HINDSIGHT_LLM_API_KEY", "")+ """Resolve the LLM API key: explicit config first, then the profile secret+ scope, then the on-disk profile env as a last resort.++ The disk fallback is the durability core: the background daemon-start+ worker usually runs with no secret scope, and without it the client would+ be built keyless — its ``ensure_running(config)`` merge would then+ overwrite the file's good key with emptiness inside the upstream manager+ (``_register_profile`` → ``create_profile`` rewrite). Falling back to the+ persisted key keeps the in-process client, the file compare, and the+ daemon subprocess all keyed from the same surviving copy.+ """+ if config.get("llmApiKey") or config.get("llm_api_key"):+ return config.get("llmApiKey") or config.get("llm_api_key")+ try:+ scoped = get_secret("HINDSIGHT_LLM_API_KEY", "")+ except UnscopedSecretError:+ # Multiplexed gateway with no profile scope on this thread: never let+ # a missing scope read os.environ (another profile's key may live+ # there). Fall through to the on-disk copy below.+ scoped = ""+ if scoped:+ return scoped+ return _on_disk_llm_api_key(config)+++def _may_rewrite_profile_env(config: dict[str, Any]) -> bool:+ """Whether rewriting the profile env file is safe right now.++ False exactly when the build has no key (no scope, no config key) but the+ file holds one: a rewrite would clobber live credentials with emptiness.+ All other mismatches (model/provider/base-url/idle-timeout drift, missing+ file, key rotation to a new non-empty value) remain writable.+ """+ if _build_embedded_profile_env(config).get("HINDSIGHT_API_LLM_API_KEY"):+ return True+ return not _on_disk_llm_api_key(config)def _build_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None) -> dict[str, str]:diff --git a/tests/plugins/memory/test_hindsight_env_perms.py b/tests/plugins/memory/test_hindsight_env_perms.pyindex f18143ba7ce..2e6a1a627fd 100644--- a/tests/plugins/memory/test_hindsight_env_perms.py+++ b/tests/plugins/memory/test_hindsight_env_perms.py@@ -13,6 +13,12 @@ from plugins.memory.hindsight import (_embedded_profile_env_path,_materialize_embedded_profile_env,)+from plugins.memory.hindsight.embedded import (+ _build_embedded_profile_env,+ _load_simple_env,+ _may_rewrite_profile_env,+ _on_disk_llm_api_key,+)@pytest.fixture(autouse=True)@@ -78,3 +84,125 @@ def test_secret_file_removed_when_permission_validation_fails(monkeypatch):assert not _embedded_profile_env_path(_CONFIG).exists(), ("secret env file must be cleaned up when validation fails")++[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")+def test_scopeless_worker_reuses_on_disk_key(monkeypatch):+ """Durability core: with no secret scope, the key resolves from disk.++ The daemon-start worker usually has no scope; without the disk fallback+ the client would be built keyless and the upstream manager merge+ (ensure_running -> _register_profile -> create_profile rewrite) would+ overwrite the file's good key with emptiness.+ """+ from agent import secret_scope++ profile_env = _embedded_profile_env_path(_CONFIG)+ profile_env.parent.mkdir(parents=True)+ profile_env.write_text(+ "HINDSIGHT_API_LLM_PROVIDER=openai\n"+ "HINDSIGHT_API_LLM_API_KEY=sk-test-live-key\n"+ "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"+ "HINDSIGHT_API_LOG_LEVEL=info\n",+ encoding="utf-8",+ )+ os.chmod(profile_env, 0o600)++ token = secret_scope.set_secret_scope(None)+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)+ monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)+ try:+ from plugins.memory.hindsight.embedded import _embedded_llm_api_key++ assert _embedded_llm_api_key(_CONFIG) == "sk-test-live-key"+ # ...so the build carries a key and the rewrite gate passes.+ assert _build_embedded_profile_env(_CONFIG)["HINDSIGHT_API_LLM_API_KEY"] == "sk-test-live-key"+ assert _may_rewrite_profile_env(_CONFIG) is True+ finally:+ secret_scope.reset_secret_scope(token)++[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")+def test_gate_refuses_keyless_build_against_keyed_disk(monkeypatch):+ """_may_rewrite_profile_env False branch: keyless build + keyed disk."""+ import plugins.memory.hindsight.embedded as hs_embedded++ monkeypatch.setattr(hs_embedded, "_build_embedded_profile_env",+ lambda config, **kw: {"HINDSIGHT_API_LLM_API_KEY": ""})+ monkeypatch.setattr(hs_embedded, "_on_disk_llm_api_key", lambda config: "sk-test-live-key")+ assert hs_embedded._may_rewrite_profile_env(_CONFIG) is False++[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")+def test_on_disk_key_survives_empty_build(monkeypatch):+ """Fail-closed core: a keyed file survives a key-destroying rewrite attempt.++ Uses the worker's real compare inputs — on-disk file vs a keyless build+ (llm_api_key="" models the pre-fix scopeless build shape) — and the+ gated worker body (rewrite only when the gate passes).+ """+ from agent import secret_scope++ profile_env = _embedded_profile_env_path(_CONFIG)+ profile_env.parent.mkdir(parents=True)+ profile_env.write_text(+ "HINDSIGHT_API_LLM_PROVIDER=openai\n"+ "HINDSIGHT_API_LLM_API_KEY=sk-test-live-key\n"+ "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"+ "HINDSIGHT_API_LOG_LEVEL=info\n",+ encoding="utf-8",+ )+ os.chmod(profile_env, 0o600)++ token = secret_scope.set_secret_scope(None)+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)+ monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)+ try:+ # The worker's real compare inputs: on-disk file vs a keyless build+ # (llm_api_key="" models the pre-fix scopeless build shape).+ keyless = _build_embedded_profile_env(_CONFIG, llm_api_key="")+ assert keyless["HINDSIGHT_API_LLM_API_KEY"] == ""+ assert _load_simple_env(profile_env) != keyless++ # The gate predicate on those same inputs: keyless build + keyed disk+ # -> refuse. Inline the predicate (same two reads the gate uses) so+ # the test pins behavior, not the helper's name.+ build_has_key = bool(keyless.get("HINDSIGHT_API_LLM_API_KEY"))+ disk_has_key = bool(_on_disk_llm_api_key(_CONFIG))+ assert not build_has_key and disk_has_key++ before = profile_env.read_bytes()+ # Gated worker body: rewrite only when the gate passes.+ if build_has_key or not disk_has_key:+ _materialize_embedded_profile_env(_CONFIG, llm_api_key="")+ assert profile_env.read_bytes() == before+ assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600+ finally:+ secret_scope.reset_secret_scope(token)+++def test_rewrite_allowed_when_build_carries_key(monkeypatch):+ """A build WITH key material (rotation, model drift) must still rewrite."""+ profile_env = _embedded_profile_env_path(_CONFIG)+ profile_env.parent.mkdir(parents=True)+ profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=sk-old\n", encoding="utf-8")++ cfg = dict(_CONFIG, llm_api_key="sk-new")+ assert _may_rewrite_profile_env(cfg) is True+ _materialize_embedded_profile_env(cfg)+ assert "HINDSIGHT_API_LLM_API_KEY=sk-new\n" in profile_env.read_text(encoding="utf-8")+++def test_rewrite_allowed_when_no_key_anywhere(monkeypatch):+ """Keyless providers (ollama) must not brick: empty build + empty disk rewrites."""+ from agent import secret_scope++ token = secret_scope.set_secret_scope(None)+ monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)+ try:+ cfg = dict(_CONFIG, llm_provider="ollama", llm_model="qwen3:8b")+ # No key on disk either -> gate passes, non-key drift still converges.+ assert _on_disk_llm_api_key(cfg) == ""+ assert _may_rewrite_profile_env(cfg) is True+ finally:+ secret_scope.reset_secret_scope(token)