The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): restore user model settings config.yaml rewrites drop during update
Teknium045865377c25
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 9a63f4d0464..bed68e2a9d8 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -22,7 +22,7 @@ import zipfilefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Tuplefrom hermes_constants import (_get_platform_default_hermes_home,@@ -2059,6 +2059,172 @@ def create_pre_update_snapshots_all_profiles(return results+# Config paths that the update flow must never change (#64160): the model+# routing keys and the Mixture-of-Agents section are consumed machine-wide+# (gateway, cron, desktop), so an update/repair cycle that rewrites them+# silently redirects paid inference. Each entry is a dotted path into the raw+# config.yaml document; a single-element tuple protects the whole section.+_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (+ ("model", "provider"),+ ("model", "default"),+ ("model", "base_url"),+ ("model", "api_key"),+ ("moa",),+)+++def _read_raw_yaml_dict(path: Path) -> Optional[Dict[str, Any]]:+ """Parse ``path`` as a YAML mapping. ``None`` = missing/unreadable/non-dict."""+ if not path.is_file():+ return None+ try:+ import yaml++ with open(path, "r", encoding="utf-8") as f:+ data = yaml.safe_load(f)+ except Exception:+ return None+ return data if isinstance(data, dict) else None+++def _get_config_path_value(data: Dict[str, Any], dotted: Tuple[str, ...]) -> Any:+ node: Any = data+ for key in dotted:+ if not isinstance(node, dict):+ return None+ node = node.get(key)+ return node+++def _set_config_path_value(data: Dict[str, Any], dotted: Tuple[str, ...], value: Any) -> None:+ node = data+ for key in dotted[:-1]:+ child = node.get(key)+ if not isinstance(child, dict):+ child = {}+ node[key] = child+ node = child+ node[dotted[-1]] = value+++def restore_config_model_settings_if_rewritten(+ snapshot_id: str,+ hermes_home: Optional[Path] = None,+) -> Optional[Dict[str, Any]]:+ """Safety net for silent config.yaml model/MoA loss across ``hermes update``.++ Desktop update/repair cycles have been observed to rewrite user-set+ ``model.provider``/``model.default`` and drop the ``moa:`` section+ entirely (issue #64160; the macOS repair/relaunch variant rewrote a+ pinned ``model.default`` to a transient composer pick). These keys are+ consumed by the gateway and unattended cron jobs too, so a rewrite+ silently changes paid inference behavior machine-wide.++ Mirrors :func:`restore_cron_jobs_if_emptied`: compare the *current*+ config against the pre-update snapshot taken minutes earlier by this+ same update run, and restore only the protected keys — never the whole+ file — when a value the user had set was changed or dropped. Everything+ the update legitimately wrote (version stamps, new sections) is left in+ place.++ Args:+ snapshot_id: The pre-update quick-snapshot id (from+ :func:`create_quick_snapshot`).+ hermes_home: Override for the Hermes home directory (tests/siblings).++ Returns:+ ``None`` when no action was taken (the common, healthy path). On a+ successful restore, ``{"restored": True, "keys": [...],+ "snapshot_id": ...}`` so the caller can warn the user.+ """+ if not snapshot_id:+ return None++ home = hermes_home or get_hermes_home()+ live_path = home / "config.yaml"+ snap_path = _quick_snapshot_root(home) / snapshot_id / "config.yaml"++ snap = _read_raw_yaml_dict(snap_path)+ if not snap:+ return None # no snapshot copy — nothing to compare against+ live = _read_raw_yaml_dict(live_path)+ if live is None:+ # Missing or unparseable live config is a different failure mode the+ # user should see rather than have papered over (matches the cron net).+ return None++ restored_keys: list[str] = []+ for dotted in _PROTECTED_CONFIG_PATHS:+ snap_val = _get_config_path_value(snap, dotted)+ if snap_val in (None, "", {}, []):+ continue # user never set it — nothing to protect+ live_val = _get_config_path_value(live, dotted)+ if live_val == snap_val:+ continue+ _set_config_path_value(live, dotted, snap_val)+ restored_keys.append(".".join(dotted))++ if not restored_keys:+ return None++ try:+ from utils import atomic_yaml_write++ atomic_yaml_write(live_path, live)+ except (OSError, PermissionError) as exc:+ logger.error(+ "config.yaml model settings were rewritten during update but "+ "auto-restore failed: %s",+ exc,+ )+ return None++ logger.warning(+ "Restored user config value(s) %s from pre-update snapshot %s — "+ "the update flow rewrote them (#64160)",+ ", ".join(restored_keys),+ snapshot_id,+ )+ return {"restored": True, "keys": restored_keys, "snapshot_id": snapshot_id}+++def restore_config_model_settings_all_profiles(+ profile_snapshots: Dict[str, str],+ invoking_home: Optional[Path] = None,+) -> list[Dict[str, Any]]:+ """Run the config model-settings safety net for every sibling profile.++ Same contract as :func:`restore_cron_jobs_all_profiles`: each profile's+ live ``config.yaml`` is compared against ITS OWN same-generation+ pre-update snapshot. Returns one result dict per restored profile, each+ with a ``profile`` key added. Never raises.+ """+ restored: list[Dict[str, Any]] = []+ if not profile_snapshots:+ return restored+ home = invoking_home or get_hermes_home()+ by_name = dict(_sibling_profile_homes(home))+ for name, snap_id in profile_snapshots.items():+ profile_home = by_name.get(name)+ if profile_home is None:+ continue+ try:+ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=profile_home+ )+ except Exception as exc:+ logger.debug(+ "Config model-settings restore check for profile %s failed: %s",+ name,+ exc,+ )+ continue+ if result:+ result["profile"] = name+ restored.append(result)+ return restored++def restore_cron_jobs_all_profiles(profile_snapshots: Dict[str, str],invoking_home: Optional[Path] = None,diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex c23024515ad..7c7125cbd95 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -497,6 +497,28 @@ def _check_and_apply_config_migration(# Never let the cron safety net break an otherwise-good update.logger.debug("Cron jobs auto-restore check failed: %s", exc)+ # #64160: config.yaml model/provider + MoA safety net. Desktop+ # update/repair cycles have rewritten user-set model.provider /+ # model.default and dropped the moa: section — settings the gateway+ # and cron jobs also consume. Compare the live config against the+ # same pre-update snapshot and restore only the protected keys.+ try:+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ cfg_restore = restore_config_model_settings_if_rewritten(+ pre_update_snapshot_id+ )+ if cfg_restore:+ print()+ print(+ " ⚠️ config.yaml user model settings were rewritten during "+ f"this update — restored {', '.join(cfg_restore['keys'])} "+ f"from pre-update snapshot {cfg_restore['snapshot_id']}."+ )+ except Exception as exc:+ # Never let the config safety net break an otherwise-good update.+ logger.debug("Config model-settings auto-restore check failed: %s", exc)+# #66140: run the same cron-jobs safety net for every sibling# profile against ITS OWN pre-update snapshot (same-generation by# construction — both taken by this run).@@ -516,6 +538,23 @@ def _check_and_apply_config_migration(except Exception as exc:logger.debug("Sibling cron auto-restore check failed: %s", exc)+ # #64160: same config model-settings safety net for sibling profiles.+ try:+ from hermes_cli.backup import restore_config_model_settings_all_profiles++ for _cfg_restored in restore_config_model_settings_all_profiles(+ _LAST_SIBLING_SNAPSHOTS+ ):+ print()+ print(+ f" ⚠️ Profile '{_cfg_restored['profile']}': config.yaml "+ f"user model settings were rewritten during this update — "+ f"restored {', '.join(_cfg_restored['keys'])} from "+ f"pre-update snapshot {_cfg_restored['snapshot_id']}."+ )+ except Exception as exc:+ logger.debug("Sibling config auto-restore check failed: %s", exc)+# Critical files that Hermes must be able to import immediately after an# update/install. Most are imported on every CLI startup; ``web_server.py``diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 3a3b5620b7c..f0e8e52e4d3 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -1777,6 +1777,161 @@ class TestRestoreCronJobsIfEmptied:assert len(restored["jobs"]) == 19+# ---------------------------------------------------------------------------+# config.yaml model/provider + MoA auto-restore after silent update rewrite+# (issue #64160)+# ---------------------------------------------------------------------------++class TestRestoreConfigModelSettingsIfRewritten:+ """Desktop update/repair cycles have rewritten user-set model.provider /+ model.default and dropped the moa: section (#64160).+ `restore_config_model_settings_if_rewritten` is the post-update safety net+ that restores only the protected keys from the pre-update snapshot."""++ USER_CONFIG = (+ "_config_version: 39\n"+ "model:\n"+ " provider: custom\n"+ " default: zyphra/zamba-3-large\n"+ " base_url: https://api.zyphra.example/v1\n"+ "moa:\n"+ " enabled: true\n"+ " presets:\n"+ " council:\n"+ " aggregator: {provider: custom, model: zyphra/zamba-3-large}\n"+ "custom_unknown_key:\n"+ " hello: world\n"+ )++ def _make_snapshot(self, hermes_home: Path, label="pre-update"):+ from hermes_cli.backup import create_quick_snapshot+ return create_quick_snapshot(label=label, hermes_home=hermes_home, keep=5)++ def _seed(self, hermes_home: Path) -> Path:+ hermes_home.mkdir(parents=True, exist_ok=True)+ cfg = hermes_home / "config.yaml"+ cfg.write_text(self.USER_CONFIG, encoding="utf-8")+ return cfg++ def test_restores_rewritten_provider_and_dropped_moa(self, tmp_path):+ import yaml+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ cfg = self._seed(hermes_home)+ snap_id = self._make_snapshot(hermes_home)+ assert snap_id++ # The update flow rewrites config.yaml with defaults: provider flips+ # to deepseek, MoA section is gone (the #64160 field report).+ cfg.write_text(+ "_config_version: 39\nmodel:\n provider: deepseek\n default: deepseek-chat\n",+ encoding="utf-8",+ )++ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=hermes_home+ )+ assert result is not None+ assert result["restored"] is True+ assert result["snapshot_id"] == snap_id+ assert "model.provider" in result["keys"]+ assert "model.default" in result["keys"]+ assert "moa" in result["keys"]++ after = yaml.safe_load(cfg.read_text(encoding="utf-8"))+ assert after["model"]["provider"] == "custom"+ assert after["model"]["default"] == "zyphra/zamba-3-large"+ assert after["model"]["base_url"] == "https://api.zyphra.example/v1"+ assert after["moa"]["enabled"] is True+ assert after["moa"]["presets"]["council"]["aggregator"]["model"] == (+ "zyphra/zamba-3-large"+ )++ def test_noop_when_config_untouched(self, tmp_path):+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ cfg = self._seed(hermes_home)+ snap_id = self._make_snapshot(hermes_home)+ before = cfg.read_text(encoding="utf-8")++ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=hermes_home+ )+ assert result is None+ assert cfg.read_text(encoding="utf-8") == before++ def test_preserves_legitimate_update_writes(self, tmp_path):+ """Only protected keys are restored — a version bump or a new section+ the migration legitimately wrote must survive the restore."""+ import yaml+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ cfg = self._seed(hermes_home)+ snap_id = self._make_snapshot(hermes_home)++ cfg.write_text(+ "_config_version: 40\n" # legitimate migration bump+ "new_section:\n added: true\n" # legitimate new default+ "model:\n provider: deepseek\n", # illegitimate rewrite+ encoding="utf-8",+ )++ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=hermes_home+ )+ assert result is not None+ after = yaml.safe_load(cfg.read_text(encoding="utf-8"))+ assert after["model"]["provider"] == "custom" # restored+ assert after["_config_version"] == 40 # kept+ assert after["new_section"] == {"added": True} # kept++ def test_noop_when_user_never_set_protected_keys(self, tmp_path):+ """A config that never had model.provider/moa set gets no restore even+ if the update writes those keys fresh — nothing of the user's was lost."""+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir(parents=True)+ cfg = hermes_home / "config.yaml"+ cfg.write_text("_config_version: 39\nagent: {}\n", encoding="utf-8")+ snap_id = self._make_snapshot(hermes_home)++ cfg.write_text(+ "_config_version: 39\nmodel:\n provider: deepseek\n", encoding="utf-8"+ )+ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=hermes_home+ )+ assert result is None++ def test_noop_on_unreadable_live_config(self, tmp_path):+ """An unparseable live config is a different failure the user must see;+ the safety net leaves it alone (mirrors the cron net's posture)."""+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ hermes_home = tmp_path / ".hermes"+ cfg = self._seed(hermes_home)+ snap_id = self._make_snapshot(hermes_home)++ cfg.write_text(": not [valid yaml", encoding="utf-8")+ result = restore_config_model_settings_if_rewritten(+ snap_id, hermes_home=hermes_home+ )+ assert result is None+ assert cfg.read_text(encoding="utf-8") == ": not [valid yaml"++ def test_noop_without_snapshot_id(self, tmp_path):+ from hermes_cli.backup import restore_config_model_settings_if_rewritten++ assert restore_config_model_settings_if_rewritten(+ "", hermes_home=tmp_path / ".hermes"+ ) is None+++