The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): make destructive replacements explicit
JoaoMarcos4416b214e1a1f0
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 9ed41a2db65..ef109e81b5c 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -177,7 +177,7 @@ jobs:run: python scripts/check_no_tmp_literals.py# config.yaml is hand-edited and commented; a PyYAML dump of it destroys every comment- # (#92554, regressed repeatedly). All writers go through hermes_cli.config.atomic_config_write.+ # (#92554, regressed repeatedly). All writers go through the hermes_cli.config writer seam.- name: Forbid config.yaml writers that bypass the comment-preserving writerrun: python scripts/check_config_yaml_writers.pydiff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.mdindex ba5844fbce5..fe0e56582c4 100644--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@ -87,11 +87,12 @@ archive_after_days, backup.*`.set/get/unset <NAME>` route any bare name registered in `OPTIONAL_ENV_VARS` / `_EXTRA_ENV_KEYS`(or carrying a `setup_hidden_env` platform suffix) to `.env` via `config_env_routing.py` — thefile the platform setup flows write — never to the top level of config.yaml.-- **One writer.** Every write of a `config.yaml` (main or profile) goes through- `hermes_cli.config.atomic_config_write` (→ `utils.atomic_roundtrip_yaml_save`, ruamel- round-trip merge): comments, key order, quoting and blank lines survive, absent keys are- deleted, and the fail-closed unreadable-file guard runs first. `save_config`, `config set/unset`,- migrations, plugin bookkeeping, gateway/TUI RPCs and auth resets all reach it; never call+- **One writer seam.** Every write of a `config.yaml` (main or profile) goes through+ `hermes_cli.config.atomic_config_write` (refuses deletion by omission) or the explicit+ `atomic_config_replace` full-state path (→ `utils.atomic_roundtrip_yaml_save`, ruamel+ round-trip): comments, key order, quoting and blank lines survive, and the fail-closed unreadable-file+ guard runs first. Deliberate `pop()`/unset/migration paths use `atomic_config_replace`; additive+ writers stay on `atomic_config_write`. Never call`atomic_yaml_write` / `yaml.dump` / `yaml.safe_dump` on a config path — `scripts/check_config_yaml_writers.py`(CI lint) rejects it, and `tests/hermes_cli/test_config_yaml_comment_preservation.py` guards eachpath (#92554). The commented example blocks are appended only when the file is created.diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 4e4937f9e3e..adf870a2501 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -258,7 +258,7 @@ BUILTIN_PROVIDER_IDS = frozenset(PROVIDER_REGISTRY)# a plugin never observes a partially initialized auth module (CONTRACT: during discovery a plugin may# rely only on ``ProviderConfig`` and ``PROVIDER_REGISTRY`` from here — nothing defined below).from hermes_cli.config import ( # noqa: E402- atomic_config_write, get_hermes_home, get_config_path, read_raw_config, require_readable_config_before_write)+ atomic_config_replace, get_hermes_home, get_config_path, read_raw_config, require_readable_config_before_write)# Plugin profiles (plugins/model-providers/<name>/) are mirrored into PROVIDER_REGISTRY with the# auth_type they declare; the mirror lives in the sibling so it can be re-run after discovery.@@ -2396,7 +2396,7 @@ def _update_config_for_provider(elif clear_default:model_cfg.pop("default", None)config["model"] = model_cfg- atomic_config_write(config_path, config)+ atomic_config_replace(config_path, config)return config_path@@ -2440,7 +2440,7 @@ def _reset_config_provider() -> Path:model["provider"] = "auto"if "base_url" in model:model["base_url"] = OPENROUTER_BASE_URL- atomic_config_write(config_path, config)+ atomic_config_replace(config_path, config)return config_pathdiff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex bb5ce3bfe44..2815fbfe1a1 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -167,14 +167,14 @@ _CONFIG_LOCK = threading.RLock()_LAST_EXPANDED_CONFIG_BY_PATH: Dict[str, Any] = {}# path -> (user_mtime_ns, user_size, managed_mtime_ns, managed_size, merged, env_ref_snapshot).# load_config() returns a deepcopy of the cached value while the signature matches (skips-# safe_load + merge + normalize + expand, ~13 ms). Writers use atomic_config_write (fresh inode+# safe_load + merge + normalize + expand, ~13 ms). Writers use the config writer seam (fresh inode# -> new mtime_ns) so no explicit invalidation is needed. The managed-file signature is folded# in so editing the managed-scope config.yaml invalidates, and the env snapshot invalidates# when a referenced ${VAR} changes value (late .env load, in-process rotation).# (path, mtime_ns, size) -> cached expanded config dict. load_config() returns a deepcopy of the cached# value when the file hasn't changed since the last load, skipping yaml.safe_load + _deep_merge +# _normalize_* + _expand_env_vars (~13 ms/call). save_config() + migrate_config() write via-# atomic_config_write which produces a fresh inode, so stat() sees a new signature and the next load+# the config writer seam, which produces a fresh inode, so stat() sees a new signature and the next load# repopulates automatically — no explicit invalidation hook. See #58514._LOAD_CONFIG_CACHE: Dict[str, Tuple[int, ...]] = {}# path -> (mtime_ns, size, ino, ctime_ns, raw yaml dict) for read_raw_config() (no defaults merged in).@@ -2048,18 +2048,78 @@ def require_readable_config_before_write(config_path: Optional[Path] = None) ->return loaded-def atomic_config_write(config_path: Path, data: Dict[str, Any], *, extra_content_on_create: Optional[str] = None) -> None:- """THE ``config.yaml`` writer: fail-closed (``require_readable_config_before_write``) and- comment-preserving (ruamel round-trip merge of *data* onto the on-disk document). Every code- path that persists a config.yaml — ``save_config``, ``config set``, migrations, plugin- bookkeeping, gateway/TUI RPCs, auth resets — goes through here; a PyYAML dump of a config- path anywhere else is rejected by ``scripts/check_config_yaml_writers.py`` (#92554)."""+def _omitted_config_paths(+ existing: Dict[str, Any], proposed: Dict[str, Any], prefix: Tuple[str, ...] = (),+) -> List[str]:+ """Mapping paths that *proposed* would delete by omission from *existing*.++ The round-trip writer recurses through mappings, so the completeness check must recurse too:+ checking top-level key counts still lets a partial ``plugins: {...}`` payload erase sibling+ settings inside that section. Replacing a non-empty mapping with a scalar/list is likewise a+ deletion of that mapping's children and is reported at the mapping path.+ """+ omitted: List[str] = []+ for key, old_value in existing.items():+ path = (*prefix, str(key))+ if key not in proposed:+ omitted.append(".".join(path))+ continue+ new_value = proposed[key]+ if isinstance(old_value, dict):+ if isinstance(new_value, dict):+ omitted.extend(_omitted_config_paths(old_value, new_value, path))+ elif old_value:+ omitted.append(".".join(path))+ return omitted+++def _write_config_state(+ config_path: Path, data: Dict[str, Any], *, allow_omissions: bool,+ extra_content_on_create: Optional[str] = None,+) -> None:+ """Shared comment-preserving config writer; omission policy is selected by the public wrapper."""from utils import atomic_roundtrip_yaml_save_refuse_failed_read(config_path, data)+ if not allow_omissions:+ existing = require_readable_config_before_write(config_path)+ omitted = _omitted_config_paths(existing, data)+ if omitted:+ shown = ", ".join(omitted[:12])+ if len(omitted) > 12:+ shown += f", +{len(omitted) - 12} more"+ exc = ValueError(f"omitted config paths: {shown}")+ raise _refuse_overwrite(+ config_path,+ "would lose settings omitted by this write",+ exc,+ "Pass the complete current config, or use atomic_config_replace() only when "+ "deletion by omission is deliberate.",+ ) from excatomic_roundtrip_yaml_save(config_path, data, extra_content_on_create=extra_content_on_create)+def atomic_config_write(+ config_path: Path, data: Dict[str, Any], *, extra_content_on_create: Optional[str] = None,+) -> None:+ """Persist config without allowing an incomplete mapping to delete existing settings.++ Values explicitly present in *data* may change, but every existing mapping path must remain.+ Use ``atomic_config_replace`` for a deliberate full-state replacement where omitted keys are+ meant to be deleted. Both paths retain the unreadable-file guard and ruamel comment preservation.+ """+ _write_config_state(+ config_path, data, allow_omissions=False, extra_content_on_create=extra_content_on_create)+++def atomic_config_replace(+ config_path: Path, data: Dict[str, Any], *, extra_content_on_create: Optional[str] = None,+) -> None:+ """Persist the complete desired config state; omitted mapping keys are deliberately deleted."""+ _write_config_state(+ config_path, data, allow_omissions=True, extra_content_on_create=extra_content_on_create)++def load_config() -> Dict[str, Any]:"""Load the merged configuration (DEFAULT_CONFIG + config.yaml + managed scope, env-expanded).Cached on the file signature; returns a deepcopy since most call sites mutate the result.@@ -2485,7 +2545,7 @@ def save_config(effective_preserve_keys = _explicit_config_paths(_raw_for_paths) | set(preserve_keys or ())normalized = _strip_default_values(normalized, DEFAULT_CONFIG, preserve_keys=effective_preserve_keys)- atomic_config_write(config_path, normalized, extra_content_on_create=_commented_sections_for_save(normalized))+ atomic_config_replace(config_path, normalized, extra_content_on_create=_commented_sections_for_save(normalized))_secure_file(config_path)_RAW_CONFIG_CACHE.pop(str(config_path), None)_LAST_EXPANDED_CONFIG_BY_PATH[str(config_path)] = copy.deepcopy(current_normalized)@@ -3519,7 +3579,7 @@ def _write_user_config(config_path: Path, user_config: Dict[str, Any]) -> None:"""Write only the user's raw config back (never the merged defaults)."""ensure_hermes_home()from hermes_cli.observability.shared_metrics_disabled import recording_raw_config_write- recording_raw_config_write(config_path, user_config, atomic_config_write)+ recording_raw_config_write(config_path, user_config, atomic_config_replace)def _print_unknown_key_notice(key: str, suggestion: Optional[str]) -> None:diff --git a/hermes_cli/credential_lifecycle.py b/hermes_cli/credential_lifecycle.pyindex caf027e8cfa..a5f95147acf 100644--- a/hermes_cli/credential_lifecycle.py+++ b/hermes_cli/credential_lifecycle.py@@ -87,7 +87,7 @@ def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[st"""if not old_value:return []- from hermes_cli.config import atomic_config_write, get_config_path, read_user_config_raw+ from hermes_cli.config import atomic_config_replace, get_config_path, read_user_config_rawconfig_path = get_config_path()if not config_path.exists():@@ -135,7 +135,7 @@ def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[st_fix(entry, f"providers.{provider_id}", fields=("api_key",))if touched:- atomic_config_write(config_path, user_config)+ atomic_config_replace(config_path, user_config)return toucheddiff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex db9bd4f7db8..0ec92c1e938 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -374,7 +374,7 @@ def _drift_config_version(f: Finding, should_fix: bool, config_path) -> None:def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:"""Root-level ``provider``/``base_url`` belong under ``model:`` (raw-file diagnostic)."""- from hermes_cli.config import atomic_config_write, read_user_config_raw+ from hermes_cli.config import atomic_config_replace, read_user_config_rawraw_config = read_user_config_raw(config_path)stale_root_keys = [k for k in ("provider", "base_url") if k in raw_config and isinstance(raw_config[k], str)]if not stale_root_keys:@@ -391,7 +391,7 @@ def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:value = raw_config.pop(k)if not raw_model.get(k):raw_model[k] = value- atomic_config_write(config_path, raw_config)+ atomic_config_replace(config_path, raw_config)check_ok("Migrated stale root-level keys into model section")f.fixed += 1diff --git a/hermes_cli/profile_channels.py b/hermes_cli/profile_channels.pyindex 7eac42c82df..b74165686af 100644--- a/hermes_cli/profile_channels.py+++ b/hermes_cli/profile_channels.py@@ -341,7 +341,7 @@ def strip_channel_config(config_path: Path, index: Optional[ChannelKeyIndex] = N"""Remove platform sections from a raw ``config.yaml`` in place. Returns the dotted paths removed."""if not config_path.is_file():return []- from hermes_cli.config import atomic_config_write, read_user_config_raw+ from hermes_cli.config import atomic_config_replace, read_user_config_rawindex = index or ChannelKeyIndex()raw = read_user_config_raw(config_path)paths = _channel_config_paths(raw, index.platforms)@@ -354,7 +354,7 @@ def strip_channel_config(config_path: Path, index: Optional[ChannelKeyIndex] = Nnode.pop(path[-1], None)if isinstance(raw.get("gateway"), dict) and not raw["gateway"]:raw.pop("gateway")- atomic_config_write(config_path, raw)+ atomic_config_replace(config_path, raw)return [".".join(path) for path in paths]diff --git a/scripts/check_config_yaml_writers.py b/scripts/check_config_yaml_writers.pyindex fc416d4bfe6..f2f19949302 100755--- a/scripts/check_config_yaml_writers.py+++ b/scripts/check_config_yaml_writers.py@@ -2,7 +2,8 @@"""Fail when a ``config.yaml`` is written by anything but the comment-preserving writer.Every writer of ``~/.hermes/config.yaml`` (and ``profiles/*/config.yaml``) must go through-``hermes_cli.config.atomic_config_write`` → ``utils.atomic_roundtrip_yaml_save`` (ruamel+``hermes_cli.config.atomic_config_write`` (safe) or ``atomic_config_replace`` (explicit full-state)+→ ``utils.atomic_roundtrip_yaml_save`` (ruamelround-trip). A PyYAML dump (``yaml.dump`` / ``yaml.safe_dump`` / ``utils.atomic_yaml_write``)of a config path re-serialises the parsed dict and destroys every user comment — the #92554class, which regressed several times because each new writer picked the plain dumper again.@@ -14,7 +15,7 @@ Flags, in the scanned trees:``get_config_path()``, ``_active_config_path()``, ``live_path``);* ``<config path>.write_text(... dump(...) ...)``;* any ``yaml.dump`` / ``yaml.safe_dump`` / ``atomic_yaml_write`` call inside ``hermes_cli/config.py``- or ``hermes_cli/config_*.py`` (the config system has exactly one writer).+ or ``hermes_cli/config_*.py`` (the config system has exactly one on-disk primitive).Suppress a true false positive with ``# config-writer: ok — <why>`` on the call's line.@@ -29,7 +30,7 @@ from pathlib import PathROOT = Path(__file__).resolve().parent.parentDEFAULT_TREES = ("hermes_cli", "agent", "gateway", "tui_gateway", "cron", "plugins", "tools", "cli.py", "utils.py")-# The writer module itself and the on-disk primitive it wraps.+# The config writer module and the on-disk primitive it wraps.ALLOWED_FILES = {ROOT / "utils.py"}DUMPERS = {"atomic_yaml_write", "safe_dump", "dump"}CONFIG_PATH_RE = re.compile(@@ -72,7 +73,8 @@ def scan_file(path: Path) -> list[str]:line = lines[node.lineno - 1]if SUPPRESS in line:return- problems.append(f"{rel}:{node.lineno}: {why} — route it through hermes_cli.config.atomic_config_write")+ problems.append(+ f"{rel}:{node.lineno}: {why} — route it through the hermes_cli.config writer seam")for node in ast.walk(tree):if not isinstance(node, ast.Call):diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.pyindex b4e3ff1e872..ff609c9879b 100644--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@ -394,6 +394,54 @@ class TestSaveAndLoadRoundtrip:assert config_path.read_text(encoding="utf-8") == originalassert list((tmp_path / "backups" / "config").glob("config.yaml.corrupt.*"))+ def test_atomic_config_write_refuses_partial_state_instead_of_wiping_config(self, tmp_path):+ """A partial dict is not a full-state replacement: preserve the existing document."""+ from hermes_cli.config import atomic_config_write++ config_path = tmp_path / "config.yaml"+ original = {f"k{i}": i for i in range(99)}+ config_path.write_text(yaml.safe_dump(original), encoding="utf-8")++ with pytest.raises(RuntimeError, match="would lose settings omitted"):+ atomic_config_write(config_path, {"skills": {"disabled": ["a"]}})++ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == original++ def test_atomic_config_write_refuses_nested_omissions_with_same_top_level_keys(self, tmp_path):+ """Completeness is recursive: keeping the root names must not hide sibling deletion."""+ from hermes_cli.config import atomic_config_write++ config_path = tmp_path / "config.yaml"+ original = {+ "plugins": {"enabled": ["guard"], "disabled": [], "config": {"guard": {"mode": "strict"}}},+ "model": {"default": "gpt-5"},+ }+ config_path.write_text(yaml.safe_dump(original), encoding="utf-8")++ with pytest.raises(RuntimeError, match=r"plugins\.(enabled|config)"):+ atomic_config_write(+ config_path,+ {"plugins": {"disabled": ["legacy"]}, "model": {"default": "gpt-5"}},+ )++ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == original++ def test_atomic_config_replace_makes_delete_by_omission_explicit(self, tmp_path):+ """Full-state owners can still deliberately prune keys without a count-based heuristic."""+ from hermes_cli.config import atomic_config_replace++ config_path = tmp_path / "config.yaml"+ config_path.write_text(+ yaml.safe_dump({"model": {"default": "gpt-5"}, "plugins": {"enabled": ["guard"]}}),+ encoding="utf-8",+ )++ replacement = {"model": {"default": "gpt-5"}}+ atomic_config_replace(config_path, replacement)++ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == replacement++class TestLoadEnvInlineComments:def test_unquoted_hash_is_a_comment_quoted_hash_is_data(self, tmp_path):"""load_env is the one dotenv reader (agent.secret_scope.load_env_file): an unquoted ` #...` taildiff --git a/tests/hermes_cli/test_config_yaml_comment_preservation.py b/tests/hermes_cli/test_config_yaml_comment_preservation.pyindex 12093b8968f..36ef08c7f6a 100644--- a/tests/hermes_cli/test_config_yaml_comment_preservation.py+++ b/tests/hermes_cli/test_config_yaml_comment_preservation.py@@ -2,7 +2,7 @@Each test seeds a hand-commented config.yaml, runs one production write path against it andasserts that every comment survives, top-level key order is unchanged, and the written value-landed. A new writer that reaches for PyYAML instead of ``atomic_config_write`` fails here or in+landed. A new writer that reaches for PyYAML instead of the config writer seam fails here or in``scripts/check_config_yaml_writers.py`` (also exercised below)."""@@ -105,7 +105,7 @@ class TestEveryWriterPreservesComments:assert data["_config_version"] == latestdef test_atomic_config_write_direct(self, home):- """Direct callers (auth provider reset, gateway slash commands, telegram, doctor)."""+ """Non-deleting direct callers keep using the guarded writer."""from hermes_cli.config import atomic_config_write, read_user_config_rawraw = read_user_config_raw(home / "config.yaml")diff --git a/tests/hermes_cli/test_model_provider_persistence.py b/tests/hermes_cli/test_model_provider_persistence.pyindex 291e24bd24f..2ccb9fd3d40 100644--- a/tests/hermes_cli/test_model_provider_persistence.py+++ b/tests/hermes_cli/test_model_provider_persistence.py@@ -54,7 +54,7 @@ class TestSaveModelChoiceAlwaysDict:class TestProviderPersistsAfterModelSave:- def test_update_config_for_provider_uses_atomic_config_write(self, config_home):+ def test_update_config_for_provider_uses_atomic_config_replace(self, config_home):"""Provider switches delegate config writes to the comment-preserving config writer."""from hermes_cli.auth import _update_config_for_provider@@ -68,7 +68,7 @@ class TestProviderPersistsAfterModelSave:assert data["model"]["default"] == "some-old-model"raise OSError("simulated atomic write failure")- with patch("hermes_cli.auth.atomic_config_write", side_effect=_boom) as mock_write:+ with patch("hermes_cli.auth.atomic_config_replace", side_effect=_boom) as mock_write:with pytest.raises(OSError, match="simulated atomic write failure"):_update_config_for_provider("nous",diff --git a/tests/hermes_cli/test_profile_clone_channels.py b/tests/hermes_cli/test_profile_clone_channels.pyindex 36afd3d3ce8..def50e8388a 100644--- a/tests/hermes_cli/test_profile_clone_channels.py+++ b/tests/hermes_cli/test_profile_clone_channels.py@@ -8,6 +8,7 @@ while provider/tool keys and general config survive; ``--clone-channels`` restorfrom __future__ import annotationsfrom pathlib import Path+from types import SimpleNamespaceimport pytestimport hermes_yaml as yaml@@ -15,7 +16,7 @@ import hermes_yaml as yamlimport hermes_constantsfrom hermes_cli import gateway_migrate as gmfrom hermes_cli.profile_channels import (- channel_platforms_configured, shared_channel_credentials, strip_channel_env_file,+ channel_platforms_configured, shared_channel_credentials, strip_channel_config, strip_channel_env_file,)from hermes_cli.profiles import create_profile@@ -114,6 +115,27 @@ def test_clone_all_drops_pairing_and_platform_state(home):assert _fingerprints(profile_dir) == set()+def test_strip_channel_config_can_deliberately_remove_most_top_level_keys(tmp_path):+ """Channel stripping is an intentional full-state prune, not an incomplete-payload accident."""+ config_path = tmp_path / "config.yaml"+ original = {+ "model": {"default": "gpt-5"},+ "platforms": {"telegram": {"enabled": True}},+ "telegram": {"reactions": True},+ "discord": {"require_mention": False},+ "gateway": {"multiplex_profiles": True, "profile_routes": [{"profile": "x"}]},+ }+ config_path.write_text(yaml.safe_dump(original), encoding="utf-8")++ removed = strip_channel_config(+ config_path, SimpleNamespace(platforms=("telegram", "discord")))++ assert set(removed) >= {+ "platforms", "telegram", "discord", "gateway.multiplex_profiles", "gateway.profile_routes"}+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {+ "model": {"default": "gpt-5"}}++def test_strip_env_file_keeps_comments_and_unknown_keys_verbatim(tmp_path):env = tmp_path / ".env"env.write_text("# header\nexport OPENAI_API_KEY=abc\n\nTELEGRAM_BOT_TOKEN=1:x\nMY_CUSTOM_THING=1\n", encoding="utf-8")diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 1e0d39eac80..a06c59f59f1 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1279,9 +1279,9 @@ def _load_cfg() -> dict:def _save_cfg(cfg: dict):global _cfg_cache, _cfg_sig, _cfg_path- from hermes_cli.config import atomic_config_write+ from hermes_cli.config import atomic_config_replacepath = _active_config_path()- atomic_config_write(path, cfg)+ atomic_config_replace(path, cfg)with _cfg_lock:_cfg_cache, _cfg_path = copy.deepcopy(cfg), pathtry:diff --git a/utils.py b/utils.pyindex beeb8668200..9915c61234d 100644--- a/utils.py+++ b/utils.py@@ -504,9 +504,9 @@ def atomic_roundtrip_yaml_save(path: Union[str, Path], new_state: dict, *,extra_content_on_create: "str | None" = None) -> None:"""Persist a full config-state dict while preserving comments and ordering.- THE writer for ``config.yaml`` (every production caller reaches it through- ``hermes_cli.config.atomic_config_write``): the on-disk document is loaded through ruamel- round-trip mode and *new_state* is merged onto it, so comments, key order, quotes, blank+ THE on-disk primitive for ``config.yaml`` (production callers reach it through+ ``hermes_cli.config.atomic_config_write`` or ``atomic_config_replace``): the document is+ loaded through ruamel round-trip mode and *new_state* is merged onto it, so comments, key order, quotes, blanklines and readable Unicode survive. Only nodes whose value actually changed are reassigned;an untouched scalar or list keeps its inline comments and formatting. Keys absent from*new_state* are deleted ("explicit absence": ``cfg.pop(k)`` + save removes ``k`` from disk).