The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): a fresh process recovers the last good config.yaml instead of running on defaults
teknium1de2d6a1b9350
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 05615a9b27c..4669b49e8e0 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -53,6 +53,9 @@ _PARSE_FAILURE_FALLBACK_MSG = {"last-known-good": ("Keeping the previously loaded config for this process — ""edits to config.yaml are being IGNORED until the YAML is fixed."),+ "last-known-good-backup": (+ "Loading the LAST KNOWN GOOD copy from backups/config/ instead — edits to config.yaml "+ "since that copy are being IGNORED until the YAML is fixed."),"refuse-write": ("REFUSING to write config.yaml so the existing file is preserved. ""Fix the YAML (hermes config edit) and retry.")}@@ -2128,8 +2131,21 @@ def _last_known_good_fallback(config_path: Path, path_key: str, cache_sig, exc:# process we still have the last successfully loaded config — keep serving it until the file is fixed.# See #31188.lkg = _LAST_EXPANDED_CONFIG_BY_PATH.get(path_key)+ fallback = "last-known-good"+ if lkg is None:+ # Fresh process (CLI restart, `hermes config get`): nothing loaded yet in this process, so+ # fall back to the newest byte-exact copy the last successful parse left in backups/config/.+ # It holds the raw file (``${VAR}`` templates intact), so it goes through the same+ # canonicalize -> expand -> managed-overlay pipeline as a normal load.+ from hermes_cli.config_backups import load_newest_good_backup+ raw_good = load_newest_good_backup(config_path)+ if raw_good is not None:+ normalized = _canonicalize_config(_deep_merge(copy.deepcopy(DEFAULT_CONFIG), raw_good))+ expanded_good: Dict[str, Any] = _expand_env_vars(normalized) # type: ignore[assignment]+ lkg, _ = _merge_managed_overlay(expanded_good)+ fallback = "last-known-good-backup"_warn_config_parse_failure(- config_path, exc, fallback="last-known-good" if lkg is not None else "defaults")+ config_path, exc, fallback=fallback if lkg is not None else "defaults")if lkg is None:return None# save_config() stores the pre-expansion dict (templates preserved); the load path stores the@@ -2194,6 +2210,11 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:user_config.pop("max_turns", None)config = _deep_merge(config, user_config)+ # A copy of the file that just parsed is what a FRESH process falls back to when the+ # next edit breaks the YAML (see _last_known_good_fallback). backup_config() skips+ # byte-identical repeats and keeps a bounded count, so steady-state loads cost one stat.+ from hermes_cli.config_backups import backup_config+ backup_config(config_path, "good")except Exception as e:lkg_copy = _last_known_good_fallback(config_path, path_key, cache_sig, e)if lkg_copy is not None:diff --git a/hermes_cli/config_backups.py b/hermes_cli/config_backups.pyindex ae12b31aa76..a20a466f457 100644--- a/hermes_cli/config_backups.py+++ b/hermes_cli/config_backups.py@@ -69,6 +69,26 @@ def backup_config(config_path: Path, reason: str, *, keep: int = DEFAULT_KEEP) -return None+def load_newest_good_backup(config_path: Path) -> Optional[dict]:+ """Parse the newest ``good`` backup (the file as it was at the last successful load).++ Returns the raw mapping, or None when there is no usable copy. Older ``good`` copies are not+ tried: a backup that fails to parse means the on-disk copy was damaged after the fact, and+ guessing further back would serve a config the user never saw as current.+ """+ newest = list_config_backups(config_path, "good")[:1]+ if not newest:+ return None+ try:+ from utils import fast_safe_load+ with newest[0].open(encoding="utf-8") as f:+ data = fast_safe_load(f)+ except Exception as exc:+ logger.warning("Last-known-good backup %s is unreadable: %s", newest[0], exc)+ return None+ return data if isinstance(data, dict) else None++def _sweep_legacy_siblings(config_path: Path, root: Path) -> None:for pattern in _LEGACY_SIBLING_GLOBS:for old in config_path.parent.glob(pattern):diff --git a/tests/hermes_cli/test_config_lkg_backup.py b/tests/hermes_cli/test_config_lkg_backup.pynew file mode 100644index 00000000000..f5f8af344be--- /dev/null+++ b/tests/hermes_cli/test_config_lkg_backup.py@@ -0,0 +1,60 @@+"""A fresh process recovers the last successfully parsed config.yaml when the file is broken.++The in-process last-known-good (#31188 port) only helps a long-running gateway. A CLI restart or+``hermes config get`` against broken YAML used to run on ``DEFAULT_CONFIG`` — dropping every+override, including ``approvals.deny`` (#102945). Successful loads now leave a ``good`` copy in+``backups/config/`` and the fallback reads it.+"""++import json+import os+import subprocess+import sys+from pathlib import Path++from hermes_cli.config_backups import list_config_backups++REPO = Path(__file__).resolve().parents[2]+GOOD = (+ "model:\n default: test/secure\n"+ "approvals:\n deny:\n - 'curl*evil*'\n"+ "custom_providers:\n - name: p\n base_url: https://x.invalid/v1\n api_key: ${LKG_TOKEN}\n"+)+BROKEN = "approvals:\n deny: [unclosed\n"+++def _fresh_load(home: Path) -> tuple[dict, str]:+ env = {**os.environ, "HERMES_HOME": str(home), "PYTHONPATH": str(REPO), "LKG_TOKEN": "expanded-secret"}+ proc = subprocess.run(+ [sys.executable, "-c", "import json; from hermes_cli.config import load_config; print(json.dumps(load_config()))"],+ cwd=REPO, env=env, text=True, capture_output=True, check=True, stdin=subprocess.DEVNULL,+ )+ return json.loads(proc.stdout), proc.stderr+++def test_fresh_process_recovers_last_good_config_and_leaves_broken_file_alone(tmp_path):+ config_path = tmp_path / "config.yaml"+ config_path.write_text(GOOD, encoding="utf-8")+ first, _ = _fresh_load(tmp_path)+ assert first["approvals"]["deny"] == ["curl*evil*"]++ config_path.write_text(BROKEN, encoding="utf-8")+ recovered, stderr = _fresh_load(tmp_path)++ assert recovered["approvals"]["deny"] == ["curl*evil*"]+ assert recovered["model"]["default"] == "test/secure"+ assert recovered["custom_providers"][0]["api_key"] == "expanded-secret"+ assert "LAST KNOWN GOOD" in stderr+ assert config_path.read_text(encoding="utf-8") == BROKEN+++def test_good_backup_keeps_env_templates_and_dedupes_repeat_loads(tmp_path):+ config_path = tmp_path / "config.yaml"+ config_path.write_text(GOOD, encoding="utf-8")+ _fresh_load(tmp_path)+ _fresh_load(tmp_path)++ good = list_config_backups(config_path, "good")+ assert len(good) == 1+ text = good[0].read_text(encoding="utf-8")+ assert "${LKG_TOKEN}" in text and "expanded-secret" not in textdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 003e76d1fa0..99367001f45 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -193,7 +193,7 @@ updates:`pre_update_backup` is the single pre-update safety knob: `quick` (default) snapshots critical state files (pairing data, cron jobs, config, auth; files over 1 GiB are skipped) into `state-snapshots/`; `full` additionally zips all of `HERMES_HOME` into `backups/` and can add minutes on large homes; `off` disables both. Legacy booleans are honored (`true` → `full`, `false` → `off`).-Point-in-time copies of `config.yaml` itself (taken before `hermes setup` rewrites it, before `hermes migrate` edits it, and when the file fails to parse) go to `backups/config/config.yaml.<reason>.<timestamp>`. Identical repeats are skipped and only the newest five per reason are kept, so they never pile up beside `config.yaml`.+Point-in-time copies of `config.yaml` itself (taken before `hermes setup` rewrites it, before `hermes migrate` edits it, every time the file parses successfully, and when it fails to parse) go to `backups/config/config.yaml.<reason>.<timestamp>`. Identical repeats are skipped and only the newest five per reason are kept, so they never pile up beside `config.yaml`. If `config.yaml` is broken, Hermes serves the newest `good` copy instead of built-in defaults and warns on every start until the YAML is fixed; the broken file is never modified.For git installs, Hermes auto-stashes dirty tracked files and untracked files before checking out the update branch or pulling. Interactive terminal updates prompt before restoring that stash. Non-interactive updates (desktop/chat app, gateway, or `--yes`) use `updates.non_interactive_local_changes`: `stash` restores local source edits after a successful pull, while `discard` drops the update-created stash after a successful pull. Use `discard` only on managed installs where local source edits are never meant to persist.