The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(config): move read-failure reporting into hermes_cli/config_read_errors.py
teknium1327dc2a72127
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 3473e436496..ee50be10c43 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -1279,7 +1279,7 @@ def _refuse_env_adoption_if_config_corrupt() -> None:silently adopt the PAID openrouter provider over whatever the broken config really names.Fires ONLY on the auto path and clears itself once the file parses again."""try:- from hermes_cli.config import get_active_config_parse_failure+ from hermes_cli.config_read_errors import get_active_config_parse_failureerr = get_active_config_parse_failure()if not err:returndiff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex a4ba470ed05..a7a6cf8b5b5 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -47,104 +47,17 @@ from hermes_constants import ( # noqa: F401# Re-export from hermes_constants — canonical definition lives there.from hermes_constants import get_hermes_home, get_process_hermes_home # noqa: F401from utils import atomic_replace, fast_safe_load, file_signature+from hermes_cli.config_read_errors import (+ _CONFIG_PARSE_FAILURES, _FIX_PERMS, _FIX_YAML, FailedConfigRead, _backups_dir_display,+ _refuse_failed_read, _refuse_overwrite, _warn_config_parse_failure, _yaml_error_details,+ _yaml_error_location)logger = logging.getLogger(__name__)-# (config_path, mtime_ns, size) tuples already warned about, so concurrent CLI/gateway-# loads of a broken config.yaml don't spam stderr. A changed file (new mtime) warns again.-_CONFIG_PARSE_WARNED: set = set()--# path -> (mtime_ns, size, error message) of active parse failures. Written by-# _warn_config_parse_failure() (the single funnel for every load-path parse failure) and-# probed by get_active_config_parse_failure() so provider auto-resolution can refuse to-# adopt a paid provider from env keys while the user's REAL config is unreadable.-_CONFIG_PARSE_FAILURES: dict = {}--class InvalidUserConfigError(RuntimeError):"""Raised when a run that cannot repair config finds invalid user YAML."""-_PARSE_FAILURE_FALLBACK_MSG = {- "last-known-good": "Hermes is running on the settings it loaded before the edit until it is fixed, so recent changes are not applied.",- "last-known-good-backup": "Hermes is running on your last good settings until it is fixed, so recent changes are not applied.",- "refuse-write": "Nothing was written, so the existing file is preserved."}-_PARSE_FAILURE_DEFAULTS_MSG = (- "Hermes is running on default settings until it is fixed, so none of your saved settings are applied.")-_PARSE_FAILURE_REPAIR_MSG = "Open it with `hermes config edit`, fix {where}, then run `hermes config check`."---def _yaml_error_location(exc: Exception) -> str:- """``"line 12"`` from a PyYAML problem mark (1-based), else ``""``."""- mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)- line = getattr(mark, "line", None)- return f"line {line + 1}" if isinstance(line, int) else ""---def _yaml_error_details(exc: Exception) -> str:- """Single-line ``Details:`` text: the PyYAML problem, or the exception's first line."""- problem = getattr(exc, "problem", None)- text = f"{problem}" if problem else str(exc).strip()- return " ".join(text.split())---def format_config_parse_failure(config_path: Path, exc: Exception, *, fallback: str = "defaults") -> str:- """User copy for an unparseable config.yaml: what happened, what Hermes is doing, how to fix.- Only the problem line/column is printed; the raw PyYAML text goes to a ``Details:`` line."""- where = _yaml_error_location(exc)- at = f" at {where}" if where else ""- fallback_msg = _PARSE_FAILURE_FALLBACK_MSG.get(fallback, _PARSE_FAILURE_DEFAULTS_MSG)- if isinstance(exc, OSError): # the file is intact; EMFILE/EIO/sharing violation, not a YAML problem- return (f"Your settings file ({config_path}) could not be read. {fallback_msg} "- "Try again; run `hermes config check` if it keeps failing.")- repair = _PARSE_FAILURE_REPAIR_MSG.format(where=where or "the problem")- return f"Your settings file ({config_path}) has a formatting error{at}. {fallback_msg} {repair}"---def _warn_config_parse_failure(- config_path: Path, exc: Exception, *, fallback: str = "defaults") -> None:- """Surface a config.yaml parse failure to log and stderr (once per file signature).- Silent fallback to ``DEFAULT_CONFIG`` drops every user override, so this must be loud.-- ``fallback`` selects the message wording: ``"defaults"`` (fresh process, nothing else to serve) or- ``"last-known-good"`` (in-process retention of the previously loaded config — see the codex#31188 port- in ``_load_config_impl``).- """- try:- st = config_path.stat()- sig = file_signature(st)- key = (str(config_path), *sig)- _CONFIG_PARSE_FAILURES[str(config_path)] = (*sig, str(exc))- except OSError:- key = (str(config_path), 0, 0, 0, 0)- if key in _CONFIG_PARSE_WARNED:- return- _CONFIG_PARSE_WARNED.add(key)- from hermes_cli.config_backups import backup_config- # A read error leaves an intact file behind: no "corrupt" copy of a good file.- backup_path = None if isinstance(exc, OSError) else backup_config(config_path, "corrupt")- msg = format_config_parse_failure(config_path, exc, fallback=fallback)- if backup_path is not None:- msg += f" A copy of the broken file was saved to {backup_path}."- logger.warning("%s Details: %s", msg, _yaml_error_details(exc))- try:- sys.stderr.write(f"⚠️ hermes config: {msg}\n Details: {_yaml_error_details(exc)}\n")- sys.stderr.flush()- except Exception:- pass---def get_active_config_parse_failure() -> Optional[str]:- """Return the recorded parse error while the ACTIVE config.yaml is still byte-identical- (mtime_ns + size + ino + ctime_ns) to the file that failed to parse; else None."""- try:- record = _CONFIG_PARSE_FAILURES[str(path := get_config_path())]- st = path.stat()- return record[4] if file_signature(st) == record[:4] else None- except Exception:- return None--_IS_WINDOWS = platform.system() == "Windows"_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")@@ -2052,45 +1965,6 @@ def read_raw_config_readonly() -> Dict[str, Any]:return _read_raw_config_impl(want_deepcopy=False)-class FailedConfigRead(dict):- """The fail-open fallback a config reader serves when an existing config.yaml could not be read- or parsed (``{}``, defaults or last-known-good). Readers use it like any dict; ``save_config`` /- ``atomic_config_write`` refuse to persist it. The writer merges by deletion, so saving a fallback- after one transient EMFILE/EIO replaced the whole file with the fallback plus the caller's edit.- A dict subclass so the refusal survives the load→mutate→save round trip at every call site."""-- def __init__(self, data: Any = (), *, error: Exception):- super().__init__(data)- self.read_error = error---def _refuse_failed_read(config_path: Path, data: Any) -> None:- if isinstance(data, FailedConfigRead):- raise _refuse_overwrite(- config_path, "could not be read", data.read_error,- "Try again; run `hermes config check` if it keeps failing.")---def _refuse_overwrite(config_path: Path, reason: str, exc: Exception, fix: str) -> RuntimeError:- """Error for a write that must not replace an existing config.yaml. Plain lead + ``Details:``."""- where = _yaml_error_location(exc)- at = f" ({where})" if where else ""- return RuntimeError(- f"Your settings file ({config_path}) {reason}{at}, so this change was not saved. {fix} "- f"Details: {_yaml_error_details(exc)}")---def _backups_dir_display() -> str:- from hermes_constants import display_hermes_home- return f"{display_hermes_home()}/backups/config/"---_FIX_PERMS = "Fix the file permissions or move it aside first."-_FIX_YAML = (- "Fix it with `hermes config edit` and check with `hermes config check`, or copy the newest good "- "file from {backups} over config.yaml.")--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; return the mapping.Guards two collapse-to-empty failure modes that would let a read-then-write caller silentlydiff --git a/hermes_cli/config_effective.py b/hermes_cli/config_effective.pyindex 3f1ff8a433b..ac60bada118 100644--- a/hermes_cli/config_effective.py+++ b/hermes_cli/config_effective.py@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tuplefrom hermes_cli import config as _configfrom hermes_cli import managed_scope+from hermes_cli.config_read_errors import _warn_config_parse_failurefrom utils import fast_safe_load# path -> raw user mapping from the last successful parse in this process; served (through the@@ -44,7 +45,7 @@ def _recover_user_raw(config_path: Path, path_key: str, exc: Exception) -> Dict[from hermes_cli.config_backups import load_newest_good_backupraw = load_newest_good_backup(config_path)fallback = "last-known-good-backup"- _config._warn_config_parse_failure(config_path, exc, fallback=fallback if raw is not None else "defaults")+ _warn_config_parse_failure(config_path, exc, fallback=fallback if raw is not None else "defaults")return copy.deepcopy(raw) if raw is not None else {}diff --git a/hermes_cli/config_read_errors.py b/hermes_cli/config_read_errors.pynew file mode 100644index 00000000000..1c40661777c--- /dev/null+++ b/hermes_cli/config_read_errors.py@@ -0,0 +1,147 @@+"""What Hermes does when an existing ``config.yaml`` cannot be read or parsed.++Readers fail open (``{}`` / defaults / last-known-good) so a broken file never takes the process+down; this module makes that fallback loud (one warning per file signature, a ``corrupt`` backup),+remembers the failure for :func:`get_active_config_parse_failure`, and marks every fallback as a+:class:`FailedConfigRead` so the writers refuse to persist it.+"""++from __future__ import annotations++import logging+import sys+from pathlib import Path+from typing import Any, Optional++from utils import file_signature++logger = logging.getLogger(__name__)++# (config_path, mtime_ns, size) tuples already warned about, so concurrent CLI/gateway+# loads of a broken config.yaml don't spam stderr. A changed file (new mtime) warns again.+_CONFIG_PARSE_WARNED: set = set()++# path -> (mtime_ns, size, error message) of active parse failures. Written by+# _warn_config_parse_failure() (the single funnel for every load-path parse failure) and+# probed by get_active_config_parse_failure() so provider auto-resolution can refuse to+# adopt a paid provider from env keys while the user's REAL config is unreadable.+_CONFIG_PARSE_FAILURES: dict = {}++_PARSE_FAILURE_FALLBACK_MSG = {+ "last-known-good": "Hermes is running on the settings it loaded before the edit until it is fixed, so recent changes are not applied.",+ "last-known-good-backup": "Hermes is running on your last good settings until it is fixed, so recent changes are not applied.",+ "refuse-write": "Nothing was written, so the existing file is preserved."}+_PARSE_FAILURE_DEFAULTS_MSG = (+ "Hermes is running on default settings until it is fixed, so none of your saved settings are applied.")+_PARSE_FAILURE_REPAIR_MSG = "Open it with `hermes config edit`, fix {where}, then run `hermes config check`."+++def _yaml_error_location(exc: Exception) -> str:+ """``"line 12"`` from a PyYAML problem mark (1-based), else ``""``."""+ mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)+ line = getattr(mark, "line", None)+ return f"line {line + 1}" if isinstance(line, int) else ""+++def _yaml_error_details(exc: Exception) -> str:+ """Single-line ``Details:`` text: the PyYAML problem, or the exception's first line."""+ problem = getattr(exc, "problem", None)+ text = f"{problem}" if problem else str(exc).strip()+ return " ".join(text.split())+++def format_config_parse_failure(config_path: Path, exc: Exception, *, fallback: str = "defaults") -> str:+ """User copy for an unparseable config.yaml: what happened, what Hermes is doing, how to fix.+ Only the problem line/column is printed; the raw PyYAML text goes to a ``Details:`` line."""+ where = _yaml_error_location(exc)+ at = f" at {where}" if where else ""+ fallback_msg = _PARSE_FAILURE_FALLBACK_MSG.get(fallback, _PARSE_FAILURE_DEFAULTS_MSG)+ if isinstance(exc, OSError): # the file is intact; EMFILE/EIO/sharing violation, not a YAML problem+ return (f"Your settings file ({config_path}) could not be read. {fallback_msg} "+ "Try again; run `hermes config check` if it keeps failing.")+ repair = _PARSE_FAILURE_REPAIR_MSG.format(where=where or "the problem")+ return f"Your settings file ({config_path}) has a formatting error{at}. {fallback_msg} {repair}"+++def _warn_config_parse_failure(+ config_path: Path, exc: Exception, *, fallback: str = "defaults") -> None:+ """Surface a config.yaml parse failure to log and stderr (once per file signature).+ Silent fallback to ``DEFAULT_CONFIG`` drops every user override, so this must be loud.++ ``fallback`` selects the message wording: ``"defaults"`` (fresh process, nothing else to serve) or+ ``"last-known-good"`` (in-process retention of the previously loaded config — see the codex#31188 port+ in ``hermes_cli.config._load_config_impl``).+ """+ try:+ st = config_path.stat()+ sig = file_signature(st)+ key = (str(config_path), *sig)+ _CONFIG_PARSE_FAILURES[str(config_path)] = (*sig, str(exc))+ except OSError:+ key = (str(config_path), 0, 0, 0, 0)+ if key in _CONFIG_PARSE_WARNED:+ return+ _CONFIG_PARSE_WARNED.add(key)+ from hermes_cli.config_backups import backup_config+ # A read error leaves an intact file behind: no "corrupt" copy of a good file.+ backup_path = None if isinstance(exc, OSError) else backup_config(config_path, "corrupt")+ msg = format_config_parse_failure(config_path, exc, fallback=fallback)+ if backup_path is not None:+ msg += f" A copy of the broken file was saved to {backup_path}."+ logger.warning("%s Details: %s", msg, _yaml_error_details(exc))+ try:+ sys.stderr.write(f"⚠️ hermes config: {msg}\n Details: {_yaml_error_details(exc)}\n")+ sys.stderr.flush()+ except Exception:+ pass+++def get_active_config_parse_failure() -> Optional[str]:+ """Return the recorded parse error while the ACTIVE config.yaml is still byte-identical+ (mtime_ns + size + ino + ctime_ns) to the file that failed to parse; else None."""+ from hermes_cli.config import get_config_path+ try:+ record = _CONFIG_PARSE_FAILURES[str(path := get_config_path())]+ st = path.stat()+ return record[4] if file_signature(st) == record[:4] else None+ except Exception:+ return None+++class FailedConfigRead(dict):+ """The fail-open fallback a config reader serves when an existing config.yaml could not be read+ or parsed (``{}``, defaults or last-known-good). Readers use it like any dict; ``save_config`` /+ ``atomic_config_write`` refuse to persist it. The writer merges by deletion, so saving a fallback+ after one transient EMFILE/EIO replaced the whole file with the fallback plus the caller's edit.+ A dict subclass so the refusal survives the load→mutate→save round trip at every call site."""++ def __init__(self, data: Any = (), *, error: Exception):+ super().__init__(data)+ self.read_error = error+++def _refuse_failed_read(config_path: Path, data: Any) -> None:+ if isinstance(data, FailedConfigRead):+ raise _refuse_overwrite(+ config_path, "could not be read", data.read_error,+ "Try again; run `hermes config check` if it keeps failing.")+++def _refuse_overwrite(config_path: Path, reason: str, exc: Exception, fix: str) -> RuntimeError:+ """Error for a write that must not replace an existing config.yaml. Plain lead + ``Details:``."""+ where = _yaml_error_location(exc)+ at = f" ({where})" if where else ""+ return RuntimeError(+ f"Your settings file ({config_path}) {reason}{at}, so this change was not saved. {fix} "+ f"Details: {_yaml_error_details(exc)}")+++def _backups_dir_display() -> str:+ from hermes_constants import display_hermes_home+ return f"{display_hermes_home()}/backups/config/"+++_FIX_PERMS = "Fix the file permissions or move it aside first."+_FIX_YAML = (+ "Fix it with `hermes config edit` and check with `hermes config check`, or copy the newest good "+ "file from {backups} over config.yaml.")diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex a8616fefc84..601bb58296b 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -167,8 +167,8 @@ class TestLoadConfigParseFailure:Ported from google-gemini/gemini-cli#21541 (policy-file TOML recovery),adapted: we back up but deliberately do NOT reset config.yaml."""- from hermes_cli import config as cfg_mod- cfg_mod._CONFIG_PARSE_WARNED.clear()+ from hermes_cli.config_read_errors import _CONFIG_PARSE_WARNED+ _CONFIG_PARSE_WARNED.clear()with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):broken = "\tmodel: test/custom\nbroken indent:\n"@@ -200,8 +200,8 @@ class TestLoadConfigParseFailure:parses again."""import time- from hermes_cli import config as cfg_mod- cfg_mod._CONFIG_PARSE_WARNED.clear()+ from hermes_cli.config_read_errors import _CONFIG_PARSE_WARNED+ _CONFIG_PARSE_WARNED.clear()with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):cfg = tmp_path / "config.yaml"diff --git a/tests/hermes_cli/test_config_save_integrity.py b/tests/hermes_cli/test_config_save_integrity.pyindex 0266e6a7ce5..c59f5af3e94 100644--- a/tests/hermes_cli/test_config_save_integrity.py+++ b/tests/hermes_cli/test_config_save_integrity.py@@ -135,10 +135,10 @@ def test_transient_read_error_is_not_recorded_as_a_corrupt_config(read, home, moprovider auto-resolution refusal (`corrupt_config`) keyed on the file signature would otherwisefire until the file is next edited, and the good file would be copied away as `.corrupt`."""from hermes_cli.auth import _refuse_env_adoption_if_config_corrupt- from hermes_cli.config import get_active_config_parse_failure+ from hermes_cli.config_read_errors import _CONFIG_PARSE_WARNED, get_active_config_parse_failurepath = home / "config.yaml"_fresh_process(home, _CONFIG)- config_mod._CONFIG_PARSE_WARNED.clear()+ _CONFIG_PARSE_WARNED.clear()faults = _ReadFaults(monkeypatch, path)faults.arm(1)diff --git a/tests/hermes_cli/test_resolve_provider_corrupt_config.py b/tests/hermes_cli/test_resolve_provider_corrupt_config.pyindex c0a6841f6bf..a5cdb4ebd84 100644--- a/tests/hermes_cli/test_resolve_provider_corrupt_config.py+++ b/tests/hermes_cli/test_resolve_provider_corrupt_config.py@@ -59,7 +59,7 @@ class TestParseFailureProbe:_home, _cfg = _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)_load_config_fresh()- from hermes_cli.config import get_active_config_parse_failure+ from hermes_cli.config_read_errors import get_active_config_parse_failureerr = get_active_config_parse_failure()assert err, "expected an active parse failure to be reported"@@ -68,7 +68,7 @@ class TestParseFailureProbe:_home, cfg = _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)_load_config_fresh()- from hermes_cli.config import get_active_config_parse_failure+ from hermes_cli.config_read_errors import get_active_config_parse_failureassert get_active_config_parse_failure()cfg.write_text(VALID_YAML) # user fixes the YAML — different size/mtime@@ -78,7 +78,7 @@ class TestParseFailureProbe:_setup_home(tmp_path, monkeypatch, VALID_YAML)_load_config_fresh()- from hermes_cli.config import get_active_config_parse_failure+ from hermes_cli.config_read_errors import get_active_config_parse_failureassert get_active_config_parse_failure() is Nonediff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 3b82fcab611..01b75f91448 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1222,7 +1222,8 @@ def _load_cfg_raw() -> dict:expansion applied here would be persisted on the next save). Behavioral reads use :func:`_load_cfg`.Cache keyed on the resolved path so profiles don't clobber."""global _cfg_cache, _cfg_sig, _cfg_path- from hermes_cli.config import FailedConfigRead, read_user_config_raw+ from hermes_cli.config import read_user_config_raw+ from hermes_cli.config_read_errors import FailedConfigReadtry:p = _active_config_path()sig = file_signature(p.stat()) if p.exists() else None