The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(cli): stop per-keystroke config re-reads in slash completers
spfcraze473490a2e97a
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.pyindex a0c94bbe47e..21c2ec9a9f1 100644--- a/hermes_cli/commands.py+++ b/hermes_cli/commands.py@@ -18,11 +18,51 @@ import subprocessimport timefrom collections.abc import Callable, Mappingfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Dict, Optional, Tuplefrom utils import is_truthy_valuefrom hermes_constants import INDICATOR_STYLES+# mtime-keyed memo of the /personality completion source. load_cli_config()+# does a full YAML parse + deep merge of the built-in defaults on every call,+# and the completer runs on every keystroke of /personality. The personalities+# list only changes when the config file changes on disk, so keying on+# path+mtime keeps the memo freshness-correct (same pattern as load_env and+# _nous_auth_status_cache). Falls back to a fresh load when the file cannot+# be stat'ed.+_personalities_memo: Optional[+ Tuple[Tuple[Optional[str], Optional[int], Optional[int]], Dict[str, Any]]+] = None+++def _personalities_from_cli_config() -> Dict[str, Any]:+ """Return the available personalities map, memoised on config mtime.++ Wraps ``available_personalities(load_cli_config())`` — the single owner of+ built-ins + user overrides. Built-ins are static for the process lifetime,+ so keying on the config file's path+mtime+size keeps the memo+ freshness-correct.+ """+ global _personalities_memo+ from cli import load_cli_config+ from hermes_cli.personality import available_personalities++ try:+ from hermes_cli.config import get_config_path++ cfg_path = get_config_path()+ st = cfg_path.stat()+ sig = (str(cfg_path), st.st_mtime_ns, st.st_size)+ except Exception:+ sig = (None, None, None)++ if _personalities_memo is not None and _personalities_memo[0] == sig:+ return _personalities_memo[1]++ personalities = available_personalities(load_cli_config())+ _personalities_memo = (sig, personalities)+ return personalities+logger = logging.getLogger(__name__)# prompt_toolkit is an optional CLI dependency — only needed for@@ -1943,14 +1983,19 @@ class SlashCommandCompleter(Completer):already = set(parts[1:] if trailing_space else parts[1:-1])try:- from hermes_cli.config import load_config+ from hermes_cli.config import load_config_readonlyfrom hermes_cli.tools_config import (CONFIGURABLE_TOOLSETS,_get_platform_tools,_get_plugin_toolset_keys,)- config = load_config()+ # Read-only path: the completer only inspects the config (toolset+ # enable state + MCP server names) — it never mutates it. Use the+ # readonly loader so the per-keystroke completion doesn't pay the+ # defensive deepcopy (perf(agent) #74322 converted 29 call sites+ # to the readonly loader; this per-keystroke site was missed).+ config = load_config_readonly()enabled = _get_platform_tools(config, "cli", include_default_mcp_servers=False)for ts_key, label, _desc in CONFIGURABLE_TOOLSETS:@@ -2047,7 +2092,13 @@ class SlashCommandCompleter(Completer):describe_personality,)- personalities = available_personalities(load_cli_config())+ # mtime-keyed memo: load_cli_config() does a full YAML parse + deep+ # merge of the built-in defaults on every call, and this completer+ # runs on every keystroke of /personality. The personalities list+ # only changes when config.yaml changes on disk, so the memo stays+ # freshness-correct (same pattern as load_env / _nous_auth_status_cache).+ personalities = _personalities_from_cli_config()+if "none".startswith(sub_lower) and "none" != sub_lower:yield Completion("none",diff --git a/tests/hermes_cli/test_completer_config_reads.py b/tests/hermes_cli/test_completer_config_reads.pynew file mode 100644index 00000000000..3318f44ae57--- /dev/null+++ b/tests/hermes_cli/test_completer_config_reads.py@@ -0,0 +1,135 @@+"""Measured-work pins for the slash-completer config reads.++The /tools and /personality completers run on every keystroke while the+user types those commands (complete_while_typing). They used to re-read ++re-parse the full config on every keypress: load_config()'s defensive+deepcopy (~345us tax) in _tools_completions, and load_cli_config()'s full+YAML parse + defaults deep-merge (~110us) in _personality_completions.+These pins hold the per-keystroke cost down:+- _tools_completions uses the read-only loader (no deepcopy).+- _personality_completions memoises the personalities source keyed on the+ config file's mtime, so the parse+merge runs once per config state.+"""++from __future__ import annotations++import os+from unittest.mock import patch++import pytest++import hermes_cli.commands as commands_mod+++def _reset_personalities_memo():+ commands_mod._personalities_memo = None++[email protected](autouse=True)+def _reset_memo():+ _reset_personalities_memo()+ yield+ _reset_personalities_memo()+++class TestToolsCompletionsReadonlyConfig:+ def test_uses_readonly_loader(self):+ """_tools_completions must not pay the defensive deepcopy.++ The completer only reads the config (toolset enable state + MCP+ server names). Using load_config_readonly() skips the ~345us+ deepcopy that load_config() applies on every cache hit — a+ per-keystroke cost while completing /tools enable|disable.+ """+ calls = {"deepcopy": 0, "readonly": 0}++ def counting_deepcopy(*a, **k):+ calls["deepcopy"] += 1+ return {}++ def counting_readonly(*a, **k):+ calls["readonly"] += 1+ return {}++ # The completer imports the loader inside the function, so patch the+ # source module.+ with patch("hermes_cli.config.load_config", counting_deepcopy), \+ patch("hermes_cli.config.load_config_readonly", counting_readonly), \+ patch("hermes_cli.tools_config._get_plugin_toolset_keys", lambda: set()), \+ patch("hermes_cli.tools_config._homeassistant_credentials_present", lambda: False), \+ patch("hermes_cli.tools_config._xai_credentials_present", lambda: False):+ list(commands_mod.SlashCommandCompleter._tools_completions("enable ", "enable "))++ assert calls["readonly"] == 1, "completer should use the readonly loader"+ assert calls["deepcopy"] == 0, (+ "completer must not call the deepcopy loader on a read-only path"+ )+++class TestPersonalityCompletionsMemo:+ def test_load_cli_config_called_once_per_config_state(self, monkeypatch):+ """The /personality completer parses the config once per state.++ load_cli_config() does a full YAML parse + deep merge of the+ built-in defaults; the completer runs on every keystroke. The+ mtime-keyed memo keeps that parse to once per config change.+ """+ calls = {"n": 0}++ def counting_load_cli_config():+ calls["n"] += 1+ return {+ "agent": {+ "personalities": {+ "helpful": "You are helpful.",+ "concise": "You are concise.",+ }+ }+ }++ monkeypatch.setattr(commands_mod, "_personalities_memo", None)+ with patch("cli.load_cli_config", counting_load_cli_config):+ # First call: cache miss -> one parse.+ list(commands_mod.SlashCommandCompleter._personality_completions("hel", "hel"))+ assert calls["n"] == 1, "first call should parse once"++ # Subsequent keystrokes: cache hit -> no re-parse.+ for _ in range(10):+ list(commands_mod.SlashCommandCompleter._personality_completions("hel", "hel"))+ assert calls["n"] == 1, (+ "repeated keystrokes must reuse the memoised personalities, "+ f"got {calls['n']} parses"+ )++ def test_mtime_change_reparses(self, monkeypatch, tmp_path):+ """A config file change on disk invalidates the memo."""+ from pathlib import Path++ cfg_path = tmp_path / "config.yaml"+ cfg_path.write_text(+ "agent:\n personalities:\n helpful: \"v1\"\n",+ encoding="utf-8",+ )+ # Pin an explicit mtime so the change below is a guaranteed mtime_ns+ # bump regardless of filesystem timestamp granularity.+ os.utime(cfg_path, (1_700_000_000, 1_700_000_000))++ calls = {"n": 0}++ def counting_load_cli_config():+ calls["n"] += 1+ return {"agent": {"personalities": {"helpful": "v1"}}}++ def fake_config_path():+ return cfg_path++ monkeypatch.setattr(commands_mod, "_personalities_memo", None)+ with patch("cli.load_cli_config", counting_load_cli_config), \+ patch("hermes_cli.config.get_config_path", fake_config_path):+ list(commands_mod.SlashCommandCompleter._personality_completions("h", "h"))+ assert calls["n"] == 1++ # Bump the file mtime -> memo invalidates -> re-parse once.+ os.utime(cfg_path, (1_800_000_000, 1_800_000_000))+ list(commands_mod.SlashCommandCompleter._personality_completions("h", "h"))+ assert calls["n"] == 2, "config mtime change should re-parse once"