The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): cache the interactive plugin skill projection
Hermes Agent7ea969be06a6
diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex 8d214d4a72b..10cbb132d5b 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -528,8 +528,61 @@ def get_skill_commands() -> Dict[str, Dict[str, Any]]:return scan_skill_commands()+# Plugin projection cache, keyed on the resolved Hermes home like the filesystem+# scan above (``_plugin_managers_by_home`` in hermes_cli/plugins.py is home-keyed,+# so two profiles never share a registry). The projection re-parses every plugin+# SKILL.md frontmatter and sits on the per-keystroke completion path; without the+# cache each Tab paid full discovery + disk I/O (94 ms measured with 60 plugin+# skills). Invalidate with ``invalidate_plugin_skill_commands()`` (``reload_skills``+# and plugin lifecycle changes route through it); a profile switch self-heals via+# the home tag.+_plugin_skill_commands: Dict[str, Dict[str, Any]] = {}+_plugin_skill_commands_home: Optional[str] = None+++def invalidate_plugin_skill_commands() -> None:+ """Drop the cached plugin skill projection (config or plugin registry changed)."""+ global _plugin_skill_commands, _plugin_skill_commands_home+ with _publish_lock:+ _plugin_skill_commands = {}+ _plugin_skill_commands_home = None++def get_plugin_skill_commands() -> Dict[str, Dict[str, Any]]:- """Project enabled plugin skills into the interactive-only slash namespace."""+ """Project enabled plugin skills into the interactive-only slash namespace.++ Cached on the resolved Hermes home: the projection re-parses every plugin+ SKILL.md and runs discovery, so it must not run per completion RPC. Config+ disable lists (``skills.disabled``, ``plugins.disabled``) are applied to the+ cached snapshot on EVERY call — a config-only disable takes effect without a+ rescan, preserving the live lifecycle behavior the cache replaced. Registry+ changes (enable/install of a plugin) rebuild the projection via+ ``invalidate_plugin_skill_commands()``, which ``reload_skills()`` and every+ plugin activation path call.+ """+ from agent.skill_utils import get_disabled_skill_names+ from hermes_cli.plugins_discovery import _get_disabled_plugins+ from hermes_constants import get_hermes_home+ home = str(get_hermes_home())+ with _publish_lock:+ cached = _plugin_skill_commands+ is_fresh = bool(cached) and _plugin_skill_commands_home == home+ if not is_fresh:+ cached = _scan_plugin_skill_commands()+ disabled = get_disabled_skill_names()+ disabled_plugins = _get_disabled_plugins()+ if not disabled and not disabled_plugins:+ return cached+ return {+ key: info for key, info in cached.items()+ if not (info["name"] in disabled or info["name"].split(":", 1)[1] in disabled+ or info["name"].split(":", 1)[0] in disabled_plugins)+ }+++def _scan_plugin_skill_commands() -> Dict[str, Dict[str, Any]]:+ """Build the plugin skill projection and publish it with its home tag atomically."""+ global _plugin_skill_commands, _plugin_skill_commands_homefrom agent.skill_utils import get_disabled_skill_namesfrom hermes_cli.plugins import discover_plugins, get_plugin_managerfrom hermes_cli.plugins_discovery import _get_disabled_plugins@@ -539,10 +592,10 @@ def get_plugin_skill_commands() -> Dict[str, Dict[str, Any]]:)discover_plugins()- manager = get_plugin_manager()disabled = get_disabled_skill_names()disabled_plugins = _get_disabled_plugins()commands: Dict[str, Dict[str, Any]] = {}+ manager = get_plugin_manager()for metadata in manager.list_plugin_skill_metadata():qualified = str(metadata.get("name") or "").strip()if not qualified or ":" not in qualified or qualified in disabled or qualified.split(":", 1)[1] in disabled:@@ -571,11 +624,16 @@ def get_plugin_skill_commands() -> Dict[str, Dict[str, Any]]:"skill_identifier": qualified, "skill_md_path": str(skill_md),"skill_dir": str(skill_md.parent), "source": "plugin",}+ with _publish_lock:+ _plugin_skill_commands = commands+ from hermes_constants import get_hermes_home+ _plugin_skill_commands_home = str(get_hermes_home())return commandsdef get_interactive_skill_commands() -> Dict[str, Dict[str, Any]]:- """Filesystem skills plus profile-scoped plugin skills; never use for native menus."""+ """Filesystem skills plus profile-scoped plugin skills; never use for+ messaging/native command menus (plugin skills are CLI/TUI/desktop only)."""commands = dict(get_skill_commands())for key, info in get_plugin_skill_commands().items():if key in commands:@@ -605,7 +663,9 @@ def reload_skills() -> Dict[str, Any]:"""Re-scan skill dirs and return a diff of the slash-command map (``added``/ ``removed`` / ``unchanged`` / ``total`` / ``commands``; descriptions are thefull frontmatter field). Does NOT invalidate the skills system-prompt cache:- skills are called by name, so ``/reload-skills`` costs no cache reset."""+ skills are called by name, so ``/reload-skills`` costs no cache reset. The+ plugin projection is rebuilt too, so a plugin enabled/disabled/installed+ since the last scan shows up without a restart."""key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())with _publish_lock:before_commands = _skill_commands_by_key.get(key, {})@@ -615,9 +675,10 @@ def reload_skills() -> Dict[str, Any]:from tools.skills_tool import clear_skills_cacheclear_skills_cache() # the scan reads the shared catalog; an explicit reload must not hit its TTLbefore = command_snapshot(before_commands)+ invalidate_plugin_skill_commands()new_commands = scan_skill_commands()result = diff_command_snapshots(before, command_snapshot(new_commands))- result["commands"] = len(new_commands)+ result["commands"] = len(new_commands) + len(get_plugin_skill_commands())return result@@ -661,10 +722,12 @@ def build_skill_invocation_message(_MAX_STACKED_SKILLS = 5-def split_stacked_skill_commands(rest: str) -> tuple[list[str], str]:+def split_stacked_skill_commands(rest: str, *, interactive: bool = False) -> tuple[list[str], str]:"""Consume further leading ``/skill`` tokens from *rest* (text after the firstmatched command); stops at the first non-skill (or repeated) token, which- starts the user instruction. Returns ``(extra_cmd_keys, remaining_instruction)``."""+ starts the user instruction. Returns ``(extra_cmd_keys, remaining_instruction)``.+ Native callers (messaging gateway) must pass ``interactive=False``: plugin+ skills are interactive-only and must not resolve here."""keys: list[str] = []remaining = rest or ""while len(keys) < _MAX_STACKED_SKILLS - 1:@@ -672,7 +735,7 @@ def split_stacked_skill_commands(rest: str) -> tuple[list[str], str]:if not stripped.startswith("/"):breaktoken, tail = (stripped.split(None, 1) + [""])[:2]- cmd_key = resolve_skill_command_key(token.lstrip("/"), interactive=True)+ cmd_key = resolve_skill_command_key(token.lstrip("/"), interactive=interactive)if cmd_key is None or cmd_key in keys:breakkeys.append(cmd_key)@@ -681,11 +744,17 @@ def split_stacked_skill_commands(rest: str) -> tuple[list[str], str]:def build_stacked_skill_invocation_message(- cmd_keys: list[str], user_instruction: str = "", task_id: str | None = None,+ cmd_keys: list[str], user_instruction: str = "", task_id: str | None = None, *, table: Mapping[str, Any] | None = None,) -> Optional[tuple[str, list[str], list[str]]]:"""Build the user message for a stacked multi-skill slash invocation:- ``(message, loaded_skill_names, missing_skill_names)``, or ``None`` when no skill loaded."""- commands = get_interactive_skill_commands()+ ``(message, loaded_skill_names, missing_skill_names)``, or ``None`` when no skill loaded.++ *table* overrides the default interactive lookup table; the messaging gateway+ passes its filesystem-only map so a stacked token can never load a plugin+ skill (they are interactive-only) and so the per-platform disabled filter+ sees every loaded skill's real name.+ """+ commands = table if table is not None else get_interactive_skill_commands()keys = [k for k in cmd_keys if k]loaded_names, missing, _disabled, skill_blocks = _load_skill_blocks(keys,diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 530074ea5ed..a9ad49573ad 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1397,6 +1397,14 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):self._discovered = Falseraise# Outside the lock: a listener (the gateway's re-wire) may read the registry from another thread.+ # The registry just changed shape (force reload: enable/disable/install): the interactive+ # plugin-skill projection must not keep serving the pre-sweep skill set.+ if force:+ try:+ from agent.skill_commands import invalidate_plugin_skill_commands+ invalidate_plugin_skill_commands()+ except Exception:+ logger.debug("plugin-skill projection invalidation failed", exc_info=True)self._notify_plugin_loaded(loaded_before)def _re_register_config_hooks_after_force(self) -> None:diff --git a/tests/agent/test_plugin_skill_boundary.py b/tests/agent/test_plugin_skill_boundary.pynew file mode 100644index 00000000000..49db2f46b55--- /dev/null+++ b/tests/agent/test_plugin_skill_boundary.py@@ -0,0 +1,164 @@+"""Regression tests for review findings B1/B2 on the plugin-skills-menu feature.++B1 — the plugin skill projection must be cached: repeating an interactive lookup+must not re-read plugin SKILL.md files per call (completion RPCs run it per+keystroke). Invalidation goes through ``invalidate_plugin_skill_commands()``+(``/reload-skills``, plugin enable/install) so a stale registration hint still+loses to fresh frontmatter after a lifecycle change.++B2 — the messaging gateway's stacked skill path is native/filesystem-only:+plugin skills are interactive-only (CLI/TUI/desktop), so neither+``split_stacked_skill_commands`` in native mode nor a loader fed the native map+may resolve a ``/plugin:skill`` token.+"""++import json+from pathlib import Path+from unittest.mock import patch++import pytest++from hermes_cli import plugins+++def _make_plugin_skill(home: Path, plugin_name: str, skill: str, body: str, description: str = "") -> Path:+ """Write a real plugin tree registering one skill and enable it in config."""+ plugin = home / "plugins" / plugin_name+ md = plugin / "skills" / skill / "SKILL.md"+ md.parent.mkdir(parents=True, exist_ok=True)+ (plugin / "plugin.yaml").write_text(f"name: {plugin_name}\nversion: 0.1.0\n")+ (plugin / "__init__.py").write_text(+ "from pathlib import Path\n"+ f"def register(ctx):\n"+ f" ctx.register_skill({skill!r}, Path(__file__).parent / 'skills' / {skill!r} / 'SKILL.md')\n"+ )+ desc_line = f"description: {description}\n" if description else ""+ md.write_text(f"---\nname: {skill}\n{desc_line}---\n{body}\n")+ config = home / "config.yaml"+ enabled = plugin_name+ if config.exists():+ text = config.read_text()+ enabled = f"{text.rstrip().rsplit('[', 1)[0].rstrip().rstrip(',')}, {plugin_name}" if False else enabled+ config.write_text(f"plugins:\n enabled: [{plugin_name}]\n")+ return md+++def plugin_home(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ (home / "config.yaml").write_text("plugins:\n enabled: []\n")+ monkeypatch.setenv("HERMES_HOME", str(home))+ plugins._reset_plugin_managers_for_tests()+ try:+ yield home+ finally:+ plugins._reset_plugin_managers_for_tests()+++class TestProjectionCache:+ def test_repeat_lookup_does_not_reread_plugin_skill_files(self, plugin_home):+ """B1: a cached interactive lookup must not touch plugin SKILL.md again."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "cache-probe", "guide", "Body.")+ first = sc.get_interactive_skill_commands()+ assert "/cache-probe:guide" in first+ reads = []+ real_read_text = Path.read_text++ def counting_read_text(self, *args, **kwargs):+ if self.name == "SKILL.md" and "cache-probe" in str(self):+ reads.append(self)+ return real_read_text(self, *args, **kwargs)++ with patch.object(Path, "read_text", counting_read_text):+ second = sc.get_interactive_skill_commands()+ assert second == first+ assert reads == []++ def test_invalidate_rebuilds_projection_with_fresh_frontmatter(self, plugin_home):+ """A changed description must reach the palette only after invalidation+ (the cache serves the last built projection until then)."""+ import agent.skill_commands as sc++ md = _make_plugin_skill(plugin_home, "fresh-probe", "guide", "Body.", "Old")+ assert sc.get_interactive_skill_commands()["/fresh-probe:guide"]["description"] == "Old"+ md.write_text("---\nname: guide\ndescription: New\n---\nBody.\n")+ assert sc.get_interactive_skill_commands()["/fresh-probe:guide"]["description"] == "Old"+ sc.invalidate_plugin_skill_commands()+ assert sc.get_interactive_skill_commands()["/fresh-probe:guide"]["description"] == "New"++ def test_profile_switch_self_heals_without_invalidation(self, plugin_home, tmp_path, monkeypatch):+ """The cache is keyed on the resolved home: switching profiles must never+ serve the other profile's plugin skills."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "profile-a", "guide", "Body from A.")+ assert "/profile-a:guide" in sc.get_interactive_skill_commands()++ other = tmp_path / "home-b"+ other.mkdir()+ (other / "config.yaml").write_text("plugins:\n enabled: []\n")+ monkeypatch.setenv("HERMES_HOME", str(other))+ plugins._reset_plugin_managers_for_tests()+ try:+ commands = sc.get_interactive_skill_commands()+ assert "/profile-a:guide" not in commands+ finally:+ monkeypatch.setenv("HERMES_HOME", str(plugin_home))+ plugins._reset_plugin_managers_for_tests()+ assert "/profile-a:guide" in sc.get_interactive_skill_commands()++ def test_reload_skills_counts_plugin_skills_and_refreshes_registry(self, plugin_home):+ """/reload-skills must rebuild the plugin projection so a plugin enabled+ since the last lookup appears, and the receipt must count it."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "reload-probe", "guide", "Body.")+ config = plugin_home / "config.yaml"+ config.write_text("plugins:\n enabled: []\n")+ first = sc.get_interactive_skill_commands()+ assert "/reload-probe:guide" not in first # not enabled yet++ config.write_text("plugins:\n enabled: [reload-probe]\n")+ plugins.discover_plugins(force=True)+ result = sc.reload_skills()+ assert "/reload-probe:guide" in sc.get_plugin_skill_commands()+ assert result["commands"] == len(sc.get_skill_commands()) + 1+++class TestNativeStackedBoundary:+ def test_split_native_mode_never_resolves_plugin_skill_token(self, plugin_home):+ """B2: the messaging gateway's token scan must stay filesystem-only."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "boundary-probe", "guide", "Body.")+ assert "/boundary-probe:guide" in sc.get_interactive_skill_commands()+ keys, instruction = sc.split_stacked_skill_commands("/boundary-probe:guide do it")+ assert keys == []+ assert instruction == "/boundary-probe:guide do it"+ interactive_keys, _ = sc.split_stacked_skill_commands("/boundary-probe:guide do it", interactive=True)+ assert interactive_keys == ["/boundary-probe:guide"]++ def test_stacked_loader_with_native_table_refuses_plugin_skill(self, plugin_home):+ """The gateway loader is fed its native map: a leaked plugin-skill key+ must load nothing (missing), never the plugin body."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "boundary-probe", "guide", "Plugin body.")+ assert sc.build_skill_invocation_message("/boundary-probe:guide", "go") is not None++ result = sc.build_stacked_skill_invocation_message(+ ["/boundary-probe:guide"], "go", table=sc.get_skill_commands(),+ )+ assert result is None++ def test_stacked_loader_defaults_to_interactive_table(self, plugin_home):+ """CLI/TUI callers keep the interactive default: a plugin skill loads."""+ import agent.skill_commands as sc++ _make_plugin_skill(plugin_home, "boundary-probe", "guide", "Plugin body.")+ result = sc.build_stacked_skill_invocation_message(["/boundary-probe:guide"], "go")+ assert result is not None+ assert result[1] == ["boundary-probe:guide"]