The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(profiles): the listing re-reads a profile's YAML only when that file has changed
John Paul Soliva55a8f42329d4
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 8dd3146654b..a1db417b026 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -566,12 +566,52 @@ def _load_yaml_dict(path: Path) -> Optional[dict]:return data if isinstance(data, dict) else None+# (path, kind) -> (file signature, the small derived value). `list_profiles` re-reads three YAML+# files PER PROFILE, and it is the shared body of `GET /api/profiles` and `profiles.list`, which the+# Bots roster polls every 5s per connection — so an installer-seeded config.yaml (the annotated+# template, ~119KB) was re-parsed for every bot every five seconds to yield the same two strings.+# Only DERIVED values are cached, never a document a caller could write back: the raw readers+# (`read_user_config_raw`, `_load_yaml_dict`) keep their uncached contract. See #117378.+_PROFILE_FILE_CACHE: Dict[tuple, tuple] = {}+_PROFILE_FILE_CACHE_MAX = 512+++def _profile_file_signature(path: Path) -> Optional[tuple]:+ """``(mtime_ns, size, inode)``, or None when the file is absent. The atomic writers rename a+ temp file into place, so a rewrite always lands a new inode even within one mtime tick."""+ try:+ stat = path.stat()+ except OSError:+ return None+ return (stat.st_mtime_ns, stat.st_size, stat.st_ino)+++def _cached_profile_read(path: Path, kind: str, compute):+ """``compute()``'s value, reused while *path* has not changed. A missing file is never cached:+ reading it costs nothing, and one created later must be picked up."""+ signature = _profile_file_signature(path)+ if signature is None:+ return compute()+ key = (str(path), kind)+ cached = _PROFILE_FILE_CACHE.get(key)+ if cached is not None and cached[0] == signature:+ return cached[1]+ value = compute()+ if len(_PROFILE_FILE_CACHE) >= _PROFILE_FILE_CACHE_MAX:+ _PROFILE_FILE_CACHE.clear()+ _PROFILE_FILE_CACHE[key] = (signature, value)+ return value++def _read_distribution_meta(profile_dir: Path) -> tuple:"""``(name, version, source)`` from ``distribution.yaml``; ``(None, None, None)`` if absent."""- data = _load_yaml_dict(profile_dir / "distribution.yaml")- if data is None:- return None, None, None- return data.get("name"), data.get("version"), data.get("source")+ def _read() -> tuple:+ data = _load_yaml_dict(profile_dir / "distribution.yaml")+ if data is None:+ return None, None, None+ return data.get("name"), data.get("version"), data.get("source")++ return _cached_profile_read(profile_dir / "distribution.yaml", "distribution", _read)def _read_config_model(profile_dir: Path) -> tuple:@@ -579,17 +619,21 @@ def _read_config_model(profile_dir: Path) -> tuple:config_path = profile_dir / "config.yaml"if not config_path.exists():return None, None- try:- # load_config() targets the ACTIVE profile's home; read THIS profile's file raw.- from hermes_cli.config import read_user_config_raw- model_cfg = read_user_config_raw(config_path).get("model", {})- if isinstance(model_cfg, str):- return model_cfg, None- if isinstance(model_cfg, dict):- return model_cfg.get("default") or model_cfg.get("model"), model_cfg.get("provider")- except Exception:- pass- return None, None++ def _read() -> tuple:+ try:+ # load_config() targets the ACTIVE profile's home; read THIS profile's file raw.+ from hermes_cli.config import read_user_config_raw+ model_cfg = read_user_config_raw(config_path).get("model", {})+ if isinstance(model_cfg, str):+ return model_cfg, None+ if isinstance(model_cfg, dict):+ return model_cfg.get("default") or model_cfg.get("model"), model_cfg.get("provider")+ except Exception:+ pass+ return None, None++ return _cached_profile_read(config_path, "config-model", _read)def launch_model_seed(source_cfg: dict) -> dict:@@ -740,20 +784,27 @@ def read_profile_meta(profile_dir: Path) -> dict:"""Read ``profile.yaml`` -> ``{description, description_auto, display_name,previous_names}`` (empty defaults when missing/unreadable). Never raises — acorrupt file on one profile must not break ``hermes profile list``."""- data = _load_yaml_dict(profile_dir / "profile.yaml") or {}- ui_meta = data.get("ui_meta")- bot_title = ""- if isinstance(ui_meta, dict):- hermes_bots = ui_meta.get("hermes-bots")- if isinstance(hermes_bots, dict):- bot_title = str(hermes_bots.get("title") or "").strip()- return {- "description": str(data.get("description") or "").strip(),- "description_auto": bool(data.get("description_auto", False)),- "display_name": str(data.get("display_name") or "").strip(),- "bot_title": bot_title,- "previous_names": _clean_previous_names(data.get("previous_names")),- }+ def _read() -> dict:+ data = _load_yaml_dict(profile_dir / "profile.yaml") or {}+ ui_meta = data.get("ui_meta")+ bot_title = ""+ if isinstance(ui_meta, dict):+ hermes_bots = ui_meta.get("hermes-bots")+ if isinstance(hermes_bots, dict):+ bot_title = str(hermes_bots.get("title") or "").strip()+ return {+ "description": str(data.get("description") or "").strip(),+ "description_auto": bool(data.get("description_auto", False)),+ "display_name": str(data.get("display_name") or "").strip(),+ "bot_title": bot_title,+ "previous_names": _clean_previous_names(data.get("previous_names")),+ }++ # A copy per caller (list included): the cached value is shared, and a caller that mutates+ # its result must not poison the next reader.+ meta = dict(_cached_profile_read(profile_dir / "profile.yaml", "profile-meta", _read))+ meta["previous_names"] = list(meta["previous_names"])+ return metadef _clean_previous_names(raw) -> List[str]:diff --git a/tests/hermes_cli/test_profile_listing_cache.py b/tests/hermes_cli/test_profile_listing_cache.pynew file mode 100644index 00000000000..45687771729--- /dev/null+++ b/tests/hermes_cli/test_profile_listing_cache.py@@ -0,0 +1,122 @@+"""``list_profiles`` re-reads a profile's YAML only when that file has changed.++The listing is the shared body of ``GET /api/profiles`` and JSON-RPC ``profiles.list``, which the+Bots roster polls every 5s per connection, and it parsed three YAML files per profile every time —+including an installer-seeded ``config.yaml`` (the annotated template, ~119KB) for two strings.++The memo must be invisible: every edit has to show up on the very next read, or `hermes profile+list` and the roster paint stale names and models. Only derived values are cached — the raw+readers keep their uncached contract, because callers write those documents back.+"""+from __future__ import annotations++from pathlib import Path++import pytest++import hermes_cli.profiles as profiles++[email protected](autouse=True)+def _clear_memo():+ profiles._PROFILE_FILE_CACHE.clear()+ yield+ profiles._PROFILE_FILE_CACHE.clear()+++def profile_dir(tmp_path) -> Path:+ p = tmp_path / "profiles" / "bob"+ p.mkdir(parents=True)+ (p / "config.yaml").write_text("model:\n provider: openai\n default: gpt-4o\n", encoding="utf-8")+ (p / "profile.yaml").write_text("display_name: Bob\ndescription: first\n", encoding="utf-8")+ (p / "distribution.yaml").write_text("name: starter\nversion: 1.0.0\nsource: registry\n", encoding="utf-8")+ return p+++def test_an_edited_config_model_is_seen_on_the_next_read(profile_dir):+ assert profiles._read_config_model(profile_dir) == ("gpt-4o", "openai")++ (profile_dir / "config.yaml").write_text(+ "model:\n provider: anthropic\n default: claude-opus-4.6\n", encoding="utf-8")++ assert profiles._read_config_model(profile_dir) == ("claude-opus-4.6", "anthropic")+++def test_an_edited_profile_meta_is_seen_on_the_next_read(profile_dir):+ assert profiles.read_profile_meta(profile_dir)["display_name"] == "Bob"++ (profile_dir / "profile.yaml").write_text("display_name: Roberta\ndescription: second\n", encoding="utf-8")++ meta = profiles.read_profile_meta(profile_dir)+ assert meta["display_name"] == "Roberta"+ assert meta["description"] == "second"+++def test_an_edited_distribution_is_seen_on_the_next_read(profile_dir):+ assert profiles._read_distribution_meta(profile_dir) == ("starter", "1.0.0", "registry")++ (profile_dir / "distribution.yaml").write_text(+ "name: pro\nversion: 2.0.0\nsource: local\n", encoding="utf-8")++ assert profiles._read_distribution_meta(profile_dir) == ("pro", "2.0.0", "local")+++def test_the_real_writer_round_trips(profile_dir):+ """``write_profile_meta`` renames a temp file into place; the memo must follow the new inode."""+ assert profiles.read_profile_meta(profile_dir)["display_name"] == "Bob"++ profiles.write_profile_meta(profile_dir, display_name="Bobby")++ assert profiles.read_profile_meta(profile_dir)["display_name"] == "Bobby"+++def test_a_missing_file_is_not_cached_and_is_picked_up_when_created(tmp_path):+ bare = tmp_path / "profiles" / "bare"+ bare.mkdir(parents=True)++ assert profiles._read_distribution_meta(bare) == (None, None, None)+ assert not any(key[1] == "distribution" for key in profiles._PROFILE_FILE_CACHE)++ (bare / "distribution.yaml").write_text("name: late\nversion: 9\nsource: registry\n", encoding="utf-8")++ assert profiles._read_distribution_meta(bare) == ("late", 9, "registry")+++def test_mutating_a_returned_meta_does_not_poison_the_next_reader(profile_dir):+ first = profiles.read_profile_meta(profile_dir)+ first["display_name"] = "clobbered"+ first["description"] = "clobbered"++ assert profiles.read_profile_meta(profile_dir)["display_name"] == "Bob"+++def test_an_unchanged_file_is_parsed_once_across_repeated_reads(profile_dir, monkeypatch):+ """The saving itself — the roster poll stops re-parsing files that have not moved."""+ parsed: list = []+ real = profiles._load_yaml_dict++ def _counting(path):+ parsed.append(Path(path).name)+ return real(path)++ monkeypatch.setattr(profiles, "_load_yaml_dict", _counting)++ for _ in range(3):+ profiles.read_profile_meta(profile_dir)+ profiles._read_distribution_meta(profile_dir)++ assert parsed.count("profile.yaml") == 1+ assert parsed.count("distribution.yaml") == 1+++def test_the_raw_config_reader_keeps_its_uncached_contract(profile_dir):+ """``read_user_config_raw`` feeds write-back round-trips, so it must NOT be memoised here."""+ from hermes_cli.config import read_user_config_raw++ config_path = profile_dir / "config.yaml"+ assert read_user_config_raw(config_path)["model"]["provider"] == "openai"++ config_path.write_text("model:\n provider: xai\n default: grok-4.6\n", encoding="utf-8")++ assert read_user_config_raw(config_path)["model"]["provider"] == "xai"