The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): a transient read error no longer wipes config.yaml
teknium1db2f07c5cfdc
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 84e6b72e7b5..2dd779042ca 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -92,6 +92,16 @@ def _nested_dict(root: dict, *keys: str) -> dict:return root+def _write_raw_config_leaf(config_path: Path, keys: tuple, value) -> None:+ """Set one leaf through a strict raw round-trip. The behavioral read is fail-open (``{}``) and+ expanded, so writing it back wipes the file after a read error and persists ``${VAR}`` values."""+ from hermes_cli.config import read_user_config_raw+ raw = read_user_config_raw(config_path)+ *parents, leaf = keys+ _nested_dict(raw, *parents)[leaf] = value+ atomic_config_write(config_path, raw)++def _preview(text: str, limit: int = 60) -> str:return text[:limit] + ("..." if len(text) > limit else "")@@ -969,8 +979,7 @@ class GatewaySlashCommandsMixin(new_mode = cycle[(cycle.index(current if current in cycle else "all") + 1) % len(cycle)]description = t(f"gateway.verbose.mode_{new_mode}")try:- _nested_dict(user_config, "display", "platforms", platform_key)["tool_progress"] = new_mode- atomic_config_write(config_path, user_config)+ _write_raw_config_leaf(config_path, ("display", "platforms", platform_key, "tool_progress"), new_mode)return f"{description}\n" + t("gateway.verbose.saved_suffix", platform=platform_key)except Exception as e:logger.warning("Failed to save tool_progress mode: %s", e)@@ -1037,8 +1046,7 @@ class GatewaySlashCommandsMixin(return t("gateway.footer.usage")new_state = _FOOTER_STATE_BY_ARG[arg] if arg else not effective["enabled"]try:- _nested_dict(user_config, "display", "runtime_footer")["enabled"] = new_state- atomic_config_write(config_path, user_config)+ _write_raw_config_leaf(config_path, ("display", "runtime_footer", "enabled"), new_state)except Exception as e:logger.warning("Failed to save runtime_footer.enabled: %s", e)return t("gateway.config_save_failed", error=e)diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 36a4415e19e..f9b4b965947 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -1991,12 +1991,13 @@ def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:passwith _CONFIG_LOCK:+ config_path = get_config_path()try:- config_path = get_config_path()- st = config_path.stat()- cache_key = file_signature(st)- except (FileNotFoundError, OSError):+ cache_key = file_signature(config_path.stat())+ except FileNotFoundError:return {}+ except OSError as e:+ return FailedConfigRead(error=e)path_key = str(config_path)hit = _raw_config_cache_hit(path_key, cache_key)@@ -2008,10 +2009,10 @@ def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:data = fast_safe_load(f) or {}except Exception as e:_warn_config_parse_failure(config_path, e)- return {}+ return FailedConfigRead(error=e)if not isinstance(data, dict):- data = {}+ return FailedConfigRead(error=TypeError(f"top-level YAML must be a mapping, got {type(data).__name__}"))# The cache stores its own deepcopy. The readonly path returns THAT object (identity# invariant: later cache hits return the same dict); the mutable path returns the parse.cached_copy = copy.deepcopy(data)@@ -2046,6 +2047,25 @@ 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)@@ -2109,6 +2129,7 @@ def atomic_config_write(config_path: Path, data: Dict[str, Any], *, extra_contenpath anywhere else is rejected by ``scripts/check_config_yaml_writers.py`` (#92554)."""from utils import atomic_roundtrip_yaml_save+ _refuse_failed_read(config_path, data)atomic_roundtrip_yaml_save(config_path, data, extra_content_on_create=extra_content_on_create)@@ -2286,10 +2307,11 @@ def _last_known_good_fallback(config_path: Path, path_key: str, cache_sig, exc:return None# save_config() stores the pre-expansion dict (templates preserved); the load path stores the# expanded one. Expand defensively — idempotent when already expanded.- lkg_copy: Dict[str, Any] = _expand_env_vars(copy.deepcopy(lkg))- if cache_sig is not None:+ lkg_copy = FailedConfigRead(_expand_env_vars(copy.deepcopy(lkg)), error=exc)+ if cache_sig is not None and not isinstance(exc, OSError):# Cache under the corrupt file's signature (empty env snapshot: always valid) so repeated- # loads don't re-parse; fixing the file changes the signature and reloads normally.+ # loads don't re-parse; fixing the file changes the signature and reloads normally. A read+ # error leaves an intact file behind, so the next load must retry it._LOAD_CONFIG_CACHE[path_key] = (*cache_sig, lkg_copy, {})return lkg_copy@@ -2380,6 +2402,13 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:lkg_copy = _last_known_good_fallback(config_path, path_key, cache_sig, e)if lkg_copy is not None:return copy.deepcopy(lkg_copy) if want_deepcopy else lkg_copy+ # Defaults stand in for the unreadable file: never the next last-known-good,+ # never saveable, and (like the LKG path) cached only for a parse error.+ fallback = FailedConfigRead(+ _merge_managed_overlay(_expand_env_vars(_canonicalize_config(config)))[0], error=e)+ if cache_sig is not None and not isinstance(e, OSError):+ _LOAD_CONFIG_CACHE[path_key] = (*cache_sig, fallback, {})+ return copy.deepcopy(fallback) if want_deepcopy else fallbacknormalized = _canonicalize_config(config)expanded, managed_config = _merge_managed_overlay(_expand_env_vars(normalized))@@ -2484,10 +2513,11 @@ def save_config(managed_error("save configuration")return+ config_path = get_config_path()+ _refuse_failed_read(config_path, config)config = _strip_managed_keys_for_save(config)ensure_hermes_home()- config_path = get_config_path()# Explicit user paths come from the RAW dict BEFORE normalisation (which may inject# agent.max_turns) so _strip_default_values keeps exactly what the user set. The# fail-closed read is the single authority here: ``read_raw_config()`` is cached anddiff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex 1caefef8c43..606495eca3f 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -21,7 +21,7 @@ from hermes_cli.web_server_profiles import (_approval_mode_of, _broadcast_gateway_session_info, _is_other_profile, _parse_model_entries,)from fastapi import HTTPException, Request-from hermes_cli.config import DEFAULT_CONFIG, OPTIONAL_ENV_VARS, read_raw_config, custom_endpoint_key_env, coerce_provider_id, find_provider_entry, get_compatible_custom_providers, redact_key, _deep_merge+from hermes_cli.config import DEFAULT_CONFIG, OPTIONAL_ENV_VARS, read_raw_config, require_readable_config_before_write, custom_endpoint_key_env, coerce_provider_id, find_provider_entry, get_compatible_custom_providers, redact_key, _deep_mergefrom hermes_cli.config_providers import _canonical_api_mode, _custom_provider_entry_to_provider_configfrom hermes_cli.web_models import ConfigUpdate, EnvVarUpdate, EnvVarDelete, EnvVarReveal, CustomEndpointUpdatefrom typing import Any, Dict, List, Optional, Tuple@@ -124,7 +124,9 @@ async def update_config(# in the PUT body, so deep-merge incoming over disk rather than# full-replace — the frontend can only overwrite what it sends.with _CONFIG_MUTATION_LOCK:- existing = read_raw_config()+ # Strict read: the merge below builds a new dict, so a swallowed read error here+ # would save the PUT body alone over the whole file.+ existing = require_readable_config_before_write()incoming = _denormalize_config_from_web(body.config)merged = _deep_merge(existing, incoming)# Compare normalized approvals.mode across the in-memorydiff --git a/tests/hermes_cli/test_config_save_integrity.py b/tests/hermes_cli/test_config_save_integrity.pyindex 25427197a48..27363e87889 100644--- a/tests/hermes_cli/test_config_save_integrity.py+++ b/tests/hermes_cli/test_config_save_integrity.py@@ -1,9 +1,132 @@-"""config.yaml write integrity: a save keeps what the user wrote."""+"""config.yaml write integrity: a failed read never reaches disk, and a save keeps what the user wrote."""++import errno+import os+import shutilimport pytestimport yaml-from hermes_cli.config import DEFAULT_CONFIG, load_config, migrate_config, save_config+import hermes_cli.config as config_mod+from hermes_cli.config import DEFAULT_CONFIG, load_config, migrate_config, read_raw_config, save_config++_CONFIG = """# hand-tuned+model:+ default: my-org/custom-model+display:+ skin: mono+terminal:+ backend: docker+approvals:+ deny:+ - rm -rf /+"""+++def home(tmp_path, monkeypatch):+ from tui_gateway import server+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(server, "_hermes_home", tmp_path)+ server._cfg_cache = server._cfg_sig = server._cfg_path = None+ (tmp_path / "config.yaml").write_text(_CONFIG, encoding="utf-8")+ yield tmp_path+ server._cfg_cache = server._cfg_sig = server._cfg_path = None+++class _ReadFaults:+ """Counts parses of config.yaml and fails the chosen one with a transient EMFILE (intact file)."""++ def __init__(self, monkeypatch, path):+ self.path, self.count, self.fail_at, real = str(path), 0, 0, config_mod.fast_safe_load++ def flaky(stream):+ if getattr(stream, "name", None) == self.path:+ self.count += 1+ if self.count == self.fail_at:+ raise OSError(errno.EMFILE, "Too many open files")+ return real(stream)+ monkeypatch.setattr(config_mod, "fast_safe_load", flaky)++ def arm(self, fail_at=0):+ self.count, self.fail_at = 0, fail_at+++def _fresh_process(home, text, *, keep_last_known_good=False):+ """*text* on a new inode with cold caches (and no last-known-good copy unless asked)."""+ from tui_gateway import server+ config_mod._LOAD_CONFIG_CACHE.clear()+ config_mod._RAW_CONFIG_CACHE.clear()+ server._cfg_cache = server._cfg_sig = server._cfg_path = None+ if not keep_last_known_good:+ config_mod._LAST_EXPANDED_CONFIG_BY_PATH.clear()+ shutil.rmtree(home / "backups", ignore_errors=True)+ tmp = home / ".config.yaml.new"+ tmp.write_text(text, encoding="utf-8")+ os.replace(tmp, home / "config.yaml")+++def _save_loaded():+ cfg = load_config()+ cfg["display"]["skin"] = "ares"+ save_config(cfg)+++def _save_raw(): # the shape every migration step and ``write_platform_config_field(raw=True)`` use+ cfg = read_raw_config()+ cfg.setdefault("display", {})["skin"] = "ares"+ save_config(cfg)+++def _tui_config_set():+ from tui_gateway import server+ reply = server._methods["config.set"](1, {"key": "skin", "value": "ares"})+ if "error" in reply:+ raise RuntimeError(reply["error"]["message"])+++def _dashboard_put():+ from starlette.testclient import TestClient+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app+ client = TestClient(app, raise_server_exceptions=False)+ r = client.put("/api/config", json={"config": {"display": {"skin": "ares"}}},+ headers={_SESSION_HEADER_NAME: _SESSION_TOKEN})+ if r.status_code != 200:+ raise RuntimeError(r.text)++[email protected]("last_known_good", ["none", "stale"])[email protected]("write", [_save_loaded, _save_raw, _tui_config_set, _dashboard_put],+ ids=["load_config", "read_raw_config", "tui-config.set", "dashboard-put"])+def test_no_single_transient_read_error_reaches_the_file(write, last_known_good, home, monkeypatch):+ """Fail each config read the write performs, one at a time: the write either lands exactly as+ it would have, or is refused with the file byte-identical, and the retry is not poisoned."""+ path = home / "config.yaml"+ before = _CONFIG + "timezone: Europe/Paris\n"+ faults = _ReadFaults(monkeypatch, path)++ def run(k):+ _fresh_process(home, before)+ if last_known_good == "stale": # loaded earlier in this process, edited elsewhere since+ _fresh_process(home, _CONFIG)+ load_config()+ _fresh_process(home, before, keep_last_known_good=True)+ faults.arm(k)+ try:+ write()+ except RuntimeError:+ return "refused"+ return "ok"++ assert run(0) == "ok"+ good_after, reads = path.read_bytes(), faults.count+ assert b"skin: ares" in good_after and reads >= 1+ for k in range(1, reads + 1):+ if run(k) == "refused":+ assert path.read_text(encoding="utf-8") == before, f"read {k}/{reads} failed, file changed"+ faults.arm()+ write() # the retry is not poisoned by a cached fallback+ assert path.read_bytes() == good_after, f"read {k}/{reads} failed, the saved file differs"@pytest.mark.parametrize("operation", ["save", "partial_save", "migrate"])diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex a716d0030a7..3b82fcab611 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1222,18 +1222,19 @@ 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- with contextlib.suppress(Exception):+ from hermes_cli.config import FailedConfigRead, read_user_config_raw+ try:p = _active_config_path()sig = file_signature(p.stat()) if p.exists() else Nonewith _cfg_lock:if _cfg_cache is not None and _cfg_sig == sig and _cfg_path == p:return copy.deepcopy(_cfg_cache)- from hermes_cli.config import read_user_config_rawdata = read_user_config_raw(p) if p.exists() else {}- with _cfg_lock: # cache the RAW config: _save_cfg writes _cfg_cache back to disk- _cfg_cache, _cfg_sig, _cfg_path = copy.deepcopy(data), sig, p- return data- return {}+ except Exception as exc:+ return FailedConfigRead(error=exc) # readable as {}, refused by _save_cfg+ with _cfg_lock: # cache the RAW config: _save_cfg writes _cfg_cache back to disk+ _cfg_cache, _cfg_sig, _cfg_path = copy.deepcopy(data), sig, p+ return datadef _load_cfg() -> dict: