Skip to content

The agent that grows with you

refactor(plugins): update-all reads a typed outcome, not printed text

Tekniume1065b4a9c3b
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 8ef022a0da8..702e42982bd 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -650,10 +650,11 @@ def repin_catalog_plugin(
return RepinResult(entry.sha, True, installed_name, warnings)
-def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, interactive: bool = True) -> None:
+def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, interactive: bool = True) -> bool:
+ """Re-pin a catalog install, printing progress; True when the pin moved. Refusals raise
+ :class:`RepinConsentRequired` / ``PluginOperationError`` with nothing changed (the caller reports them)."""
from hermes_cli.plugins_cmd import (
- PluginOperationError, _ask_yes, _declared_capabilities_from_manifest, _fail, _is_tty, _read_manifest,
- _run_capability_consent)
+ _ask_yes, _declared_capabilities_from_manifest, _is_tty, _read_manifest, _run_capability_consent)
console.print(f"[dim]Checking catalog pin for {name}...[/dim]")
def _confirm_widening(delta: dict[str, list[str]]) -> bool:
@@ -666,19 +667,7 @@ def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, inter
return False
return _ask_yes(" Apply this update? [y/N]: ")
- try:
- result = repin_catalog_plugin(
- target,
- sidecar,
- interactive=interactive,
- consent_cb=_confirm_widening,
- )
- except RepinConsentRequired as exc:
- _fail(console, f"[yellow]Update of {name} not applied:[/yellow] {exc}")
- raise SystemExit(1)
- except PluginOperationError as exc:
- _fail(console, f"[red]Error:[/red] {exc}")
- raise SystemExit(1)
+ result = repin_catalog_plugin(target, sidecar, interactive=interactive, consent_cb=_confirm_widening)
verb = "updated to" if result.changed else "is already at catalog pin"
console.print(f"[green]✓[/green] Plugin [bold]{result.installed_name}[/bold] {verb} {result.sha[:8]}.")
for warning in result.warnings:
@@ -697,6 +686,7 @@ def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, inter
console.print(
f"[yellow]Plugin {result.installed_name} has new capabilities; review them with "
f"`hermes plugins capabilities {result.installed_name}`.[/yellow]")
+ return result.changed
diff --git a/hermes_cli/plugins_cmd_update.py b/hermes_cli/plugins_cmd_update.py
index a519142490c..20eb0cc1153 100644
--- a/hermes_cli/plugins_cmd_update.py
+++ b/hermes_cli/plugins_cmd_update.py
@@ -67,28 +67,27 @@ 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:
- """Update an installed plugin by pulling latest from its git remote."""
+def update_one(name: str, target: Path, console, *, interactive: bool = True) -> bool:
+ """Update one installed plugin, printing progress and consent prompts; True when it moved.
+
+ Refusals raise :class:`~hermes_cli.plugins_cmd_catalog.RepinConsentRequired` or
+ ``PluginOperationError`` with nothing changed; :func:`cmd_update` turns them into exit 1 and
+ ``hermes plugins update`` with no name records them per plugin and moves on.
+ """
from rich.markup import escape
from hermes_cli import plugins_cmd_catalog as catalog
- console = _pc()._console()
- target = _pc()._require_installed_plugin(name, _pc()._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, interactive=interactive)
- return
- try:
- output = _pull_plugin_update(
- target,
- lambda rec: (
- f"Plugin '{name}' is pinned to {rec.get('revision')}. To move it, run "
- 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]"),
- interactive=interactive)
- except _pc().PluginOperationError as exc:
- _pc()._fail(console, f"[red]Error:[/red] {exc}")
+ return catalog.cmd_update_catalog(name, target, sidecar, console, interactive=interactive)
+ output = _pull_plugin_update(
+ target,
+ lambda rec: (
+ f"Plugin '{name}' is pinned to {rec.get('revision')}. To move it, run "
+ 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]"),
+ interactive=interactive)
_post_pull_housekeeping(target, console)
# Update-time re-consent (#64228): if the new version declares
@@ -110,9 +109,23 @@ def cmd_update(name: str, *, interactive: bool = True) -> None:
out = output.strip()
if "Already up to date" in out:
console.print(f"[green]✓[/green] Plugin [bold]{name}[/bold] is already up to date.")
- else:
- console.print(f"[green]✓[/green] Plugin [bold]{name}[/bold] updated.")
- console.print(f"[dim]{out}[/dim]")
+ return False
+ console.print(f"[green]✓[/green] Plugin [bold]{name}[/bold] updated.")
+ console.print(f"[dim]{out}[/dim]")
+ return True
+
+
+def cmd_update(name: str, *, interactive: bool = True) -> None:
+ """``hermes plugins update <name>``: :func:`update_one`, exit 1 on a refusal."""
+ from hermes_cli.plugins_cmd_catalog import RepinConsentRequired
+ console = _pc()._console()
+ target = _pc()._require_installed_plugin(name, _pc()._plugins_dir(), console)
+ try:
+ update_one(name, target, console, interactive=interactive)
+ except RepinConsentRequired as exc:
+ _pc()._fail(console, f"[yellow]Update of {name} not applied:[/yellow] {exc}")
+ except _pc().PluginOperationError as exc:
+ _pc()._fail(console, f"[red]Error:[/red] {exc}")
def _post_pull_housekeeping(target: Path, console) -> None:
diff --git a/hermes_cli/plugins_cmd_update_all.py b/hermes_cli/plugins_cmd_update_all.py
index 56096889400..7bf1eafd667 100644
--- a/hermes_cli/plugins_cmd_update_all.py
+++ b/hermes_cli/plugins_cmd_update_all.py
@@ -1,16 +1,15 @@
"""``hermes plugins update`` with no name: update every installed plugin that has an update.
The list comes from the read-only ``check-updates`` probe (:func:`hermes_cli.plugins_updates.run_checks`);
-each plugin is then updated through the single-plugin :func:`~hermes_cli.plugins_cmd_update.cmd_update`
-path, so catalog consent, the security scan and capability re-consent still apply per plugin.
+each plugin is then updated through the single-plugin
+path (:func:`~hermes_cli.plugins_cmd_update.update_one`), so catalog consent, the security scan and
+capability re-consent still apply per plugin.
Sibling of :mod:`hermes_cli.plugins_cmd` (the facade is imported late, never at module level).
"""
from __future__ import annotations
-import logging
-import re
import sys
from dataclasses import dataclass, field
from typing import Any
@@ -19,8 +18,6 @@ from typing import Any
# re-pins to the reviewed sha, a tracked git install pulls. A pip row is a PyPI distribution that
# Hermes never upgrades (#132494), so offering it would promise an update nothing applies.
_UPDATE_KIND = {"catalog": "catalog re-pin", "git": "git pull"}
-_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
-logger = logging.getLogger(__name__)
def _pc():
@@ -57,58 +54,31 @@ def plan_update_all(results: list[Any]) -> UpdatePlan:
return plan
-class _Tee:
- """Pass-through stdout that keeps what was written, so a failed update's own error message can
- be quoted in the summary. Everything else (isatty, fileno, encoding) is the real stream's."""
+def _short(reason: str) -> str:
+ first = reason.strip().splitlines()[0] if reason.strip() else ""
+ return first if len(first) <= 200 else first[:197] + "..."
- def __init__(self, stream):
- self._stream = stream
- self.text: list[str] = []
- def write(self, data):
- self.text.append(data)
- return self._stream.write(data)
-
- def __getattr__(self, name):
- return getattr(self._stream, name)
-
- def failure_reason(self) -> str:
- """The paragraph the single-plugin update printed with its refusal (``Error: ...`` or
- ``... not applied``), rejoined from Rich's wrapping; else the last line printed."""
- lines = [ln.strip() for ln in _ANSI_RE.sub("", "".join(self.text)).splitlines()]
- start = next((i for i, ln in enumerate(lines) if ln.startswith("Error:") or "not applied" in ln), None)
- if start is None:
- return next((ln for ln in reversed(lines) if ln), "")
- para = []
- for ln in lines[start:]:
- if not ln:
- break
- para.append(ln)
- reason = " ".join(para)
- return reason if len(reason) <= 200 else reason[:197] + "..."
-
-
-def _revision(name: str) -> str:
- return str(_pc()._read_install_metadata().get(name, {}).get("revision") or "")
-
-
-def _update_one(name: str, *, interactive: bool) -> tuple[str, str]:
- """Run the single-plugin update; return ``(status, detail)`` with status updated/current/failed."""
- before = _revision(name)
- tee = _Tee(sys.stdout)
- sys.stdout = tee
+def _update_one(row, console, *, interactive: bool) -> tuple[str, str]:
+ """Run the single-plugin update for one plan row; return ``(status, detail)``, status being
+ updated/current/failed. A refusal is printed like ``update <name>`` prints it, then recorded."""
+ from rich.markup import escape
+ from hermes_cli.plugins_cmd_catalog import RepinConsentRequired
+ from hermes_cli.plugins_cmd_update import update_one
+ target = _pc()._user_installed_plugin_dir(row.name)
+ if target is None:
+ return "failed", "no longer installed"
try:
- _pc().cmd_update(name, interactive=interactive)
- except SystemExit as exc:
- if exc.code not in (0, None):
- return "failed", tee.failure_reason() or f"exit {exc.code}"
- except Exception as exc: # one plugin's crash must not stop the rest
- logger.warning("update of plugin %s failed", name, exc_info=True)
- return "failed", f"{type(exc).__name__}: {exc}"
- finally:
- sys.stdout = tee._stream
- after = _revision(name)
- return ("updated", f"{before[:8]}..{after[:8]}") if after != before else ("current", "")
+ moved = update_one(row.name, target, console, interactive=interactive)
+ except RepinConsentRequired as exc:
+ console.print(f"[yellow]Update of {escape(row.name)} not applied:[/yellow] {escape(str(exc))}")
+ return "failed", _short(f"not applied: {exc}")
+ except _pc().PluginOperationError as exc:
+ console.print(f"[red]Error:[/red] {escape(str(exc))}")
+ return "failed", _short(str(exc))
+ if not moved:
+ return "current", ""
+ return "updated", f"{(row.current or '')[:8]}..{(row.latest or '')[:8]}"
def _print_plan(console, plan: UpdatePlan) -> None:
@@ -127,7 +97,7 @@ def cmd_update_all(*, yes: bool = False) -> None:
"""``hermes plugins update [--yes]``: list the plugins with an update and update them all.
A terminal asks once (``Update all N? [Y/n]``); without one nothing moves unless ``--yes`` is
- given. Each plugin then goes through ``cmd_update``, interactive only when a terminal is present,
+ given. Each plugin then goes through ``update_one``, interactive only when a terminal is present,
so per-plugin consent prompts still appear there and stay closed (fail closed) under ``--yes``
in scripts. One failure does not stop the rest; exit 1 when any update failed.
"""
@@ -160,7 +130,7 @@ def cmd_update_all(*, yes: bool = False) -> None:
outcomes = []
for row in plan.movable:
console.print(f"\n[bold]── {row.name}[/bold]")
- outcomes.append((row.name, *_update_one(row.name, interactive=tty)))
+ outcomes.append((row.name, *_update_one(row, console, interactive=tty)))
console.print("\n[bold]Summary[/bold]")
marks = {"updated": "[green]✓ updated[/green]", "current": "[dim]= already current[/dim]",
diff --git a/tests/hermes_cli/test_plugins_update_all.py b/tests/hermes_cli/test_plugins_update_all.py
index e4c58c6b3da..dd359ea2ec5 100644
--- a/tests/hermes_cli/test_plugins_update_all.py
+++ b/tests/hermes_cli/test_plugins_update_all.py
@@ -20,7 +20,7 @@ def _parse(argv):
@pytest.fixture
def fleet(monkeypatch, tmp_path):
"""Four installed rows: two the update path can move, a PyPI row it never upgrades (#132494) and a pin."""
- from hermes_cli import plugins_cmd, plugins_updates
+ from hermes_cli import plugins_cmd, plugins_cmd_update, plugins_updates
rows = [
CheckResult("cat", "catalog", current="a" * 40, latest="b" * 40, update_available=True),
@@ -30,14 +30,16 @@ def fleet(monkeypatch, tmp_path):
]
calls = []
- def fake_update(name, *, interactive=True):
+ def fake_update(name, target, console, *, interactive=True):
calls.append((name, interactive))
if name == "cat":
- plugins_cmd._fail(plugins_cmd._console(), "Error: catalog pin refused")
+ raise plugins_cmd.PluginOperationError("catalog pin refused")
+ return True
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr(plugins_updates, "run_checks", lambda plugins_dir, **kw: rows)
- monkeypatch.setattr(plugins_cmd, "cmd_update", fake_update)
+ monkeypatch.setattr(plugins_cmd, "_user_installed_plugin_dir", lambda name: tmp_path / name)
+ monkeypatch.setattr(plugins_cmd_update, "update_one", fake_update)
return calls