Skip to content

The agent that grows with you

fix(plugins): gate an update's new dependencies like an install does

ethernet8839afd427d9
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 2794bb89b37..a2023f41468 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -397,8 +397,13 @@ def _install_plugin_python_deps(
if not has_python:
return True, None
+ return _consent_python_deps(manifest.get("name", "this plugin"), deps, console)
- plugin_name = manifest.get("name", "this plugin")
+
+def _consent_python_deps(plugin_name: str, deps: tuple[str, ...], console) -> tuple[bool, Optional[str]]:
+ """The y/N gate for Python deps entering the shared environment — install,
+ reinstall AND an update that declares new ones all pass through here.
+ Returns (consented, reason); never raises."""
console.print(
f"\n[bold]{plugin_name}[/bold] declares Python dependencies:"
)
@@ -986,7 +991,7 @@ def cmd_install(
console.print()
-def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None) -> str:
+def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None, *, interactive: bool = False) -> str:
"""Shared ``update`` core: refuse pinned / non-git checkouts, ``git pull``, record the new
revision. Returns the pull output; raises :class:`PluginOperationError` on any refusal.
*pinned_msg(install_record)* / *not_git_msg()* build the caller-specific error text."""
@@ -1000,7 +1005,7 @@ def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None)
before_pull()
from hermes_cli.plugins_transaction import update_plugin
- return update_plugin(target)
+ return update_plugin(target, interactive=interactive)
def cmd_update(name: str, *, interactive: bool = True) -> None:
@@ -1011,7 +1016,7 @@ def cmd_update(name: str, *, interactive: bool = True) -> None:
target = _require_installed_plugin(name, _plugins_dir(), console)
sidecar = catalog.catalog_install_record(target)
if sidecar: # catalog installs re-pin to the reviewed SHA — never `git pull`
- catalog.cmd_update_catalog(name, target, sidecar, console)
+ catalog.cmd_update_catalog(name, target, sidecar, console, interactive=interactive)
return
try:
output = _pull_plugin_update(
@@ -1021,7 +1026,8 @@ def cmd_update(name: str, *, interactive: bool = True) -> None:
f"`hermes plugins install {escape(str(rec.get('source', '<source>')))} --force "
"--ref <40-character commit SHA>`."),
lambda: f"Plugin '{name}' was not installed from git (no .git directory). Cannot update.",
- before_pull=lambda: console.print(f"[dim]Updating {name}...[/dim]"))
+ before_pull=lambda: console.print(f"[dim]Updating {name}...[/dim]"),
+ interactive=interactive)
except PluginOperationError as exc:
_fail(console, f"[red]Error:[/red] {exc}")
_post_pull_housekeeping(target, console)
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index ea1e94f354f..dfd3e72f988 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -111,7 +111,7 @@ def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Option
return target, manifest, installed_name
-def repin_catalog_plugin(target: Path, sidecar: dict) -> tuple[str, bool]:
+def repin_catalog_plugin(target: Path, sidecar: dict, *, interactive: bool = False) -> tuple[str, bool]:
"""Re-pin a catalog install to the current catalog SHA (never ``git pull``). Returns
``(new_sha, changed)``; raises ``PluginOperationError`` when the entry left the catalog."""
from hermes_cli.plugins_cmd import PluginOperationError
@@ -126,15 +126,15 @@ def repin_catalog_plugin(target: Path, sidecar: dict) -> tuple[str, bool]:
return entry.sha, False
from hermes_cli.plugins_transaction import update_plugin
- update_plugin(target, catalog_entry=entry)
+ update_plugin(target, catalog_entry=entry, interactive=interactive)
return entry.sha, True
-def cmd_update_catalog(name: str, target: Path, sidecar: dict, console) -> None:
+def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, interactive: bool = True) -> None:
from hermes_cli.plugins_cmd import PluginOperationError, _fail
console.print(f"[dim]Checking catalog pin for {name}...[/dim]")
try:
- sha, changed = repin_catalog_plugin(target, sidecar)
+ sha, changed = repin_catalog_plugin(target, sidecar, interactive=interactive)
except PluginOperationError as exc:
_fail(console, f"[red]Error:[/red] {exc}")
raise SystemExit(1)
diff --git a/hermes_cli/plugins_transaction.py b/hermes_cli/plugins_transaction.py
index f26352581f2..852577a16ca 100644
--- a/hermes_cli/plugins_transaction.py
+++ b/hermes_cli/plugins_transaction.py
@@ -35,8 +35,50 @@ def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata:
})
-def update_plugin(target: Path, *, catalog_entry=None) -> str:
- """Prepare a catalog re-pin or custom Git pull without changing the live tree."""
+def _refresh_declared_dependencies(target: Path, staged: Path, manifest: dict, *, interactive: bool) -> None:
+ """Dependency changes carried by an update clear the same gates as an install.
+
+ New Python requirements install packages into the shared environment: install and
+ reinstall prompt for that, so an update prompts too, and an unattended one (dashboard,
+ ``plugins.auto_apply`` from the gateway) is REFUSED rather than consented on the user's
+ behalf. Publication replaces the whole tree, so a Node sidecar the user accepted earlier is
+ rebuilt in the staged copy when its package.json/lock moved (custom pulls copy a stale
+ node_modules; catalog re-pins clone without one).
+ """
+ from hermes_cli import plugins_cmd as pc
+ from hermes_cli.runtime_state import _bytes
+ from pm.plugin_declarations import read_python_declaration
+ from pm.workspace import enabled_plugin_dirs, install_node_sidecar
+
+ if (target / "node_modules").is_dir() and (staged / "package.json").is_file() and (
+ not (staged / "node_modules").is_dir()
+ or any(_bytes(target / name) != _bytes(staged / name) for name in ("package.json", "package-lock.json"))):
+ reason = install_node_sidecar(staged, explicit=True)
+ if reason:
+ raise pc.PluginOperationError(
+ f"Node dependencies could not be refreshed: {reason}. "
+ "The installed plugin and active environment are unchanged.")
+ if target.resolve() not in enabled_plugin_dirs(installing=target):
+ return # a disabled plugin's deps are admitted (and consented) by `hermes plugins enable`
+ before, after = read_python_declaration(target), read_python_declaration(staged)
+ added = tuple(spec for spec in after.install_requirements if spec not in before.install_requirements)
+ if not added and not (after.is_member and not before.is_member):
+ return
+ if not interactive:
+ raise pc.PluginOperationError(
+ f"The update declares new Python dependencies ({', '.join(added) or 'in its pyproject.toml'}); "
+ f"run `hermes plugins update {target.name}` in a terminal to review them.")
+ consented, reason = pc._consent_python_deps(manifest.get("name", target.name), added, pc._console())
+ if not consented:
+ raise pc.PluginOperationError(
+ f"Update declined: {reason}. The installed plugin and active environment are unchanged.")
+
+
+def update_plugin(target: Path, *, catalog_entry=None, interactive: bool = False) -> str:
+ """Prepare a catalog re-pin or custom Git pull without changing the live tree.
+
+ *interactive*: a terminal user is present to consent to newly declared dependencies;
+ the dashboard and the gateway's auto-apply pass False and get a refusal instead."""
import tempfile
from hermes_cli import plugins_cmd as pc
@@ -108,6 +150,7 @@ def update_plugin(target: Path, *, catalog_entry=None) -> str:
pc._check_manifest_version(manifest, target.name)
pc._scan_plugin_tree(staged, source, force=False)
pc._copy_example_files(staged, pc._console())
+ _refresh_declared_dependencies(target, staged, manifest, interactive=interactive)
if tree_digest(target) != before:
raise pc.PluginOperationError("Plugin files changed while preparing the update; retry.")
record["revision"] = revision
diff --git a/tests/hermes_cli/test_plugin_update_transaction.py b/tests/hermes_cli/test_plugin_update_transaction.py
index dc71156422f..a5a5620f129 100644
--- a/tests/hermes_cli/test_plugin_update_transaction.py
+++ b/tests/hermes_cli/test_plugin_update_transaction.py
@@ -19,25 +19,28 @@ def _commit(repo, message):
return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
-def _version(repo, version, *, broken=False, minimum=""):
+def _version(repo, version, *, broken=False, minimum="", libraries=("shared-library",)):
from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION
(repo / "plugin.yaml").write_text(
f"name: transactional\nversion: {version}\nmanifest_version: {SUPPORTED_MANIFEST_VERSION}\n"
f"requires_hermes: '{minimum}'\n", encoding="utf-8")
(repo / "__init__.py").write_text(f"VERSION = {version!r}\ndef register(ctx):\n pass\n", encoding="utf-8")
+ (repo / ".gitignore").write_text("node_modules/\n", encoding="utf-8")
deps = '["impossible-plugin-dep==1", "impossible-plugin-dep==2"]' if broken else '[]'
- library = repo.parent / "shared-library"
- library.mkdir(exist_ok=True)
- (library / "pyproject.toml").write_text(
- '[project]\nname="shared-library"\nversion="1"\nrequires-python=">=3.14"\n'
- '[tool.uv]\npackage=false\n', encoding="utf-8")
+ for name in libraries:
+ library = repo.parent / name
+ library.mkdir(exist_ok=True)
+ (library / "pyproject.toml").write_text(
+ f'[project]\nname="{name}"\nversion="1"\nrequires-python=">=3.14"\n'
+ '[tool.uv]\npackage=false\n', encoding="utf-8")
if not broken:
- deps = '["shared-library"]'
+ deps = json.dumps(list(libraries))
+ sources = "".join(f'{name}={{path="../{name}"}}\n' for name in libraries)
(repo / "pyproject.toml").write_text(
f'[project]\nname="transactional"\nversion="{version}"\nrequires-python=">=3.14"\n'
f'dependencies={deps}\n[tool.uv]\npackage=false\n'
- '[tool.uv.sources]\nshared-library={path="../shared-library"}\n', encoding="utf-8")
+ f'[tool.uv.sources]\n{sources}', encoding="utf-8")
return _commit(repo, version)
@@ -72,6 +75,98 @@ def installed(admission_env, monkeypatch, request):
return root, home, repo, target, state
+def _head(repo) -> str:
+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
+def test_unattended_update_refuses_newly_declared_python_dependencies(installed):
+ """Install gates Python deps behind a prompt; an update that ADDS a dependency must not
+ slip them into the shared environment without one. With nobody to ask (dashboard, gateway
+ ``plugins.auto_apply``) the update is refused and nothing — code, env, metadata — moves."""
+ import shutil
+ from hermes_cli import plugins_cmd
+ from pm.environments import selected_venv
+
+ root, home, repo, target, state = installed
+ old_head, old_venv = _head(target), selected_venv(root / "core")
+ state["sha"] = _version(repo, "2.0.0", libraries=("shared-library", "second-library"))
+ shutil.copytree(repo.parent / "second-library", target.parent / "second-library", dirs_exist_ok=True)
+
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+
+ assert result["ok"] is False, result
+ assert "second-library" in result["error"]
+ assert _head(target) == old_head
+ assert selected_venv(root / "core") == old_venv
+
+
[email protected]("installed", ["custom"], indirect=True)
[email protected]("answer, published", [("y", True), ("n", False)])
+def test_interactive_update_asks_before_installing_new_python_dependencies(
+ installed, monkeypatch, answer, published):
+ """A terminal user is asked the same question install asks; yes publishes code AND the
+ dependency together, no leaves both untouched."""
+ import shutil
+ from types import SimpleNamespace
+ from hermes_cli import plugins_cmd
+ from hermes_cli.plugins_transaction import update_plugin
+ from pm.environments import selected_venv
+
+ root, home, repo, target, state = installed
+ old_head, old_venv = _head(target), selected_venv(root / "core")
+ state["sha"] = _version(repo, "2.0.0", libraries=("shared-library", "second-library"))
+ shutil.copytree(repo.parent / "second-library", target.parent / "second-library", dirs_exist_ok=True)
+ monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: True))
+ monkeypatch.setattr("sys.stdout", SimpleNamespace(isatty=lambda: True, write=lambda *a: None, flush=lambda: None))
+ asked: list = []
+ monkeypatch.setattr("builtins.input", lambda prompt="": asked.append(prompt) or answer)
+
+ if published:
+ update_plugin(target, interactive=True)
+ else:
+ with pytest.raises(plugins_cmd.PluginOperationError, match="declined"):
+ update_plugin(target, interactive=True)
+
+ assert asked, "no dependency consent prompt was shown"
+ assert (_head(target) == state["sha"]) is published
+ assert (selected_venv(root / "core") != old_venv) is published
+ assert (_head(target) != old_head) is published
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
+def test_update_rebuilds_an_accepted_node_sidecar_when_its_manifest_moves(installed, monkeypatch):
+ """Publication swaps the whole tree, so a node_modules the user accepted at install would
+ come back stale (custom pull copies it) or missing (catalog re-clone). When package.json
+ changes, the sidecar is rebuilt in the staged copy and published with the code."""
+ from hermes_cli import plugins_cmd
+ from pm import workspace
+
+ root, home, repo, target, state = installed
+ (repo / "package.json").write_text('{"name": "transactional", "dependencies": {}}', encoding="utf-8")
+ _commit(repo, "add node sidecar")
+ # the user accepted the sidecar at install time
+ (target / "node_modules").mkdir()
+ (target / "node_modules" / "stale").write_text("v1", encoding="utf-8")
+ (repo / "package.json").write_text('{"name": "transactional", "dependencies": {"left-pad": "*"}}', encoding="utf-8")
+ state["sha"] = _commit(repo, "bump node deps")
+ rebuilt: list = []
+
+ def fake_npm(plugin_dir, *, explicit=False):
+ rebuilt.append(plugin_dir)
+ (plugin_dir / "node_modules").mkdir(exist_ok=True)
+ (plugin_dir / "node_modules" / "fresh").write_text("v2", encoding="utf-8")
+ return None
+
+ monkeypatch.setattr(workspace, "install_node_sidecar", fake_npm)
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+
+ assert result["ok"] is True, result
+ assert len(rebuilt) == 1 and rebuilt[0] != target, "npm must run in the staged copy, not the live tree"
+ assert (target / "node_modules" / "fresh").is_file()
+ assert _head(target) == state["sha"]
+
+
@pytest.mark.parametrize("installed", ["catalog", "custom"], indirect=True)
@pytest.mark.parametrize("failure", ["dependencies", "version", "publication", "manifest"])
def test_failed_update_keeps_code_metadata_config_and_environment(installed, monkeypatch, failure):