The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(model): publish saved model selections atomically
helix4u5ae26ec781e1
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 3cd0cba7e7e..c31d89d3478 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -1825,15 +1825,17 @@ def persist_model_selection(result: ModelSwitchResult, config_path: Any = None)"""Write a successful :func:`switch_model` result to ``config_path`` (default:``HERMES_HOME/config.yaml`` — the context override or ``HERMES_HOME`` at call time).- Targeted key writes, not a whole-``model:`` rewrite: a block rewrite destroys sibling keys the- user set there (``model_slots``, ``model_fallback``, ...). ``should_clear_context_pin`` can do- cold-start disk I/O — async callers run this on a worker thread."""+ Build the complete selection from one raw snapshot, preserving sibling settings and secret+ references, then publish once. Per-key publication can leave a mixed route after a failed+ write or an overlapping selection. ``should_clear_context_pin`` can do cold-start disk I/O+ — async callers run this on a worker thread."""from pathlib import Path- from hermes_cli.config import get_config_path, read_user_config_raw- from utils import atomic_roundtrip_yaml_update+ from hermes_cli.config import _CONFIG_LOCK, atomic_config_replace, get_config_path, read_user_config_rawpath = Path(config_path) if config_path else get_config_path()- for key, value in model_selection_config_updates(result, read_user_config_raw(path).get("model")).items():- atomic_roundtrip_yaml_update(path, f"model.{key}", value)+ with _CONFIG_LOCK:+ config = read_user_config_raw(path)+ config["model"] = apply_model_selection(config.get("model"), result)+ atomic_config_replace(path, config)try: # owner-only: config files contain API keysos.chmod(path, 0o600)except (OSError, NotImplementedError):diff --git a/tests/hermes_cli/test_global_switch_persists_base_url_api_mode.py b/tests/hermes_cli/test_global_switch_persists_base_url_api_mode.pyindex dd7be0d3b68..097ecdece5f 100644--- a/tests/hermes_cli/test_global_switch_persists_base_url_api_mode.py+++ b/tests/hermes_cli/test_global_switch_persists_base_url_api_mode.py@@ -20,6 +20,23 @@ import pytestfrom hermes_cli.model_switch import ModelSwitchResult[email protected](autouse=True)+def model_config(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ path = tmp_path / "config.yaml"+ path.write_text(+ "model:\n default: old-model\n provider: copilot\n"+ " base_url: https://api.githubcopilot.com\n api_mode: chat_completions\n",+ encoding="utf-8",+ )+ return path+++def _saved_model():+ from hermes_cli.config import read_user_config_raw+ return {f"model.{key}": value for key, value in read_user_config_raw()["model"].items()}++def _make_result(*, base_url="https://api.minimax.io/v1", api_mode="chat_completions", provider_changed=True):return ModelSwitchResult(success=True,@@ -78,19 +95,13 @@ def _run_switch(monkeypatch, result, cmd="/model MiniMax-M3 --global"):import cli as cli_modmonkeypatch.setattr(cli_mod, "_cprint", lambda *a, **k: None)- saved: dict[str, object] = {}-- def _fake_save(path, key, value):- saved[key] = value-- monkeypatch.setattr("utils.atomic_roundtrip_yaml_update", _fake_save)monkeypatch.setattr("hermes_cli.model_switch.switch_model", lambda **kw: result)monkeypatch.setattr("hermes_cli.inventory.load_picker_context",lambda: (_ for _ in ()).throw(RuntimeError("no picker context in test")),)cli_mod.HermesCLI._handle_model_switch(_StubCLI(), cmd)- return saved+ return _saved_model()def test_global_switch_persists_base_url_and_api_mode(monkeypatch):@@ -104,14 +115,13 @@ def test_global_switch_persists_base_url_and_api_mode(monkeypatch):assert saved["model.api_mode"] == "chat_completions"-def test_session_only_switch_does_not_touch_config(monkeypatch):+def test_session_only_switch_does_not_touch_config(monkeypatch, model_config):"""--session must not write config.yaml at all — persistence staysentirely in-memory."""import cli as cli_modmonkeypatch.setattr(cli_mod, "_cprint", lambda *a, **k: None)- save_calls = []- monkeypatch.setattr("utils.atomic_roundtrip_yaml_update", lambda *a, **k: save_calls.append(a))+ original = model_config.read_bytes()monkeypatch.setattr("hermes_cli.model_switch.switch_model", lambda **kw: _make_result())monkeypatch.setattr("hermes_cli.inventory.load_picker_context",@@ -120,7 +130,7 @@ def test_session_only_switch_does_not_touch_config(monkeypatch):cli_mod.HermesCLI._handle_model_switch(_StubCLI(), "/model MiniMax-M3 --session")- assert save_calls == []+ assert model_config.read_bytes() == originaldef _run_apply(monkeypatch, result, persist_global=True):@@ -132,14 +142,16 @@ def _run_apply(monkeypatch, result, persist_global=True):import cli as cli_modmonkeypatch.setattr(cli_mod, "_cprint", lambda *a, **k: None)- saved: dict[str, object] = {}+ cli_mod.HermesCLI._apply_model_switch_result(_StubCLI(), result, persist_global)+ return _saved_model()- def _fake_save(path, key, value):- saved[key] = value- monkeypatch.setattr("utils.atomic_roundtrip_yaml_update", _fake_save)- cli_mod.HermesCLI._apply_model_switch_result(_StubCLI(), result, persist_global)- return saved+def test_picker_global_switch_persists_base_url_and_api_mode(monkeypatch):+ saved = _run_apply(monkeypatch, _make_result())+ assert saved["model.default"] == "MiniMax-M3"+ assert saved["model.provider"] == "custom:minimax"+ assert saved["model.base_url"] == "https://api.minimax.io/v1"+ assert saved["model.api_mode"] == "chat_completions"diff --git a/tests/hermes_cli/test_model_selection_atomic_persistence.py b/tests/hermes_cli/test_model_selection_atomic_persistence.pynew file mode 100644index 00000000000..e369f966679--- /dev/null+++ b/tests/hermes_cli/test_model_selection_atomic_persistence.py@@ -0,0 +1,191 @@+"""A saved model route is one publication, including stale credential removal."""++from pathlib import Path+import subprocess+import sys++import pytest++import hermes_yaml as yaml+from hermes_cli.model_switch import ModelSwitchResult, persist_model_selection+++_SEED = (+ "# Keep this header\n"+ "model:\n"+ " default: old-model\n"+ " provider: custom:old\n"+ " base_url: https://old.example.test/v1\n"+ " api_mode: chat_completions\n"+ " api_key: ${OLD_MODEL_KEY}\n"+ " key_env: OLD_MODEL_KEY\n"+ " api_key_env: OLD_MODEL_KEY\n"+ " context_length: 32000\n"+ " model_slots:\n"+ ' fast: "keep-this" # Keep this slot\n'+ "auxiliary:\n"+ " vision:\n"+ " api_key: ${VISION_KEY}\n"+ "display:\n"+ ' label: "off" # Keep these quotes\n'+)+_RESULT = ModelSwitchResult(+ success=True,+ new_model="new-model",+ target_provider="custom:new",+ base_url="https://new.example.test/v1",+ api_mode="anthropic_messages",+ is_global=True,+)+_EXPECTED = {+ "default": "new-model",+ "provider": "custom:new",+ "base_url": "https://new.example.test/v1",+ "api_mode": "anthropic_messages",+ "model_slots": {"fast": "keep-this"},+}+++def profile_config(tmp_path, monkeypatch):+ default_home = tmp_path / "default"+ default_home.mkdir()+ default_config = default_home / "config.yaml"+ default_config.write_text("model: default-profile-model\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ monkeypatch.setenv("OLD_MODEL_KEY", "synthetic-expanded-old-key")+ monkeypatch.setenv("VISION_KEY", "synthetic-expanded-vision-key")+ profile_home = tmp_path / "selected-profile"+ profile_home.mkdir()+ path = profile_home / "config.yaml"+ path.write_text(_SEED, encoding="utf-8")+ yield path+ assert (+ default_config.read_text(encoding="utf-8") == "model: default-profile-model\n"+ )+++def test_persist_publishes_only_a_complete_model_route(profile_config, monkeypatch):+ import utils++ replace = utils.atomic_replace+ published = []++ def observe(source, target):+ result = replace(source, target)+ if Path(target) == profile_config:+ published.append(+ yaml.safe_load(profile_config.read_text(encoding="utf-8"))["model"]+ )+ return result++ monkeypatch.setattr(utils, "atomic_replace", observe)+ persist_model_selection(_RESULT, profile_config)++ assert published == [_EXPECTED]+++def test_failed_route_publication_leaves_original_bytes(profile_config, monkeypatch):+ import utils++ original = profile_config.read_bytes()+ replace = utils.atomic_replace++ def reject_new_provider(source, target):+ if Path(target) == profile_config:+ pending = yaml.safe_load(Path(source).read_text(encoding="utf-8"))+ if pending["model"]["provider"] == _RESULT.target_provider:+ raise OSError("synthetic publication failure")+ return replace(source, target)++ monkeypatch.setattr(utils, "atomic_replace", reject_new_provider)+ with pytest.raises(OSError, match="synthetic publication failure"):+ persist_model_selection(_RESULT, profile_config)++ assert profile_config.read_bytes() == original+++def test_same_route_preserves_raw_references_and_siblings(profile_config):+ seed = _SEED.replace(" context_length: 32000\n", "")+ profile_config.write_text(seed, encoding="utf-8")+ same_route = ModelSwitchResult(+ success=True,+ new_model="old-model",+ target_provider="custom:old",+ base_url="https://old.example.test/v1",+ api_mode="chat_completions",+ is_global=True,+ )+ persist_model_selection(same_route, profile_config)++ text = profile_config.read_text(encoding="utf-8")+ assert yaml.safe_load(text) == yaml.safe_load(seed)+ assert "# Keep this header" in text+ assert '"keep-this" # Keep this slot' in text+ assert '"off" # Keep these quotes' in text+ assert "${OLD_MODEL_KEY}" in text and "${VISION_KEY}" in text+ assert "synthetic-expanded" not in text+++def test_overlapping_process_selection_cannot_leave_a_mixed_route(+ profile_config, monkeypatch+):+ from hermes_cli import model_switch+ import utils++ replace = utils.atomic_replace+ intervened = False+ child = (+ "import sys\n"+ "from hermes_cli.model_switch import ModelSwitchResult, persist_model_selection\n"+ 'persist_model_selection(ModelSwitchResult(success=True, new_model="other-model", '+ 'target_provider="custom:other", base_url="https://other.example.test/v1", '+ 'api_mode="chat_completions", is_global=True), sys.argv[1])\n'+ )++ def interleave(source, target):+ nonlocal intervened+ result = replace(source, target)+ if Path(target) == profile_config and not intervened:+ intervened = True+ subprocess.run(+ [sys.executable, "-c", child, str(profile_config)],+ cwd=Path(model_switch.__file__).resolve().parents[1],+ check=True,+ capture_output=True,+ timeout=60,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ return result++ monkeypatch.setattr(utils, "atomic_replace", interleave)+ persist_model_selection(_RESULT, profile_config)+ block = yaml.safe_load(profile_config.read_text(encoding="utf-8"))["model"]+ assert block == {+ **_EXPECTED,+ "default": "other-model",+ "provider": "custom:other",+ "base_url": "https://other.example.test/v1",+ "api_mode": "chat_completions",+ }+++ "content", ["model: [unterminated\n", "- not-a-config-mapping\n"]+)+def test_unreadable_config_is_not_replaced(profile_config, content):+ profile_config.write_text(content, encoding="utf-8")+ original = profile_config.read_bytes()+ with pytest.raises((yaml.YAMLError, RuntimeError, TypeError)):+ persist_model_selection(_RESULT, profile_config)+ assert profile_config.read_bytes() == original+++def test_missing_config_gets_the_complete_route(profile_config):+ profile_config.unlink()+ persist_model_selection(_RESULT, profile_config)+ assert yaml.safe_load(profile_config.read_text(encoding="utf-8")) == {+ "model": {+ key: value for key, value in _EXPECTED.items() if key != "model_slots"+ },+ }