The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hermes_cli): stop config set/unset from wiping user overrides on invalid YAML
fangliquanflq77d4d23fbcca
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex e563d137fc3..d74d8168d9c 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -3408,14 +3408,33 @@ def read_raw_config_readonly() -> Dict[str, Any]:return cached_copy-def require_readable_config_before_write(config_path: Optional[Path] = None) -> None:- """Refuse to replace an existing config.yaml that cannot be read."""+def require_readable_config_before_write(+ config_path: Optional[Path] = None,+) -> Dict[str, Any]:+ """Refuse to replace an existing config.yaml that cannot be read or parsed.++ Guards two collapse-to-empty failure modes that would otherwise let a+ read-then-write caller silently wipe user overrides:++ 1. **Unreadable** (permissions / broken mount) - byte open fails.+ 2. **Unparseable or non-mapping** - YAML load raises, or the root is a+ list/scalar. ``read_user_config_raw()`` / bare ``except`` loaders treat+ both as ``{}``, so a subsequent write would replace the recoverable+ file with only the caller's partial dict.++ Returns the loaded mapping (or ``{}`` for a missing / empty / null+ document) so mutation callers can skip a second parse. A valid empty+ mapping (``{}``) is allowed through so first-time installs and+ intentional empty configs still work. On parse failure this also+ snapshots a ``.corrupt.*.bak`` via :func:`_warn_config_parse_failure`+ before raising.+ """if config_path is None:config_path = get_config_path()try:config_path.stat()except FileNotFoundError:- return+ return {}except OSError as exc:raise RuntimeError(f"Refusing to overwrite {config_path}: existing config.yaml cannot be accessed "@@ -3431,6 +3450,47 @@ def require_readable_config_before_write(config_path: Optional[Path] = None) ->f"({exc}). Fix the file permissions or move it aside first.") from exc+ return _load_user_config_for_mutation(config_path)+++def _load_user_config_for_mutation(config_path: Path) -> Dict[str, Any]:+ """Load raw user config for a fail-closed mutation path.++ Fail closed on parse / non-mapping (no bare-except to ``{}`` collapse).+ Used by :func:`require_readable_config_before_write` and any caller that+ must re-validate after other work. Distinct from+ :func:`read_user_config_raw`, which collapses non-dict roots to ``{}``.+ """+ if not config_path.exists():+ return {}+ try:+ with open(config_path, encoding="utf-8") as f:+ loaded = fast_safe_load(f)+ except OSError as exc:+ raise RuntimeError(+ f"Refusing to overwrite {config_path}: existing config.yaml cannot be read "+ f"({exc}). Fix the file permissions or move it aside first."+ ) from exc+ except Exception as exc:+ _warn_config_parse_failure(config_path, exc, fallback="refuse-write")+ raise RuntimeError(+ f"Refusing to overwrite {config_path}: existing config.yaml is not valid YAML "+ f"({exc}). Fix the file or restore from a .corrupt.*.bak backup first."+ ) from exc+ if loaded is None:+ return {}+ if not isinstance(loaded, dict):+ exc = TypeError(+ f"top-level YAML must be a mapping, got {type(loaded).__name__}"+ )+ _warn_config_parse_failure(config_path, exc, fallback="refuse-write")+ raise RuntimeError(+ f"Refusing to overwrite {config_path}: top-level YAML must be a mapping, "+ f"got {type(loaded).__name__}. Fix the file or restore from a "+ f".corrupt.*.bak backup first."+ ) from exc+ return loaded+def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None:"""Fail-closed atomic write for ``config.yaml``.@@ -3440,12 +3500,13 @@ def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None::func:`require_readable_config_before_write` first, so a full-filereplacement can never silently clobber an existing ``config.yaml`` thatdegraded to an empty dict on read (permission error, broken mount,- transient I/O). New-file creation still works when the path is absent.+ transient I/O, unparseable YAML, or a non-mapping root). New-file+ creation still works when the path is absent.- Root cause this guards: ``read_raw_config()`` returns ``{}`` for BOTH an- absent file and an unreadable-but-present file. Callers that read then- overwrite can't tell the two apart, so an unreadable config would be- replaced with only defaults or the single edited section. Routing every+ Root cause this guards: ``read_user_config_raw()`` returns ``{}`` for an+ absent file / unreadable path edge cases and collapses non-dict roots.+ Callers that read then overwrite can't tell these apart, so a broken+ config would be replaced with only defaults or the single edited section. Routing everywrite through this helper enforces the invariant in one place rather thanrelying on each of ~15 independent write sites to remember the guard.@@ -5528,21 +5589,9 @@ def set_config_value(key: str, value: str, force: bool = False):# Read the raw user config (not merged with defaults) to avoid# dumping all default values back to the fileconfig_path = get_config_path()- require_readable_config_before_write(config_path)- user_config = {}- if config_path.exists():- try:- with open(config_path, encoding="utf-8") as f:- user_config = fast_safe_load(f) or {}- except Exception as exc:- print(- f"✗ Cannot parse {config_path}: {exc}\n"- f" The file contains a YAML syntax error. Fix the error\n"- f" in your config file first, then retry.\n"- f" (hermes config edit will open it in your editor.)",- file=sys.stderr,- )- sys.exit(1)+ # Fail-closed parse via require_readable (unparseable / non-mapping+ # refuse-write); returns the mapping so we do not re-parse / collapse.+ user_config = require_readable_config_before_write(config_path)# Handle nested keys (e.g., "tts.provider") including numeric list# indices (e.g., "custom_providers.0.api_key"). Delegates to@@ -5786,21 +5835,9 @@ def unset_config_value(key: str):returnconfig_path = get_config_path()- require_readable_config_before_write(config_path)- user_config = {}- if config_path.exists():- try:- with open(config_path, encoding="utf-8") as f:- user_config = fast_safe_load(f) or {}- except Exception as exc:- print(- f"✗ Cannot parse {config_path}: {exc}\n"- f" The file contains a YAML syntax error. Fix the error\n"- f" in your config file first, then retry.\n"- f" (hermes config edit will open it in your editor.)",- file=sys.stderr,- )- sys.exit(1)+ # Fail-closed parse via require_readable (unparseable / non-mapping+ # refuse-write); returns the mapping so we do not re-parse / collapse.+ user_config = require_readable_config_before_write(config_path)removed = _unset_nested(user_config, key)diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex 97dd40d6cfb..8478f454eb4 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -26,6 +26,7 @@ from hermes_cli.config import (save_env_value_secure,sanitize_env_file,set_config_value,+ unset_config_value,write_platform_config_field,_sanitize_env_lines,)@@ -246,6 +247,106 @@ class TestSaveAndLoadRoundtrip:++ def test_config_set_refuses_to_overwrite_unparseable_existing_config(self, tmp_path):+ """Unparseable YAML must not be replaced with a single-key document.++ Regression for the set/unset wipe class: a bare except around YAML+ load used to treat parse failure as {}, then atomic-write only the+ new key — destroying every prior override with no .corrupt backup.+ """+ config_path = tmp_path / "config.yaml"+ original = (+ "model:\n"+ " default: claude-opus\n"+ " provider: anthropic\n"+ "gateway:\n"+ " platforms:\n"+ " telegram:\n"+ " enabled: true\n"+ "broken: [unterminated\n"+ )+ config_path.write_text(original, encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(RuntimeError, match="not valid YAML"):+ set_config_value("model.default", "gpt-4o")++ assert config_path.read_text(encoding="utf-8") == original+ assert list(tmp_path.glob("config.yaml.corrupt.*.bak")), (+ "parse-failure path should snapshot a corrupt backup before refusing"+ )++ def test_config_unset_refuses_to_overwrite_unparseable_existing_config(self, tmp_path):+ """Unset must refuse the same way — env-sync paths used to write {}."""+ config_path = tmp_path / "config.yaml"+ original = "model:\n default: keep-me\nbroken: [unterminated\n"+ config_path.write_text(original, encoding="utf-8")+ (tmp_path / ".env").write_text("TERMINAL_TIMEOUT=30\n", encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(RuntimeError, match="not valid YAML"):+ unset_config_value("terminal.timeout")++ assert config_path.read_text(encoding="utf-8") == original+ assert (tmp_path / ".env").read_text(encoding="utf-8") == "TERMINAL_TIMEOUT=30\n"+ assert list(tmp_path.glob("config.yaml.corrupt.*.bak")), (+ "unset parse-failure path should snapshot a corrupt backup before refusing"+ )++ def test_config_set_refuses_non_mapping_root(self, tmp_path):+ """A list/scalar root parses without raising but would still wipe."""+ config_path = tmp_path / "config.yaml"+ original = "- just\n- a\n- list\n"+ config_path.write_text(original, encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(RuntimeError, match="must be a mapping"):+ set_config_value("model.default", "gpt-4o")++ assert config_path.read_text(encoding="utf-8") == original+ assert list(tmp_path.glob("config.yaml.corrupt.*.bak")), (+ "non-mapping root should snapshot a corrupt backup before refusing"+ )++ def test_config_unset_refuses_non_mapping_root(self, tmp_path):+ """Unset shares the same non-mapping refuse path as set."""+ config_path = tmp_path / "config.yaml"+ original = "- just\n- a\n- list\n"+ config_path.write_text(original, encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ with pytest.raises(RuntimeError, match="must be a mapping"):+ unset_config_value("model.default")++ assert config_path.read_text(encoding="utf-8") == original+ assert list(tmp_path.glob("config.yaml.corrupt.*.bak"))++ def test_config_set_allows_valid_empty_mapping(self, tmp_path):+ """A genuine empty {} config must still be writable (not a false refuse)."""+ config_path = tmp_path / "config.yaml"+ config_path.write_text("{}\n", encoding="utf-8")++ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ set_config_value("model.default", "gpt-4o")++ saved = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert saved == {"model": {"default": "gpt-4o"}}++ def test_atomic_config_write_refuses_unparseable_existing_config(self, tmp_path):+ """Shared chokepoint must refuse unparseable YAML, not only unreadable."""+ from hermes_cli.config import atomic_config_write++ config_path = tmp_path / "config.yaml"+ original = "broken: [unterminated\n"+ config_path.write_text(original, encoding="utf-8")++ with pytest.raises(RuntimeError, match="not valid YAML"):+ atomic_config_write(config_path, {"model": {"provider": "openai"}})++ assert config_path.read_text(encoding="utf-8") == original+ assert list(tmp_path.glob("config.yaml.corrupt.*.bak"))+class TestSaveEnvValueSecure:def test_secure_save_returns_metadata_only(self, tmp_path):