Files
hermes-agent/hermes_cli/config_backend.py
Teknium 749cb638ff fix(config): an unreadable config never serves the TUI's cached empty config; review fixes
- tui_gateway _load_cfg_raw: only FileNotFoundError means "no config".
  config_version_or_none folded every stat error into None, so after a
  cached absent config a transient EACCES matched the cached {} and the
  next config.set could save it over the now-existing file. Any other
  stat error is a FailedConfigRead again, which _save_cfg refuses.
- ConfigBackend.read_user_doc replaces read_user_layer/UserLayer: no
  caller used the version it stat'ed on every uncached read; cached
  loaders already ask config_version first.
- Reader lint scopes follow Python: a self.<attr> bound in one method is
  seen by every method of the class, and a comprehension's target no
  longer leaks into the enclosing function. The class rule found
  pm/publication.py's compare-and-swap re-read of self.path, now marked
  like its twin in __init__.
2026-10-25 18:54:09 -07:00

217 lines
8.4 KiB
Python

"""Where the user config layer lives: the ``ConfigBackend`` seam (config-config design §4.1, D10).
Every read and write of a profile's user ``config.yaml`` goes through the backend returned by
:func:`get_config_backend` (``scripts/check_config_yaml_readers.py`` and
``scripts/check_config_yaml_writers.py`` reject direct file access elsewhere). The key per call is
the hermes home (profile): one multiplexed process serves N profiles, and every config cache
already keys on the config path, so a backend keeps per-home state.
:class:`FileBackend` is the only backend and is today's behaviour byte for byte:
the version is the ``file_signature`` stat tuple, reads are ``open`` + ``fast_safe_load`` and raise
exactly what those raise (``FileNotFoundError`` for an absent file, ``OSError``, YAML errors), and
writes are the ruamel round-trip writers in ``utils``. Callers keep their own error handling, so a
backend whose layer always exists simply never takes the "no file" branches.
The managed scope (``/etc/hermes``) is NOT a backend concern: it stays an overlay applied on top of
whatever user layer the backend returns.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Mapping, Optional, Protocol, Union, runtime_checkable
CONFIG_FILENAME = "config.yaml"
PathLike = Union[str, "os.PathLike[str]"]
@dataclass(frozen=True)
class Changes:
"""A write to one profile's user layer.
``document`` replaces the whole user-layer document (``atomic_config_write``: the file backend
merges it onto the on-disk document, comment-preserving); ``set`` / ``unset`` are single dotted
keys (``atomic_roundtrip_yaml_update`` semantics). A backend applies ``document`` first.
"""
document: Optional[dict] = None
set: Mapping[str, Any] = field(default_factory=dict)
unset: tuple[str, ...] = ()
extra_content_on_create: Optional[str] = None
@runtime_checkable
class ConfigBackend(Protocol):
name: str
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_doc(home)`` re-read only when ``version`` changes; never mutate it."""
...
def version(self, home: Path) -> tuple[Any, ...]:
"""Cheap cache signature; changes whenever the user layer does."""
...
def exists(self, home: Path) -> bool: ...
def probe_readable(self, home: Path) -> None:
"""Raise ``OSError`` while the user layer cannot be read; no parse."""
...
def write_changes(self, home: Path, changes: Changes) -> None: ...
class FileBackend:
"""The user layer is ``<home>/config.yaml`` on local disk."""
name = "file"
# Path-level primitives: the file backend's whole behaviour, also used for explicit files
# that are not a home's config.yaml (see ``_route``).
@staticmethod
def version_path(path: Path) -> tuple[int, int, int, int]:
st = path.stat() # before the import: a missing file must not need the utils stack (PM runtime)
from utils import file_signature
return file_signature(st)
@staticmethod
def read_path(path: Path) -> Any:
from utils import fast_safe_load
with open(path, encoding="utf-8-sig") as f:
return fast_safe_load(f)
@staticmethod
def read_path_readonly(path: Path) -> Any:
from utils import load_yaml_file_readonly
return load_yaml_file_readonly(path)
@staticmethod
def write_path(path: Path, changes: Changes) -> None:
from utils import atomic_roundtrip_yaml_save, atomic_roundtrip_yaml_update
if changes.document is not None:
atomic_roundtrip_yaml_save(path, changes.document, extra_content_on_create=changes.extra_content_on_create)
for key, value in changes.set.items():
atomic_roundtrip_yaml_update(path, key, value)
for key in changes.unset:
atomic_roundtrip_yaml_update(path, key, None)
def config_path(self, home: Path) -> Path:
return Path(home) / CONFIG_FILENAME
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))
def version(self, home: Path) -> tuple[int, int, int, int]:
return self.version_path(self.config_path(home))
def exists(self, home: Path) -> bool:
return self.config_path(home).exists()
def probe_readable(self, home: Path) -> None:
path = self.config_path(home)
with open(path, "rb") as f:
f.read(1)
def write_changes(self, home: Path, changes: Changes) -> None:
self.write_path(self.config_path(home), changes)
_FILE_BACKEND = FileBackend()
def get_config_backend() -> ConfigBackend:
"""The backend serving every home's user layer: the file backend, the only one there is."""
return _FILE_BACKEND
class _ExplicitFile(FileBackend):
"""A config file that is not a home's user layer (a test fixture, an import source): the file
backend's behaviour on that exact path, whichever backend is selected."""
def __init__(self, path: Path):
self._path = path
def config_path(self, home: Path) -> Path:
return self._path
def _route(config_path: PathLike) -> tuple[ConfigBackend, Path]:
"""``(backend, home)`` serving a config path through the one ``ConfigBackend`` surface.
``<home>/config.yaml`` is that home's user layer and goes to the selected backend. Any other
file name is an explicit file, served by the file backend on that path.
"""
path = Path(config_path)
if path.name == CONFIG_FILENAME:
return get_config_backend(), path.parent
return _ExplicitFile(path), path.parent
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_doc(home)
def read_config_doc_readonly(config_path: PathLike) -> Any:
"""Signature-cached :func:`read_config_doc`; the result is shared — never mutate it."""
backend, home = _route(config_path)
return backend.read_user_doc_readonly(home)
def config_version(config_path: PathLike) -> tuple[Any, ...]:
"""Cache signature of a config file; raises ``FileNotFoundError`` / ``OSError`` like ``stat``."""
backend, home = _route(config_path)
return backend.version(home)
def config_version_or_none(config_path: PathLike) -> Optional[tuple[Any, ...]]:
""":func:`config_version`, or None when the config is absent or cannot be stat'ed."""
try:
return config_version(config_path)
except OSError:
return None
def version_token(version: Optional[tuple[Any, ...]]) -> float:
"""A number that changes with a backend ``version`` (0 = no config), for clients that only
compare successive values: the file backend's version leads with ``st_mtime_ns``, kept as seconds.
Any other int-led version is scaled the same way, which is fine: only changes are compared."""
if not version:
return 0
if isinstance(version[0], int):
return version[0] / 1_000_000_000
import zlib
return float(zlib.crc32(repr(version).encode("utf-8")) or 1)
def probe_config_readable(config_path: PathLike) -> None:
"""Raise ``OSError`` while a config file cannot be read; no parse."""
backend, home = _route(config_path)
backend.probe_readable(home)
def config_exists(config_path: PathLike) -> bool:
backend, home = _route(config_path)
return backend.exists(home)
def write_config_document(config_path: PathLike, document: dict, *, extra_content_on_create: Optional[str] = None) -> None:
"""Replace a config file's document (comment-preserving merge for the file backend)."""
backend, home = _route(config_path)
backend.write_changes(home, Changes(document=document, extra_content_on_create=extra_content_on_create))
def write_config_key(config_path: PathLike, key_path: str, value: Any) -> None:
"""Set one dotted key (``None`` removes it) — ``atomic_roundtrip_yaml_update`` semantics."""
backend, home = _route(config_path)
backend.write_changes(home, Changes(unset=(key_path,)) if value is None else Changes(set={key_path: value}))