The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): refuse checkout mutations while the gateway is live
Austin Pickett0f0b0a12aa52
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex ba3950ae51a..d5960222af3 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -119,6 +119,43 @@ def _table(columns, **kwargs):return table+RUNNING_GATEWAY_PLUGIN_MUTATION_ERROR = (+ "the messaging gateway is running and its loaded plugin callbacks import from the "+ "installed checkouts. Run `hermes gateway stop`, apply the change, then `hermes gateway "+ "start`. To skip this check pass --allow-live-gateway (callbacks may fail until restart)."+)+++def _gateway_is_running() -> bool:+ """Is the active profile's gateway live? Same liveness read as the dashboard status+ surfaces (``resolve_gateway_liveness``), never mutating the profile's identity files."""+ from hermes_cli.profiles import _check_gateway_running++ try:+ return _check_gateway_running(get_hermes_home())+ except Exception:+ # A failed probe must not strand an uninstallable plugin (issue #70473's fix may not+ # become its own lock-out); treat unknown liveness as not running.+ logger.exception("gateway liveness probe failed; proceeding without the live-gateway guard")+ return False+++def _refuse_live_gateway_mutation(action: str, *, allow_live_gateway: bool = False) -> None:+ """Fail before any mutating git operation on an installed plugin (#70473).++ Pulling, re-cloning or deleting a checkout under a running gateway breaks its+ already-loaded plugin callbacks (a deferred relative import hits files the+ operation just removed). *action* names the refusal ("update", "remove", ...).+ """+ if allow_live_gateway:+ return+ if _gateway_is_running():+ raise PluginOperationError(+ f"Cannot {action} plugin files while {RUNNING_GATEWAY_PLUGIN_MUTATION_ERROR}",+ failure_class="already_installed",+ )++def _is_tty() -> bool:return sys.stdin.isatty() and sys.stdout.isatty()@@ -1003,20 +1040,21 @@ _PLUGIN_ACTIONS = {ref=getattr(args, "ref", None),allow_removed=getattr(args, "allow_removed", False),no_deps=getattr(args, "no_deps", False),- yes_deps=getattr(args, "yes_deps", False)),+ yes_deps=getattr(args, "yes_deps", False),+ allow_live_gateway=getattr(args, "allow_live_gateway", False)),"search": lambda args: _catalog().cmd_search(getattr(args, "term", "") or "", json_output=getattr(args, "json", False)),"browse": lambda args: _catalog().cmd_search(""),"validate": lambda args: _catalog().cmd_validate(args.path, as_json=getattr(args, "json", False), install_deps=getattr(args, "install_deps", False)),- "update": lambda args: cmd_update(args.name),+ "update": lambda args: cmd_update(args.name, allow_live_gateway=getattr(args, "allow_live_gateway", False)),"adopt": lambda args: cmd_adopt(args.name),"trust-update-url": lambda args: cmd_trust_update_url(args.name),"check-updates": lambda args: cmd_check_updates(args),"check": lambda args: cmd_check_updates(args),- "remove": lambda args: cmd_remove(args.name),- "rm": lambda args: cmd_remove(args.name),- "uninstall": lambda args: cmd_remove(args.name),+ "remove": lambda args: cmd_remove(args.name, allow_live_gateway=getattr(args, "allow_live_gateway", False)),+ "rm": lambda args: cmd_remove(args.name, allow_live_gateway=getattr(args, "allow_live_gateway", False)),+ "uninstall": lambda args: cmd_remove(args.name, allow_live_gateway=getattr(args, "allow_live_gateway", False)),"enable": lambda args: cmd_enable(args.name,allow_tool_override=_tri_state_flag(args, "allow_tool_override", "no_allow_tool_override")),diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.pyindex 50283240c50..e6c58e6c8d6 100644--- a/hermes_cli/plugins_cmd_install.py+++ b/hermes_cli/plugins_cmd_install.py@@ -530,6 +530,7 @@ def cmd_install(allow_removed: bool = False,no_deps: bool = False,yes_deps: bool = False,+ allow_live_gateway: bool = False,) -> None:"""Install a plugin from the curated catalog (bare name), a Git URL, or owner/repo shorthand.@@ -559,6 +560,10 @@ def cmd_install("This plugin may have been removed for security reasons.[/red]")try:+ if force:+ # `install --force` over an existing install replaces its code in place — the same+ # destructive mutation of a loaded checkout that `update` is (#70473).+ _pc()._refuse_live_gateway_mutation("reinstall", allow_live_gateway=allow_live_gateway)git_url, _subdir = _pc()._resolve_git_url(identifier)if not allow_removed:catalog.raise_if_removed(identifier, git_url, *((entry.name,) if entry else ()))diff --git a/hermes_cli/plugins_cmd_remove.py b/hermes_cli/plugins_cmd_remove.pyindex 90ee86e8334..d7b620bd6a5 100644--- a/hermes_cli/plugins_cmd_remove.py+++ b/hermes_cli/plugins_cmd_remove.py@@ -42,13 +42,13 @@ def _remove_plugin_core(target: Path) -> None:_pc().rmtree_readonly(staging)-def cmd_remove(name: str) -> None:+def cmd_remove(name: str, *, allow_live_gateway: bool = False) -> None:"""Remove an installed plugin by name."""console = _pc()._console()plugins_dir = _pc()._plugins_dir()target = _pc()._require_installed_plugin(name, plugins_dir, console)try:- result = _remove_user_plugin(plugins_dir, name, target)+ result = _remove_user_plugin(plugins_dir, name, target, allow_live_gateway=allow_live_gateway)except (OSError, _pc().PluginOperationError) as exc:_pc()._fail(console, f"[red]Error:[/red] Could not remove plugin '{name}': {exc}")console.print()@@ -59,7 +59,7 @@ def cmd_remove(name: str) -> None:console.print()-def _remove_user_plugin(plugins_dir: Path, name: str, target: Path) -> dict[str, Any]:+def _remove_user_plugin(plugins_dir: Path, name: str, target: Path, *, allow_live_gateway: bool = False) -> dict[str, Any]:"""Shared ``remove`` tail for the CLI, the dashboard and the ``plugins.manage`` RPC.*target* is the resolved directory; when ``plugins_dir/name`` itself is a symlink only the link@@ -67,6 +67,7 @@ def _remove_user_plugin(plugins_dir: Path, name: str, target: Path) -> dict[str,and following it deleted that plugin plus its install metadata while the alias stayed dangling.Config bookkeeping (aliases, toolset) is gathered before the tree disappears."""+ _pc()._refuse_live_gateway_mutation("remove", allow_live_gateway=allow_live_gateway)link = plugins_dir / name.strip("/")if link.is_symlink():link.unlink()diff --git a/hermes_cli/plugins_cmd_update.py b/hermes_cli/plugins_cmd_update.pyindex 8ea12530e2e..3c8c8a0411d 100644--- a/hermes_cli/plugins_cmd_update.py+++ b/hermes_cli/plugins_cmd_update.py@@ -67,7 +67,7 @@ def _reclone_plugin_update(target: Path, source: str, previous_revision: object)return f"Re-installed from {source}: {previous[:8]}..{revision[:8]}"-def cmd_update(name: str, *, interactive: bool = True) -> None:+def cmd_update(name: str, *, interactive: bool = True, allow_live_gateway: bool = False) -> None:"""Update an installed plugin by pulling latest from its git remote."""from rich.markup import escapefrom hermes_cli import plugins_cmd_catalog as catalog@@ -78,6 +78,7 @@ def cmd_update(name: str, *, interactive: bool = True) -> None:catalog.cmd_update_catalog(name, target, sidecar, console, interactive=interactive)returntry:+ _pc()._refuse_live_gateway_mutation("update", allow_live_gateway=allow_live_gateway)output = _pull_plugin_update(target,lambda rec: (@@ -282,6 +283,7 @@ def dashboard_update_user_plugin(name: str, *, accept_capabilities: bool = Falsereturn {"ok": False, "error": f"Plugin '{name}' was not found under {_pc()._plugins_dir()}."}sidecar = catalog.catalog_install_record(target)try:+ _pc()._refuse_live_gateway_mutation("update")if sidecar:result = catalog.repin_catalog_plugin(target, sidecar, consent_cb=(lambda _delta: True) if accept_capabilities else None)diff --git a/hermes_cli/subcommands/plugins.py b/hermes_cli/subcommands/plugins.pyindex fe703ee56ee..1814209ad6f 100644--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@ -30,6 +30,10 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:plugins_install.add_argument("--allow-removed", action="store_true",help="DANGEROUS: bypass the catalog removed-plugin blocklist check")+ plugins_install.add_argument(+ "--allow-live-gateway", action="store_true",+ help="DANGEROUS: allow a forced reinstall while the messaging gateway is running "+ "(loaded plugin callbacks may break until it restarts)")_install_deps_group = plugins_install.add_mutually_exclusive_group()_install_deps_group.add_argument("--no-deps", action="store_true",@@ -68,6 +72,10 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:plugins_update = plugins_subparsers.add_parser("update", help="Pull latest changes for an installed plugin")plugins_update.add_argument("name", help="Plugin name to update")+ plugins_update.add_argument(+ "--allow-live-gateway", action="store_true",+ help="DANGEROUS: update while the messaging gateway is running "+ "(loaded plugin callbacks may break until it restarts)")plugins_adopt = plugins_subparsers.add_parser("adopt",@@ -113,6 +121,10 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:plugins_remove = plugins_subparsers.add_parser("remove", aliases=["rm", "uninstall"], help="Remove an installed plugin")plugins_remove.add_argument("name", help="Plugin directory name to remove")+ plugins_remove.add_argument(+ "--allow-live-gateway", action="store_true",+ help="DANGEROUS: remove while the messaging gateway is running "+ "(loaded plugin callbacks may break until it restarts)")plugins_list = plugins_subparsers.add_parser("list", aliases=["ls"], help="List installed plugins")diff --git a/tests/hermes_cli/test_plugin_live_gateway_guard.py b/tests/hermes_cli/test_plugin_live_gateway_guard.pynew file mode 100644index 00000000000..f3c44931b70--- /dev/null+++ b/tests/hermes_cli/test_plugin_live_gateway_guard.py@@ -0,0 +1,194 @@+"""Mutating plugin verbs refuse while a REAL gateway-shaped lock holder is live (#70473).++``hermes plugins update`` / ``install --force`` / ``remove`` (and the dashboard twins)+mutate an installed checkout in place. A running gateway has already loaded that+plugin's callbacks, so a pull that deletes a lazily-imported module breaks the next+tool call even though the command reported success. The verbs must fail BEFORE any+git operation when the gateway is live, and keep working when it is not.++The holder is a real child process holding ``gateway.lock`` through+``acquire_gateway_runtime_lock`` with a gateway-shaped command line, so the guard+exercises the platform's actual liveness probe (``resolve_gateway_liveness``), not a+stub — the same fixture shape as ``tests/gateway/test_status_strict_identity_live.py``.+"""++from __future__ import annotations++import queue+import os+import subprocess+import sys+import threading+from contextlib import suppress+from pathlib import Path++import psutil+import pytest++from hermes_cli import plugins_cmd+from hermes_cli import plugins_cmd_update++PROJECT_ROOT = Path(__file__).resolve().parents[2]++# Blocks on stdin: exits as soon as the parent's pipe closes, even when pytest is+# killed and teardown never runs.+_HOLDER = """+import os, sys+sys.path.insert(0, {root!r})+from gateway import status+if not status.acquire_gateway_runtime_lock():+ sys.exit("could not acquire gateway.lock")+status.write_pid_file()+print(os.getpid(), flush=True)+sys.stdin.read()+"""+++def _readline(stream, timeout: float = 20.0) -> str:+ got: queue.Queue = queue.Queue()+ threading.Thread(target=lambda: got.put(stream.readline()), daemon=True).start()+ try:+ return got.get(timeout=timeout)+ except queue.Empty:+ return ""++[email protected](scope="module")+def live_gateway_home(tmp_path_factory):+ """A temp HERMES_HOME whose gateway identity files name a real live holder."""+ root = tmp_path_factory.mktemp("plugin-live-gateway")+ home = root / "home"+ (home / "plugins").mkdir(parents=True)+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")+ script = root / "bin" / "hermes"+ script.parent.mkdir(parents=True, exist_ok=True)+ script.write_text(_HOLDER.format(root=str(PROJECT_ROOT)), encoding="utf-8")+ proc = subprocess.Popen(+ [sys.executable, str(script), "gateway", "run"],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,+ env={**os.environ, "HERMES_HOME": str(home)},+ )+ line = _readline(proc.stdout).strip()+ if not line.isdigit():+ with suppress(Exception):+ proc.kill()+ pytest.fail(f"lock holder failed to start: {line!r} {proc.communicate(timeout=10)[1]}")+ yield home+ holder = None+ with suppress(psutil.Error):+ holder = psutil.Process(int(line))+ for target in ([holder] if holder else []) + [psutil.Process(proc.pid)]:+ with suppress(psutil.Error):+ target.kill()+ with suppress(Exception):+ proc.communicate(timeout=10)+++def plugin_home(live_gateway_home, monkeypatch):+ """The holder's home with one git-installed plugin; HERMES_HOME points there."""+ monkeypatch.setenv("HERMES_HOME", str(live_gateway_home))+ target = live_gateway_home / "plugins" / "git-plugin"+ (target / ".git").mkdir(parents=True, exist_ok=True)+ (target / "plugin.yaml").write_text("name: git-plugin\nversion: '1.0'\n", encoding="utf-8")+ (target / "__init__.py").write_text("def register(ctx):\n pass\n", encoding="utf-8")+ (live_gateway_home / "plugins" / ".install-metadata.json").write_text("{}", encoding="utf-8")+ return live_gateway_home+++def stopped_home(tmp_path, monkeypatch):+ """A home with no gateway at all — stopped-gateway behaviour must be unchanged."""+ home = tmp_path / "home"+ (home / "plugins").mkdir(parents=True)+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home++[email protected]_gateway_lookalike+class TestLiveGatewayGuard:+ def test_probe_reports_the_holder_live(self, plugin_home):+ """The integration fixture really is 'running' by the guard's own probe."""+ assert plugins_cmd._gateway_is_running() is True++ def test_cmd_update_refuses_before_git_with_a_live_gateway(self, plugin_home, monkeypatch):+ pulled = []+ monkeypatch.setattr(plugins_cmd_update, "_pull_plugin_update",+ lambda *a, **k: pulled.append(1) or "Already up to date.")++ with pytest.raises(SystemExit) as exc:+ plugins_cmd.cmd_update("git-plugin")++ assert exc.value.code == 1+ assert pulled == [] # refused BEFORE any git mutation++ def test_cmd_update_override_flag_proceeds(self, plugin_home, monkeypatch):+ pulled = []+ monkeypatch.setattr(plugins_cmd_update, "_pull_plugin_update",+ lambda *a, **k: pulled.append(1) or "Already up to date.")++ plugins_cmd.cmd_update("git-plugin", allow_live_gateway=True)++ assert pulled == [1]++ def test_dashboard_update_refuses_with_clear_message(self, plugin_home, monkeypatch):+ pulled = []+ monkeypatch.setattr(plugins_cmd_update, "_pull_plugin_update",+ lambda *a, **k: pulled.append(1) or "Already up to date.")++ result = plugins_cmd.dashboard_update_user_plugin("git-plugin")++ assert result["ok"] is False+ assert "gateway is running" in result["error"]+ assert "hermes gateway stop" in result["error"]+ assert pulled == []++ def test_dashboard_remove_refuses_and_keeps_the_tree(self, plugin_home):+ result = plugins_cmd.dashboard_remove_user_plugin("git-plugin")++ assert result["ok"] is False+ assert "gateway is running" in result["error"]+ assert (plugin_home / "plugins" / "git-plugin" / "plugin.yaml").exists()++ def test_force_reinstall_refuses(self, plugin_home, monkeypatch):+ installed = []+ monkeypatch.setattr(plugins_cmd, "_install_plugin_core",+ lambda *a, **k: installed.append(1) or (None, {}, "git-plugin"))++ with pytest.raises(SystemExit) as exc:+ plugins_cmd.cmd_install("some/plugin", force=True)++ assert exc.value.code == 1+ assert installed == []++ def test_plain_install_is_not_gated(self, plugin_home, monkeypatch):+ """A brand-new install creates no checkout a gateway could have loaded, so only the+ forced reinstall path is gated — the guard must not fire before `--force` does."""+ class _Sentinel(Exception):+ pass++ def _boom(*_a, **_k):+ raise _Sentinel++ monkeypatch.setattr(plugins_cmd, "_install_plugin_core", _boom)++ with pytest.raises(_Sentinel):+ plugins_cmd.cmd_install("some/plugin", force=False) # reaches the clone — not gated+ with pytest.raises(SystemExit) as exc:+ plugins_cmd.cmd_install("some/plugin", force=True) # gated before the clone++ assert exc.value.code == 1++ def test_stopped_gateway_update_is_unchanged(self, stopped_home, monkeypatch):+ target = stopped_home / "plugins" / "git-plugin"+ (target / ".git").mkdir(parents=True, exist_ok=True)+ (target / "plugin.yaml").write_text("name: git-plugin\nversion: '1.0'\n", encoding="utf-8")+ (stopped_home / "plugins" / ".install-metadata.json").write_text("{}", encoding="utf-8")+ pulled = []+ monkeypatch.setattr(plugins_cmd_update, "_pull_plugin_update",+ lambda *a, **k: pulled.append(1) or "Updating 111..222")++ plugins_cmd.cmd_update("git-plugin")++ assert pulled == [1]