The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): an unreadable config never serves the TUI's cached empty config; review fixes
Teknium749cb638ff43
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.pyindex 789c16e1a33..b4b93037958 100644--- a/hermes_cli/config_backend.py+++ b/hermes_cli/config_backend.py@@ -27,13 +27,6 @@ CONFIG_FILENAME = "config.yaml"PathLike = Union[str, "os.PathLike[str]"]-@dataclass(frozen=True)-class UserLayer:- """One read of a profile's user layer."""- doc: Any # the parsed root as written (None for an empty document)- version: tuple[Any, ...] # the cache signature this doc was read at--@dataclass(frozen=True)class Changes:"""A write to one profile's user layer.@@ -52,10 +45,12 @@ class Changes:class ConfigBackend(Protocol):name: str- def read_user_layer(self, home: Path) -> UserLayer: ...+ def read_user_doc(self, home: Path) -> Any:+ """The parsed user layer as written (None for an empty document); version checks are separate."""+ ...def read_user_doc_readonly(self, home: Path) -> Any:- """``read_user_layer(home).doc`` re-read only when ``version`` changes; never mutate it."""+ """``read_user_doc(home)`` re-read only when ``version`` changes; never mutate it."""...def version(self, home: Path) -> tuple[Any, ...]:@@ -108,10 +103,8 @@ class FileBackend:def config_path(self, home: Path) -> Path:return Path(home) / CONFIG_FILENAME- def read_user_layer(self, home: Path) -> UserLayer:- path = self.config_path(home)- version = self.version_path(path)- return UserLayer(doc=self.read_path(path), version=version)+ def read_user_doc(self, home: Path) -> Any:+ return self.read_path(self.config_path(home))def read_user_doc_readonly(self, home: Path) -> Any:return self.read_path_readonly(self.config_path(home))@@ -165,7 +158,7 @@ def _route(config_path: PathLike) -> tuple[ConfigBackend, Path]:def read_config_doc(config_path: PathLike) -> Any:"""Parsed root of a config file (None when empty); raises like ``open`` + ``fast_safe_load``."""backend, home = _route(config_path)- return backend.read_user_layer(home).doc+ return backend.read_user_doc(home)def read_config_doc_readonly(config_path: PathLike) -> Any:diff --git a/pm/publication.py b/pm/publication.pyindex 0deff0ccf9e..b89618a375b 100644--- a/pm/publication.py+++ b/pm/publication.py@@ -94,7 +94,7 @@ class PluginSelection:enabled=selection["enabled"], disabled=selection["disabled"])def publish(self, project: Path) -> None:- if selection_snapshot() != self.configs or read_bytes_or_none(self.path) != self.previous:+ if selection_snapshot() != self.configs or read_bytes_or_none(self.path) != self.previous: # config-reader: ok — pm publication: byte-level compare-and-swap rewrite of the local fileraise ValueError("plugin configuration changed while preparing publication; retry")row = {"config": str(self.path),"previous": base64.b64encode(self.previous).decode() if self.previous is not None else None,diff --git a/scripts/check_config_yaml_readers.py b/scripts/check_config_yaml_readers.pyindex 86038e00ee3..9c9b971fb74 100644--- a/scripts/check_config_yaml_readers.py+++ b/scripts/check_config_yaml_readers.py@@ -80,13 +80,18 @@ def _func_name(node: ast.AST) -> str | None:return None+_COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)+# Each binds its own names: a comprehension's target never leaks into the enclosing function.+_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef, *_COMPREHENSIONS)++def _scope_nodes(scope: ast.AST):- """Nodes of *scope* without descending into nested function/class bodies."""+ """Nodes of *scope* without descending into nested function/class/comprehension scopes."""stack = list(ast.iter_child_nodes(scope))while stack:node = stack.pop()yield node- if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):+ if not isinstance(node, _SCOPES):stack.extend(ast.iter_child_nodes(node))@@ -147,6 +152,11 @@ class _Scanner:if len(names) == before:return names+ def class_attrs(self, cls: ast.ClassDef, inherited: set[str]) -> set[str]:+ """``self.<attr>`` bound to a config path in any method: every method of the class sees it."""+ methods = (n for n in cls.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)))+ return {name for m in methods for name in self.config_names(m, inherited) if name.startswith("self.")}+def _bind(self, target: ast.AST, value: ast.AST, names: set[str]) -> None:"""Add *target* (a name, ``self.attr``, or an unpacked tuple element) when *value* is a config path."""if isinstance(target, (ast.Tuple, ast.List)):@@ -201,10 +211,12 @@ class _Scanner:def walk(scope: ast.AST, inherited: set[str]) -> None:names = self.config_names(scope, inherited)+ if isinstance(scope, ast.ClassDef):+ names |= self.class_attrs(scope, names)for node in _scope_nodes(scope):if isinstance(node, ast.Call):self.check_call(node, names)- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):+ if isinstance(node, _SCOPES):walk(node, names)walk(tree, set())diff --git a/tests/hermes_cli/test_config_backend.py b/tests/hermes_cli/test_config_backend.pyindex 22b2e211221..95cd403a548 100644--- a/tests/hermes_cli/test_config_backend.py+++ b/tests/hermes_cli/test_config_backend.py@@ -86,9 +86,9 @@ class _RecordingBackend(cb.FileBackend):def _rec(self, op, home):self.calls.append((op, Path(home)))- def read_user_layer(self, home):+ def read_user_doc(self, home):self._rec("read", home)- return super().read_user_layer(home)+ return super().read_user_doc(home)def read_user_doc_readonly(self, home):self._rec("read", home)@@ -241,6 +241,22 @@ class TestReaderGate:with patch.object(guard, "ROOT", tmp_path):assert len(guard.scan_file(bad)) == 1+ def test_scopes_follow_python(self, tmp_path):+ # An attribute bound in __init__ is seen by every method; a comprehension's name stays inside it.+ guard = self._guard()+ src = tmp_path / "hermes_cli" / "scoped.py"+ src.parent.mkdir()+ src.write_text(+ "from hermes_cli.config_backend import read_config_doc\n"+ "class A:\n def __init__(self, home):\n self.cfg = home / 'config.yaml'\n"+ " def read(self):\n return self.cfg.read_text()\n"+ "def b(home, p):\n docs = [read_config_doc(p) for p in (home / 'config.yaml',)]\n"+ " return docs, p.read_text()\n",+ encoding="utf-8")+ with patch.object(guard, "ROOT", tmp_path):+ problems = guard.scan_file(src)+ assert [int(p.split(":")[1]) for p in problems] == [6], problems+def test_backend_calls_are_clean(self, tmp_path):guard = self._guard()good = tmp_path / "hermes_cli" / "good_reader.py"diff --git a/tests/hermes_cli/test_profile_listing_cache.py b/tests/hermes_cli/test_profile_listing_cache.pyindex e5276987320..08f18870f11 100644--- a/tests/hermes_cli/test_profile_listing_cache.py+++ b/tests/hermes_cli/test_profile_listing_cache.py@@ -93,7 +93,7 @@ def test_config_model_cache_is_keyed_on_the_backend_version_not_the_local_file(passert profiles._read_config_model(profile_dir) == ("gpt-4o", "openai")version = [("v2",)]monkeypatch.setattr(config_backend, "config_version", lambda path: version[0])- monkeypatch.setattr(config_backend.FileBackend, "read_user_layer", lambda self, home: config_backend.UserLayer(- doc={"model": {"provider": "anthropic", "default": "claude-opus-4.6"}}, version=version[0]))+ monkeypatch.setattr(config_backend.FileBackend, "read_user_doc",+ lambda self, home: {"model": {"provider": "anthropic", "default": "claude-opus-4.6"}})assert profiles._read_config_model(profile_dir) == ("claude-opus-4.6", "anthropic")diff --git a/tests/tui_gateway/test_raw_config_cache_stat_errors.py b/tests/tui_gateway/test_raw_config_cache_stat_errors.pynew file mode 100644index 00000000000..2a2598a9a99--- /dev/null+++ b/tests/tui_gateway/test_raw_config_cache_stat_errors.py@@ -0,0 +1,26 @@+"""The TUI raw-config cache never treats an unreadable config.yaml as an absent one.++``_load_cfg_raw`` feeds ``config.set`` read-modify-write round-trips; serving its cached ``{}`` for a+config that now exists but cannot be stat'ed would let the next save erase every other setting.+"""++from hermes_cli import config_backend+from hermes_cli.config_read_errors import FailedConfigRead+from tui_gateway import server+++def test_stat_error_after_a_cached_absent_config_is_a_failed_read(monkeypatch, tmp_path):+ cfg = tmp_path / "config.yaml"+ monkeypatch.setattr(server, "_active_config_path", lambda: cfg)+ monkeypatch.setattr(server, "_cfg_cache", None)+ monkeypatch.setattr(server, "_cfg_sig", None)+ monkeypatch.setattr(server, "_cfg_path", None)+ assert server._load_cfg_raw() == {} # absent: cached as "no config"++ cfg.write_text("display:\n skin: mono\nmodel:\n default: keep-me\n", encoding="utf-8")++ def denied(path):+ raise PermissionError(13, "Permission denied", str(path))++ monkeypatch.setattr(config_backend, "config_version", denied)+ assert isinstance(server._load_cfg_raw(), FailedConfigRead)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex cf1aa513c0f..096e6002fcb 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -998,12 +998,15 @@ def _load_cfg_raw() -> dict:expansion applied here would be persisted on the next save). Behavioral reads use :func:`_load_cfg`.Cache keyed on the resolved path so profiles don't clobber."""global _cfg_cache, _cfg_sig, _cfg_path- from hermes_cli.config_backend import config_exists, config_version_or_none+ from hermes_cli.config_backend import config_exists, config_versionfrom hermes_cli.config import read_user_config_rawfrom hermes_cli.config_read_errors import FailedConfigReadtry:p = _active_config_path()- sig = config_version_or_none(p)+ try:+ sig = config_version(p)+ except FileNotFoundError: # absent; any other stat error is a failed read, never "no config"+ sig = Nonewith _cfg_lock:if _cfg_cache is not None and _cfg_sig == sig and _cfg_path == p:return copy.deepcopy(_cfg_cache)