The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): move the config version stamp into config_version_stamp
Brooklyn Nicholson81c2145c8d35
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex c899458eab0..fa25d241248 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -609,6 +609,13 @@ from hermes_cli.personality import ( # noqa: E402,F401render_personality_prompt,resolve_ephemeral_system_prompt as resolve_ephemeral_system_prompt_from_config)+# ---- Config schema-version stamp ---- (moved into config_version_stamp; re-exported here+# because callers and tests import these from hermes_cli.config)++from hermes_cli.config_version_stamp import ( # noqa: E402,F401+ check_config_version, read_config_version_stamp)++# ---- Config Migration System ----# Env vars introduced per config version; migration only mentions vars new since the user's@@ -894,6 +901,8 @@ def _format_config_get_value(value, *, as_json: bool) -> str:def get_missing_config_fields() -> List[Dict[str, Any]]:"""Check which config fields are missing or outdated (recursive)."""+ from hermes_cli.moa_config import skip_deep_merge+missing = []def _check(defaults: dict, current: dict, prefix: str = ""):@@ -904,11 +913,8 @@ def get_missing_config_fields() -> List[Dict[str, Any]]:if key not in current:missing.append({"key": full_key, "default": default_value,"description": f"New config option: {full_key}"})- elif (- isinstance(default_value, dict)- and isinstance(current.get(key), dict)- and not (prefix == "moa" and key == "presets")- ):+ elif (isinstance(default_value, dict) and isinstance(current.get(key), dict)+ and not skip_deep_merge(prefix, key)):_check(default_value, current[key], full_key)_check(DEFAULT_CONFIG, load_config())@@ -936,67 +942,6 @@ def get_missing_skill_config_vars() -> List[Dict[str, Any]]:return [var for var, v in values if v is None or (isinstance(v, str) and not v.strip())]-def _coerce_config_version(value: Any) -> int:- """Return a safe integer config version, treating invalid values as legacy."""- if isinstance(value, bool):- return 0- try:- version = int(value)- except (TypeError, ValueError):- return 0- return max(version, 0)---def _read_config_version_stamp(*, raise_on_parse_error: bool = False) -> Tuple[Optional[int], int]:- """Single raw read behind ``check_config_version()``: ``(stamp, latest_version)`` where- *stamp* is ``None`` when config.yaml parsed but carries no ``_config_version`` key (a- never-stamped current-schema file, not an ancient install — ``migrate_config()`` gives it only- the legacy-key steps). A missing file, or malformed YAML under a tolerant caller, reads as- ``latest`` exactly as ``check_config_version()`` always reported it."""- latest = _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1- config_path = get_config_path()- if not config_path.exists():- return latest, latest-- try:- with open(config_path, encoding="utf-8-sig") as f:- config = fast_safe_load(f)- except Exception as e:- _warn_config_parse_failure(config_path, e)- if raise_on_parse_error:- raise InvalidUserConfigError(- f"Cannot inspect {config_path}: config.yaml is not valid YAML ({e})"- ) from e- return latest, latest-- if config is None:- config = {} # empty file / bare document: valid first-run state- if not isinstance(config, dict):- # A list/scalar root parses fine but is just as unusable as broken YAML: save_config()- # would refuse it later, after .env was already rewritten. Strict callers see it up front.- if raise_on_parse_error:- raise InvalidUserConfigError(- f"Cannot inspect {config_path}: config.yaml top-level value must be "- f"a mapping, got {type(config).__name__}"- )- config = {}- if "_config_version" not in config:- return None, latest- return _coerce_config_version(config.get("_config_version")), latest---def check_config_version(*, raise_on_parse_error: bool = False) -> Tuple[int, int]:- """Return ``(current_version, latest_version)`` from the raw on-disk config.- Reads the raw file rather than ``load_config()``: the deep-merge would make a file lacking- ``_config_version`` inherit the latest version, hiding that the schema was never migrated.- Invalid YAML gets a parse warning, not an automatic schema rewrite. Tolerant runtime status- callers keep the historical latest/latest fallback for malformed YAML; mutation and explicit- validation paths set ``raise_on_parse_error`` so a parse failure or a non-mapping root cannot- be mistaken for an up-to-date config. A file with no version key reads as 0."""- stamp, latest = _read_config_version_stamp(raise_on_parse_error=raise_on_parse_error)- return (0 if stamp is None else stamp), latest--# ---- Config structure validation ----# DEFAULT_CONFIG is the single source of truth for documented roots; the set is derived so new@@ -1352,7 +1297,7 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A# Validate config.yaml before any migration side effect: sanitize_env_file() rewrites .env,# which must not happen when the migration will be refused for malformed YAML.- stamp, latest_ver = _read_config_version_stamp(raise_on_parse_error=True)+ stamp, latest_ver = read_config_version_stamp(raise_on_parse_error=True)current_ver = 0 if stamp is None else stamptry:diff --git a/hermes_cli/config_version_stamp.py b/hermes_cli/config_version_stamp.pynew file mode 100644index 00000000000..330f518e395--- /dev/null+++ b/hermes_cli/config_version_stamp.py@@ -0,0 +1,75 @@+"""The config schema-version stamp: raw reads of ``_config_version`` from config.yaml.++Split out of :mod:`hermes_cli.config` (code-health size ratchet); ``hermes_cli.config``+late-imports these and re-exports them, and :mod:`scripts.docker_config_migrate` reads the+raw stamp directly. ``_coerce_config_version`` stays module-private here.+"""++from __future__ import annotations++from typing import Optional, Tuple++from hermes_cli.config_defaults import DEFAULT_CONFIG+++def _coerce_config_version(value) -> int:+ """Return a safe integer config version, treating invalid values as legacy."""+ if isinstance(value, bool):+ return 0+ try:+ version = int(value)+ except (TypeError, ValueError):+ return 0+ return max(version, 0)+++def read_config_version_stamp(*, raise_on_parse_error: bool = False) -> Tuple[Optional[int], int]:+ """Single raw read behind ``check_config_version()``: ``(stamp, latest_version)`` where+ *stamp* is ``None`` when config.yaml parsed but carries no ``_config_version`` key (a+ never-stamped current-schema file, not an ancient install — ``migrate_config()`` gives it only+ the legacy-key steps). A missing file, or malformed YAML under a tolerant caller, reads as+ ``latest`` exactly as ``check_config_version()`` always reported it."""+ from hermes_cli.config import InvalidUserConfigError, _warn_config_parse_failure, fast_safe_load, get_config_path++ latest = _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1+ config_path = get_config_path()+ if not config_path.exists():+ return latest, latest++ try:+ with open(config_path, encoding="utf-8-sig") as f:+ config = fast_safe_load(f)+ except Exception as e:+ _warn_config_parse_failure(config_path, e)+ if raise_on_parse_error:+ raise InvalidUserConfigError(+ f"Cannot inspect {config_path}: config.yaml is not valid YAML ({e})"+ ) from e+ return latest, latest++ if config is None:+ config = {} # empty file / bare document: valid first-run state+ if not isinstance(config, dict):+ # A list/scalar root parses fine but is just as unusable as broken YAML: save_config()+ # would refuse it later, after .env was already rewritten. Strict callers see it up front.+ if raise_on_parse_error:+ raise InvalidUserConfigError(+ f"Cannot inspect {config_path}: config.yaml top-level value must be "+ f"a mapping, got {type(config).__name__}"+ )+ config = {}+ if "_config_version" not in config:+ return None, latest+ return _coerce_config_version(config.get("_config_version")), latest+++def check_config_version(*, raise_on_parse_error: bool = False) -> Tuple[int, int]:+ """Return ``(current_version, latest_version)`` from the raw on-disk config.+ Reads the raw file rather than ``load_config()``: the deep-merge would make a file lacking+ ``_config_version`` inherit the latest version, hiding that the schema was never migrated.+ Invalid YAML gets a parse warning, not an automatic schema rewrite. Tolerant runtime status+ callers keep the historical latest/latest fallback for malformed YAML; mutation and explicit+ validation paths set ``raise_on_parse_error`` so a parse failure or a non-mapping root cannot+ be mistaken for an up-to-date config. A file with no version key reads as 0."""+ stamp, latest = read_config_version_stamp(raise_on_parse_error=raise_on_parse_error)+ return (0 if stamp is None else stamp), latestdiff --git a/hermes_cli/moa_config.py b/hermes_cli/moa_config.pyindex 66559bb6e3b..d0a2b44dd39 100644--- a/hermes_cli/moa_config.py+++ b/hermes_cli/moa_config.py@@ -291,6 +291,16 @@ def resolve_moa_preset(config: Any, name: str | None = None) -> dict[str, Any]:return deepcopy(preset)+def skip_deep_merge(prefix: str, key: str) -> bool:+ """True when the generic missing-config recursion must NOT descend into this section key.++ ``moa.presets`` is a named map; a present-but-partial user map is authoritative+ (see :func:`apply_user_moa_presets`), so the new-key probe must not imply a+ union into it.+ """+ return prefix == "moa" and key == "presets"++def apply_user_moa_presets(merged: dict[str, Any], raw: Any) -> None:"""Treat an explicit user MoA preset map as authoritative.diff --git a/scripts/docker_config_migrate.py b/scripts/docker_config_migrate.pyindex bd111f0d0f7..ff3ae593e23 100644--- a/scripts/docker_config_migrate.py+++ b/scripts/docker_config_migrate.py@@ -9,12 +9,11 @@ from typing import Iterablefrom hermes_cli.config import (InvalidUserConfigError,- _read_config_version_stamp,- check_config_version,get_config_path,get_env_path,migrate_config,)+from hermes_cli.config_version_stamp import check_config_version, read_config_version_stampfrom hermes_cli.config_backups import backup_config, list_config_backupsfrom hermes_cli.config_migrations import (SUPPORT_FLOOR_VERSION,@@ -53,7 +52,7 @@ def main() -> int:# boot continues, instead of running the backup/migrate dance that migrate_config() would# refuse anyway.try:- stamp, latest_ver = _read_config_version_stamp(raise_on_parse_error=True)+ stamp, latest_ver = read_config_version_stamp(raise_on_parse_error=True)except InvalidUserConfigError as exc:print(f"[config-migrate] WARNING: {exc}; leaving config.yaml untouched", file=sys.stderr)return 0diff --git a/tests/tools/test_docker_config_migrate.py b/tests/tools/test_docker_config_migrate.pyindex f5ccd92ca97..faec600929e 100644--- a/tests/tools/test_docker_config_migrate.py+++ b/tests/tools/test_docker_config_migrate.py@@ -156,7 +156,7 @@ def test_docker_config_migrate_restores_backups_after_failed_migration(env_path.write_text(original_env, encoding="utf-8")monkeypatch.setattr(- module, "_read_config_version_stamp",+ module, "read_config_version_stamp",lambda *, raise_on_parse_error=False: (12, DEFAULT_CONFIG["_config_version"]))monkeypatch.setattr(module, "get_config_path", lambda: config_path)monkeypatch.setattr(module, "get_env_path", lambda: env_path)@@ -189,7 +189,7 @@ def test_docker_config_migrate_restores_backups_when_version_does_not_advance(env_path.write_text(original_env, encoding="utf-8")monkeypatch.setattr(- module, "_read_config_version_stamp",+ module, "read_config_version_stamp",lambda *, raise_on_parse_error=False: (12, DEFAULT_CONFIG["_config_version"]))monkeypatch.setattr(module, "check_config_version", lambda: (12, DEFAULT_CONFIG["_config_version"]))monkeypatch.setattr(module, "get_config_path", lambda: config_path)