The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): a refused hub update or uninstall exits non-zero too; blocked installs toast
ThereWasAYang96108880add6
diff --git a/apps/desktop/src/store/hub-actions.blocked.test.ts b/apps/desktop/src/store/hub-actions.blocked.test.tsindex eb92bfefef6..43798587c56 100644--- a/apps/desktop/src/store/hub-actions.blocked.test.ts+++ b/apps/desktop/src/store/hub-actions.blocked.test.ts@@ -51,6 +51,16 @@ test('the current CLI "Not installed:" tail parses into findings + trust', () =>]expect(parseInstallBlocked(uncounted)).toEqual({ findings: 0, unverified: false })++ // The real action log is Rich-wrapped at 80 columns, which can break the+ // hard-block clause between "never" and "installs" (seen on a live arxiv install).+ const wrappedHardBlock = [+ 'Not installed: the security scan found 9 high-risk pattern(s) in ',+ "'NousResearch/hermes-agent/skills/research/arxiv' (listed above). Hermes never ",+ 'installs unverified skills with high-risk findings, even with --force. Review '+ ]++ expect(parseInstallBlocked(wrappedHardBlock)).toEqual({ findings: 9, unverified: true })})test('the legacy "Installation blocked:" tail still parses and toasts a plain explanation', () => {diff --git a/apps/desktop/src/store/hub-actions.ts b/apps/desktop/src/store/hub-actions.tsindex 0088fd8d52b..e2fd188f1f2 100644--- a/apps/desktop/src/store/hub-actions.ts+++ b/apps/desktop/src/store/hub-actions.ts@@ -201,7 +201,7 @@ export function closeHubLog(): void {const INSTALL_BLOCKED_CURRENT_RE =/Not installed:\s+the security scan found\s+(?:(?<findings>\d+)\s+)?high-risk\s+pattern/i-const INSTALL_BLOCKED_UNVERIFIED_RE = /never installs\s+unverified/i+const INSTALL_BLOCKED_UNVERIFIED_RE = /never\s+installs\s+unverified/iconst INSTALL_BLOCKED_LEGACY_RE =/Installation blocked:.*?\((?<source>[a-z_-]+) source \+ (?<verdict>[a-z_]+) verdict, (?<findings>\d+) findings?\)/idiff --git a/hermes_cli/main_agent_cmds.py b/hermes_cli/main_agent_cmds.pyindex 17a2e49b65a..5f27641239e 100644--- a/hermes_cli/main_agent_cmds.py+++ b/hermes_cli/main_agent_cmds.py@@ -180,7 +180,7 @@ def cmd_skills(args):_cmd_skills_trust(args)else:from hermes_cli.skills_hub import skills_command- skills_command(args)+ return skills_command(args)def _cmd_skills_trust(args):diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.pyindex 4ee55740ec7..9a365c06490 100644--- a/hermes_cli/skills_hub.py+++ b/hermes_cli/skills_hub.py@@ -941,9 +941,10 @@ def _has_local_edits(installed: dict) -> bool:def do_update(name: Optional[str] = None, console: Optional[Console] = None,- force: bool = False) -> None:+ force: bool = False) -> Optional[bool]:"""Update hub-installed skills. Locally edited ones are skipped unless ``force`` — the- update rmtree-replaces the user's work, so that must be an explicit choice.+ update rmtree-replaces the user's work, so that must be an explicit choice. Returns False+ when any update failed (e.g. the new version is refused by the scan gate), else None.Skills whose on-disk content no longer matches the hash recorded at install time have been editedlocally; updating them would silently destroy the user's work (``do_install(force=True)``@@ -962,6 +963,7 @@ def do_update(name: Optional[str] = None, console: Optional[Console] = None,returnskipped_local: list[str] = []+ failed: list[str] = []for entry in updates:installed = lock.get_installed(entry["name"])category = ""@@ -977,15 +979,21 @@ def do_update(name: Optional[str] = None, console: Optional[Console] = None,# Pin to the lockfile's source registry: a bare identifier such as "reddit" would# otherwise fuzzy-resolve inside do_install to a same-named skill in a DIFFERENT# registry, overwriting the user's files and rewriting the lock's `source`.- do_install(entry["identifier"], category=category, force=True, console=c,- source_id=entry.get("source", "") or None)+ if do_install(entry["identifier"], category=category, force=True, console=c,+ source_id=entry.get("source", "") or None) is False:+ failed.append(entry["name"])- if len(updates) > len(skipped_local):- c.print(f"[bold green]Updated {len(updates) - len(skipped_local)} skill(s).[/]\n")+ updated = len(updates) - len(skipped_local) - len(failed)+ if updated:+ c.print(f"[bold green]Updated {updated} skill(s).[/]\n")if skipped_local:c.print(f"[dim]{len(skipped_local)} skill(s) kept your local edits: "f"{', '.join(sorted(skipped_local))}.[/]")c.print("[dim]Overwrite with: hermes skills update <name> --force[/]\n")+ if failed:+ c.print(f"[bold red]Not updated:[/] {', '.join(sorted(failed))} (see the messages above).\n")+ return False+ return Nonedef do_audit(name: Optional[str] = None, console: Optional[Console] = None,@@ -1019,15 +1027,18 @@ def do_audit(name: Optional[str] = None, console: Optional[Console] = None,# --- uninstall / reset / bundled-skill management ---def do_uninstall(name: str, console: Optional[Console] = None, skip_confirm: bool = False,- invalidate_cache: bool = True) -> None:- """Remove a hub-installed skill with confirmation."""+ invalidate_cache: bool = True) -> Optional[bool]:+ """Remove a hub-installed skill with confirmation. True when removed, False when the removal+ was refused (not a hub skill, unsafe path), None when the user declined the prompt."""from tools.skills_hub_install import uninstall_skillc = console or _console# skip_confirm bypasses the prompt (TUI mode, where input() hangs)if not skip_confirm and not _confirm_or_cancel(c, f"\n[bold]Uninstall '{name}'?[/]"):- return- if _report_pair(c, *uninstall_skill(name)):- _finish_change(c, invalidate_cache)+ return None+ if not _report_pair(c, *uninstall_skill(name)):+ return False+ _finish_change(c, invalidate_cache)+ return Truedef do_reset(name: str, restore: bool = False, console: Optional[Console] = None,@@ -1448,18 +1459,18 @@ _CLI_ACTIONS = {"snapshot": _snapshot_cli, "tap": _tap_cli}-def skills_command(args) -> None:+def skills_command(args) -> Optional[int]:"""Router for `hermes skills <subcommand>` — called from hermes_cli/main.py."""handler = _CLI_ACTIONS.get(getattr(args, "skills_action", None))if handler is None:_console.print("Usage: hermes skills [browse|search|install|inspect|list|list-modified|diff|check|update|audit|uninstall|reset|opt-out|opt-in|publish|snapshot|tap]\n")_console.print("Run 'hermes skills <command> --help' for details.\n")- return- # A handler reporting a real failure (do_install's False) must exit non-zero: the Desktop Hub- # reads the spawned action's exit code to decide whether to toast, so an exit-0 failure renders- # as "the button did nothing" while the reason sits unread in the action log.- if handler(args) is False:- sys.exit(1)+ return None+ # A handler reporting a real failure (install/update/uninstall's False) must exit non-zero: the+ # Desktop Hub reads the spawned action's exit code to decide whether to toast, so an exit-0+ # failure renders as "the button did nothing" while the reason sits unread in the action log.+ # Returned, not sys.exit()-ed: `hermes` turns a handler's int into the exit code.+ return 1 if handler(args) is False else None# --- Slash command entry point (/skills in chat) ---diff --git a/tests/hermes_cli/test_skills_failure_exit_code.py b/tests/hermes_cli/test_skills_failure_exit_code.pynew file mode 100644index 00000000000..540fb3a14f6--- /dev/null+++ b/tests/hermes_cli/test_skills_failure_exit_code.py@@ -0,0 +1,182 @@+"""A failed ``hermes skills install|update|uninstall`` exits non-zero (#118301).++The Desktop spawns these as detached actions and learns their outcome only from the+exit code (``apps/desktop/src/store/hub-actions.ts`` toasts on non-zero), so a refused+action that exits 0 reads as "the button did nothing" while the reason sits unread in+the action log. The scan gate is the common case: a blocked install used to print+"Not installed: ..." and exit 0.+"""++import sys+from io import StringIO++import pytest+from rich.console import Console++import hermes_cli.skills_hub as cli_hub+++def _console():+ sink = StringIO()+ return Console(file=sink, force_terminal=False, color_system=None, width=200), sink+++def _scan_gate_env(monkeypatch, tmp_path, *, verdict="dangerous", installed=None):+ """Wire ``do_install`` down to the real scan-policy decision for a community skill."""+ import tools.skills_guard as guard+ import tools.skills_hub as hub+ import tools.skills_hub_install as hub_install++ bundle = type("Bundle", (), {+ "name": "risky-skill", "files": {"SKILL.md": "---\nname: risky-skill\n---\n"},+ "source": "skills-sh", "identifier": "org/repo/risky-skill", "trust_level": "community",+ "metadata": {},+ })()+ q_path = tmp_path / "skills" / ".hub" / "quarantine" / "risky-skill"+ q_path.mkdir(parents=True)+ audit: list = []++ monkeypatch.setattr(hub, "ensure_hub_dirs", lambda: None)+ monkeypatch.setattr(hub, "append_audit_log", lambda *a, **k: audit.append(a))+ monkeypatch.setattr(hub, "HubLockFile", lambda: type(+ "Lock", (), {"get_installed": lambda self, n: installed})())+ monkeypatch.setattr(cli_hub, "_sources", lambda: [object()])+ monkeypatch.setattr(cli_hub, "_resolve_source_meta_and_bundle",+ lambda identifier, sources: (None, bundle, sources[0]))+ monkeypatch.setattr(cli_hub, "_record_skill_install", lambda *a, **k: None)+ monkeypatch.setattr(hub_install, "quarantine_bundle", lambda b: q_path)+ finding = guard.Finding("remote_fetch", "critical", "supply_chain", "SKILL.md", 40,+ 'curl -s "https://example.com"', "remote fetch")+ monkeypatch.setattr(cli_hub, "_scan_quarantined", lambda *a, **k: guard.ScanResult(+ skill_name="risky-skill", source="org/repo/risky-skill", trust_level="community",+ verdict=verdict, findings=[finding, finding]))+ installs: list = []++ def _install(q, name, category, b, result):+ installs.append(name)+ d = tmp_path / "skills" / name+ d.mkdir(parents=True, exist_ok=True)+ return d++ monkeypatch.setattr(hub_install, "install_from_quarantine", _install)+ monkeypatch.setattr(hub, "SKILLS_DIR", tmp_path / "skills")+ return installs, audit++[email protected]("verdict", ["dangerous", "caution"])+def test_scan_blocked_install_reports_failure(monkeypatch, tmp_path, verdict):+ installs, audit = _scan_gate_env(monkeypatch, tmp_path, verdict=verdict)+ console, sink = _console()++ assert cli_hub.do_install("org/repo/risky-skill", console=console, skip_confirm=True) is False+ assert installs == []+ assert "Not installed:" in sink.getvalue()+ assert audit and audit[0][0] == "BLOCKED"+++def test_successful_install_reports_success(monkeypatch, tmp_path):+ installs, _ = _scan_gate_env(monkeypatch, tmp_path, verdict="safe")+ monkeypatch.setattr(cli_hub, "_finish_change", lambda *a, **k: None)+ console, _ = _console()++ assert cli_hub.do_install("org/repo/risky-skill", console=console, skip_confirm=True) is True+ assert installs == ["risky-skill"]+++def test_already_installed_is_not_a_failure(monkeypatch, tmp_path):+ """No-op the user owns: exits 0 (the Desktop never offers install on an installed row)."""+ _scan_gate_env(monkeypatch, tmp_path, installed={"install_path": "risky-skill"})+ console, _ = _console()++ assert cli_hub.do_install("org/repo/risky-skill", console=console, skip_confirm=True) is None+++def test_unresolvable_source_reports_failure(monkeypatch):+ import tools.skills_hub as hub++ monkeypatch.setattr(hub, "ensure_hub_dirs", lambda: None)+ monkeypatch.setattr(cli_hub, "_sources", lambda: [object()])+ monkeypatch.setattr(cli_hub, "_resolve_source_meta_and_bundle",+ lambda identifier, sources: (None, None, None))+ monkeypatch.setattr(cli_hub, "_record_skill_install", lambda *a, **k: None)+ console, sink = _console()++ assert cli_hub.do_install("org/repo/gone", console=console, skip_confirm=True) is False+ assert "Could not download" in sink.getvalue()+++def _update_env(monkeypatch, outcomes):+ import tools.skills_hub as hub+ import tools.skills_hub_install as hub_install++ names = list(outcomes)+ monkeypatch.setattr(hub_install, "check_for_skill_updates", lambda **_k: [+ {"name": n, "identifier": f"org/{n}", "source": "github", "status": "update_available"}+ for n in names])+ monkeypatch.setattr(hub, "HubLockFile", lambda: type(+ "Lock", (), {"get_installed": lambda self, n: None})())+ monkeypatch.setattr(cli_hub, "do_install",+ lambda identifier, **_k: outcomes[identifier.split("/", 1)[1]])+++def test_update_reports_failure_when_a_new_version_is_refused(monkeypatch):+ _update_env(monkeypatch, {"good": True, "blocked": False})+ console, sink = _console()++ assert cli_hub.do_update(console=console) is False+ out = sink.getvalue()+ assert "Updated 1 skill(s)" in out+ assert "Not updated:" in out and "blocked" in out+++def test_update_all_succeeding_is_not_a_failure(monkeypatch):+ _update_env(monkeypatch, {"good": True})+ console, sink = _console()++ assert cli_hub.do_update(console=console) is None+ assert "Not updated" not in sink.getvalue()+++def test_uninstall_refusal_reports_failure(monkeypatch):+ import tools.skills_hub_install as hub_install++ monkeypatch.setattr(hub_install, "uninstall_skill",+ lambda name: (False, f"'{name}' is not a hub-installed skill (may be a builtin)"))+ console, _ = _console()++ assert cli_hub.do_uninstall("builtin-skill", console=console, skip_confirm=True) is False+++def test_uninstall_success(monkeypatch):+ import tools.skills_hub_install as hub_install++ monkeypatch.setattr(hub_install, "uninstall_skill", lambda name: (True, f"Uninstalled '{name}'"))+ monkeypatch.setattr(cli_hub, "_finish_change", lambda *a, **k: None)+ console, _ = _console()++ assert cli_hub.do_uninstall("hub-skill", console=console, skip_confirm=True) is True+++# --- the process exit code, through the real `hermes` entry point ---++[email protected]("argv, target, outcome, code", [+ (["skills", "install", "org/repo/x", "--yes"], "do_install", False, 1),+ (["skills", "install", "org/repo/x", "--yes"], "do_install", True, 0),+ (["skills", "install", "org/repo/x", "--yes"], "do_install", None, 0),+ (["skills", "update"], "do_update", False, 1),+ (["skills", "update"], "do_update", None, 0),+ (["skills", "uninstall", "x", "--yes"], "do_uninstall", False, 1),+ (["skills", "uninstall", "x", "--yes"], "do_uninstall", True, 0),+])+def test_cli_exit_code_follows_the_action_outcome(monkeypatch, argv, target, outcome, code):+ from hermes_cli.main import main++ monkeypatch.setattr(cli_hub, target, lambda *a, **k: outcome)+ monkeypatch.setattr(sys, "argv", ["hermes", *argv])+ try:+ main()+ exit_code = 0+ except SystemExit as exc:+ exit_code = exc.code or 0+ assert exit_code == codediff --git a/tests/hermes_cli/test_skills_hub.py b/tests/hermes_cli/test_skills_hub.pyindex c56cbd97d15..e8127a24d37 100644--- a/tests/hermes_cli/test_skills_hub.py+++ b/tests/hermes_cli/test_skills_hub.py@@ -723,7 +723,7 @@ def test_do_install_reports_unresolved_name_as_failure(monkeypatch):assert cli_hub.do_install("no-such-skill", console=console, skip_confirm=True) is False[email protected]("verdict, expected_exit", [(False, 1), (None, 0)])[email protected]("verdict, expected_exit", [(False, 1), (None, None)])def test_skills_command_exit_code_follows_install_verdict(monkeypatch, verdict, expected_exit):"""`hermes skills install` exits non-zero only on a real failure: the Desktop Hub keys itsfailure toast off the spawned action's exit code, so an exit-0 failure reads as silence."""@@ -732,9 +732,5 @@ def test_skills_command_exit_code_follows_install_verdict(monkeypatch, verdict,monkeypatch.setattr(cli_hub, "_CLI_ACTIONS", {"install": lambda args: verdict})args = type("Args", (), {"skills_action": "install"})()- if expected_exit:- with pytest.raises(SystemExit) as excinfo:- cli_hub.skills_command(args)- assert excinfo.value.code == expected_exit- else:- cli_hub.skills_command(args)+ # The router returns the code; `hermes` (main()) turns a handler's int into the exit status.+ assert cli_hub.skills_command(args) == expected_exit