The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(pm): scan the plugin tree once per eviction instead of once per evicted plugin
Charan Rathored7382ef014e7
diff --git a/pm/plugin_eviction.py b/pm/plugin_eviction.pyindex b56cd07f9fb..33187794b6e 100644--- a/pm/plugin_eviction.py+++ b/pm/plugin_eviction.py@@ -77,17 +77,27 @@ def static_verdicts(entries: list[Entry], python_version: str) -> tuple[dict[Patreturn reasons, waiting-def _spellings(name: str) -> set[str]:- """Every spelling a config list may hold for plugin *name* (key, bare leaf, manifest name)."""+def _discover_plugins() -> list | None:+ """One scan of the plugin tree for alias lookup, or None when it cannot be read."""try:- from hermes_cli.plugins_cmd import _plugin_aliases+ from hermes_cli.plugins_cmd import _discover_all_plugins- return _plugin_aliases(name)+ return _discover_all_plugins()except (ImportError, OSError) as exc:# Discovery only adds manifest-name aliases; the key and its bare leaf are always known.# Anything else is a real bug in the plugin tree and should surface, not be hidden.- logger.warning("Could not discover aliases of plugin '%s': %s", name, exc)+ logger.warning("Could not discover plugin aliases: %s", exc)+ return None+++def _spellings(name: str, discovered: list | None) -> set[str]:+ """Every spelling a config list may hold for plugin *name* (key, bare leaf, manifest name).+ *discovered* is the shared scan from :func:`_discover_plugins`; None means the scan failed."""+ if discovered is None:return {name, name.split("/")[-1]}+ from hermes_cli.plugins_cmd import _plugin_aliases++ return _plugin_aliases(name, discovered)def _discard_aliases(names: list, aliases: set[str]) -> None:@@ -110,6 +120,8 @@ class PluginEviction:if plugin_dir.resolve() in reasons:by_home.setdefault(plugins_dir.parent, []).append(name)self.edits: list[tuple[Path, bytes | None, bytes]] = []+ discovered: list | None = None+ scanned = False # scan once for every evicted plugin, and only if an enabled list needs itfor home, names in by_home.items():path = home / "config.yaml"previous = read_bytes_or_none(path)@@ -130,7 +142,9 @@ class PluginEviction:# Keep the two lists consistent: a plugin that is disabled must not stay enabled# under any spelling the loader matches, or `plugins enable` has nothing to repair.if isinstance(enabled, list):- _discard_aliases(enabled, _spellings(name))+ if not scanned:+ discovered, scanned = _discover_plugins(), True+ _discard_aliases(enabled, _spellings(name, discovered))# plugins.disabled does not veto memory.provider; the provider joins the union on its own.if isinstance(memory, dict) and str(memory.get("provider") or "").strip() == name:memory["provider"] = ""diff --git a/tests/pm/test_plugin_eviction_config.py b/tests/pm/test_plugin_eviction_config.pyindex bed274b1718..6b70daf0947 100644--- a/tests/pm/test_plugin_eviction_config.py+++ b/tests/pm/test_plugin_eviction_config.py@@ -15,6 +15,7 @@ from pm.plugin_eviction import PluginEviction, _discard_aliases_REAL_ALIASES = _plugins_cmd._plugin_aliases+_REAL_DISCOVER = _plugins_cmd._discover_all_plugins@pytest.fixture(autouse=True)@@ -22,6 +23,7 @@ def _no_alias_discovery(monkeypatch):"""Alias discovery scans installed plugins; these tests only need key + bare leaf."""import hermes_cli.plugins_cmd as plugins_cmd+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: [])monkeypatch.setattr(plugins_cmd, "_plugin_aliases", lambda key, entries=None: {key, key.split("/")[-1]})monkeypatch.setattr(publication, "selection_snapshot", lambda: {})@@ -159,10 +161,10 @@ def test_discard_aliases_keeps_other_entries_in_order():def test_alias_discovery_failure_from_io_falls_back_and_is_logged(tmp_path, monkeypatch, caplog):import hermes_cli.plugins_cmd as plugins_cmd- def unreadable(key, entries=None):+ def unreadable():raise OSError("tree unreadable")- monkeypatch.setattr(plugins_cmd, "_plugin_aliases", unreadable)+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", unreadable)with caplog.at_level("WARNING", logger="pm.plugin_eviction"):cfg, _ = _evict(tmp_path, ["web/firecrawl"], "plugins:\n enabled: [web/firecrawl, firecrawl, keep]\n")assert cfg["plugins"]["enabled"] == ["keep"]@@ -172,10 +174,10 @@ def test_alias_discovery_failure_from_io_falls_back_and_is_logged(tmp_path, monkdef test_unexpected_alias_discovery_error_is_not_swallowed(tmp_path, monkeypatch):import hermes_cli.plugins_cmd as plugins_cmd- def broken(key, entries=None):+ def broken():raise RuntimeError("half-broken plugin tree")- monkeypatch.setattr(plugins_cmd, "_plugin_aliases", broken)+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", broken)with pytest.raises(RuntimeError, match="half-broken plugin tree"):_evict(tmp_path, ["plug-a"], "plugins:\n enabled: [plug-a]\n")@@ -183,6 +185,7 @@ def test_unexpected_alias_discovery_error_is_not_swallowed(tmp_path, monkeypatchdef test_real_alias_discovery_skips_a_malformed_manifest_and_still_removes_aliases(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.setattr(_plugins_cmd, "_plugin_aliases", _REAL_ALIASES)+ monkeypatch.setattr(_plugins_cmd, "_discover_all_plugins", _REAL_DISCOVER)good = tmp_path / "plugins" / "web" / "firecrawl"good.mkdir(parents=True)(good / "plugin.yaml").write_text("name: web-firecrawl\n", encoding="utf-8")@@ -192,3 +195,23 @@ def test_real_alias_discovery_skips_a_malformed_manifest_and_still_removes_aliascfg, _ = _evict(tmp_path, ["web/firecrawl"],"plugins:\n enabled: [web/firecrawl, web-firecrawl, firecrawl, keep]\n")assert cfg["plugins"]["enabled"] == ["keep"]+++def test_several_evicted_plugins_share_one_plugin_tree_scan(tmp_path, monkeypatch):+ import hermes_cli.plugins_cmd as plugins_cmd++ scans = []+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: scans.append(1) or [])+ cfg, _ = _evict(tmp_path, ["plug-a", "plug-b", "plug-c"],+ "plugins:\n enabled: [plug-a, plug-b, plug-c, keep]\n")+ assert cfg["plugins"]["enabled"] == ["keep"]+ assert len(scans) == 1+++def test_no_tree_scan_when_nothing_is_enabled(tmp_path, monkeypatch):+ import hermes_cli.plugins_cmd as plugins_cmd++ scans = []+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: scans.append(1) or [])+ _evict(tmp_path, ["plug-a"], "plugins:\n disabled: []\n")+ assert scans == []