Skip to content

The agent that grows with you

fix(env): clear inherited Hermes keys missing from profile .env (ACP leak)

keepConcentration968b66338c9f
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 6668677bd52..ed5c191bc16 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -316,6 +316,14 @@ _EXTRA_ENV_KEYS = frozenset({
"LANGFUSE_PUBLIC_KEY",
"LANGFUSE_SECRET_KEY",
"LANGFUSE_BASE_URL",
+ # ACP (Agent Client Protocol) keys — profile-isolable so different
+ # profiles can use different ACP backends without cross-leak.
+ "HERMES_ACP_AUTH_METHOD",
+ "HERMES_ACP_AUTO_APPROVE",
+ "HERMES_COPILOT_ACP_COMMAND",
+ "HERMES_COPILOT_ACP_ARGS",
+ "COPILOT_CLI_PATH",
+ "COPILOT_ACP_BASE_URL",
})
import yaml
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index f1e4eae9006..f10da837560 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -50,6 +50,71 @@ _SECRET_SOURCE_VALUES_BY_HOME: dict[str, dict[str, str]] = {}
_APPLIED_HOMES: set[str] = set()
+def _known_hermes_env_keys() -> set[str]:
+ """Return the combined set of known Hermes env-var keys.
+
+ Includes both ``OPTIONAL_ENV_VARS`` (setup-flow vars with metadata) and
+ ``_EXTRA_ENV_KEYS`` (provider/platform keys managed outside the setup
+ wizard). Lazy-imported to avoid circular-dependency during early-bootstrap
+ ``load_hermes_dotenv()`` calls.
+ """
+ from hermes_cli.config import _EXTRA_ENV_KEYS
+ from hermes_cli.config_defaults import OPTIONAL_ENV_VARS
+
+ return set(OPTIONAL_ENV_VARS.keys()) | set(_EXTRA_ENV_KEYS)
+
+
+def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
+ """Return KEY names assigned in a dotenv file (including empty ``KEY=``).
+
+ Uses a fast line scanner rather than full dotenv parsing so it works
+ during early bootstrap without importing python-dotenv. Ignores comment
+ and blank lines. Non-ASCII encoding errors fall back to ``latin-1``,
+ matching ``_load_dotenv_with_fallback``.
+ """
+ keys: set[str] = set()
+ try:
+ text = path.read_text(encoding="utf-8", errors="replace")
+ except Exception:
+ try:
+ text = path.read_text(encoding="latin-1", errors="replace")
+ except Exception:
+ return keys
+ for line in text.splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key = line.split("=", 1)[0].strip()
+ if key:
+ keys.add(key)
+ return keys
+
+
+def _clear_known_keys_missing_from_dotenv(path: Path) -> None:
+ """Remove inherited known Hermes keys absent from the profile ``.env``.
+
+ After the profile's ``.env`` has been loaded with ``override=True``,
+ scan the file for which known Hermes keys it explicitly defines and
+ delete any known key that exists in ``os.environ`` but is *not* present
+ in the file.
+
+ This mirrors the semantics of ``reload_env()`` in ``config.py`` (which
+ already deletes missing known keys on hot-reload) and closes the gap
+ between startup and hot-reload: without this, a known key inherited
+ from the parent process leaks into the profile, silently mutating
+ provider / ACP / platform behaviour.
+
+ Does **not** run when the ``.env`` file does not exist (bare-profile
+ case, which follows ``#66930`` / ``#67027`` semantics).
+ """
+ if not path.exists():
+ return
+ defined = _env_keys_defined_in_dotenv(path)
+ for key in _known_hermes_env_keys():
+ if key not in defined and key in os.environ:
+ del os.environ[key]
+
+
def get_secret_source(env_var: str) -> str | None:
"""Return the label of the secret source that supplied ``env_var``, if any.
@@ -320,6 +385,9 @@ def load_hermes_dotenv(
if user_env.exists():
_load_dotenv_with_fallback(user_env, override=True)
loaded.append(user_env)
+ # Mirror reload_env() known-key cleanup so inherited Hermes keys
+ # absent from this profile's .env do not leak into the runtime.
+ _clear_known_keys_missing_from_dotenv(user_env)
# Load .op.env AFTER .env so that .env values win, but the bootstrap
# token (OP_SERVICE_ACCOUNT_TOKEN) becomes available for
diff --git a/tests/hermes_cli/test_env_loader.py b/tests/hermes_cli/test_env_loader.py
index c1870715cb2..305d75dbbdf 100644
--- a/tests/hermes_cli/test_env_loader.py
+++ b/tests/hermes_cli/test_env_loader.py
@@ -169,3 +169,99 @@ def test_cp1252_env_regression_does_not_crash(tmp_path, monkeypatch):
assert os.getenv("LATIN1_VALUE") == "café"
# Sanitize must not have rewritten (would have persisted U+FFFD).
assert env_file.read_bytes() == before
+
+
+# ---------------------------------------------------------------------------
+# Profile .env isolation: inherited known-key cleanup
+# ---------------------------------------------------------------------------
+
+
+def test_known_keys_absent_from_user_env_are_cleared(tmp_path, monkeypatch):
+ """Known Hermes keys inherited from parent process are removed when absent
+ from the profile's .env.
+
+ This is the startup equivalent of ``reload_env()``'s known-key cleanup and
+ fixes the isolation gap where one profile's ACP/provider settings silently
+ leak into another profile's runtime via ``os.environ`` inheritance.
+ """
+ home = tmp_path / "hermes"
+ home.mkdir()
+ (home / ".env").write_text(
+ "OPENAI_BASE_URL=https://profile.example/v1\n", encoding="utf-8"
+ )
+
+ # Inherited known keys from parent process / other profile
+ monkeypatch.setenv("OPENAI_BASE_URL", "https://stale.example/v1")
+ monkeypatch.setenv("HERMES_ACP_AUTH_METHOD", "cursor_login")
+ monkeypatch.setenv("COPILOT_CLI_PATH", "/usr/bin/claude-code")
+ # Unrelated shell var must NOT be touched
+ monkeypatch.setenv("MY_SHELL_ONLY_VAR", "keep-me")
+
+ load_hermes_dotenv(hermes_home=home)
+
+ # OPENAI_BASE_URL is defined in the profile .env → overridden to the new value
+ assert os.getenv("OPENAI_BASE_URL") == "https://profile.example/v1"
+ # HERMES_ACP_AUTH_METHOD and COPILOT_CLI_PATH are NOT in the profile .env → cleared
+ assert "HERMES_ACP_AUTH_METHOD" not in os.environ
+ assert "COPILOT_CLI_PATH" not in os.environ
+ # Unrelated shell vars must survive
+ assert os.getenv("MY_SHELL_ONLY_VAR") == "keep-me"
+
+
+def test_empty_assignment_in_user_env_is_preserved(tmp_path, monkeypatch):
+ """An explicit ``KEY=`` (empty value) in the profile .env keeps the key
+ in ``os.environ`` — distinct from a key absent from .env entirely.
+
+ Empty ``HERMES_ACP_AUTH_METHOD=`` tells the ACP adapter to skip
+ ``authenticate`` (the key exists, its value is just empty). This is the
+ documented workaround for the leak and must still work after the cleanup.
+ """
+ home = tmp_path / "hermes"
+ home.mkdir()
+ (home / ".env").write_text("HERMES_ACP_AUTH_METHOD=\n", encoding="utf-8")
+
+ monkeypatch.setenv("HERMES_ACP_AUTH_METHOD", "cursor_login")
+ monkeypatch.setenv("COPILOT_CLI_PATH", "/usr/bin/sneaky") # NOT in .env → cleared
+
+ load_hermes_dotenv(hermes_home=home)
+
+ # KEY= in .env keeps the key (now empty string)
+ assert "HERMES_ACP_AUTH_METHOD" in os.environ
+ assert os.environ["HERMES_ACP_AUTH_METHOD"] == ""
+ # COPILOT_CLI_PATH is absent from .env → cleared
+ assert "COPILOT_CLI_PATH" not in os.environ
+
+
+def test_no_user_env_does_not_clear_anything(tmp_path, monkeypatch):
+ """When no profile .env exists (bare profile), load_hermes_dotenv must not
+ wipe inherited known keys — the bare-profile case follows #66930 / #67027
+ semantics and the user's shell environment should not be mutilated.
+ """
+ home = tmp_path / "hermes"
+ home.mkdir()
+ # No .env in home — bare profile
+
+ monkeypatch.setenv("HERMES_ACP_AUTH_METHOD", "cursor_login")
+ monkeypatch.setenv("PATH", "/usr/bin:/bin")
+
+ load_hermes_dotenv(hermes_home=home)
+
+ assert os.getenv("HERMES_ACP_AUTH_METHOD") == "cursor_login"
+ assert os.getenv("PATH") == "/usr/bin:/bin"
+
+
+def test_known_key_explicitly_set_in_user_env_is_kept(tmp_path, monkeypatch):
+ """A known Hermes key that IS explicitly set in the profile .env survives
+ the cleanup (overrides the inherited value).
+ """
+ home = tmp_path / "hermes"
+ home.mkdir()
+ (home / ".env").write_text(
+ "HERMES_ACP_AUTH_METHOD=claude_code_cli\n", encoding="utf-8"
+ )
+
+ monkeypatch.setenv("HERMES_ACP_AUTH_METHOD", "cursor_login")
+
+ load_hermes_dotenv(hermes_home=home)
+
+ assert os.getenv("HERMES_ACP_AUTH_METHOD") == "claude_code_cli"