The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into feat/plugin-catalog — reconcile with landed index/manifest-v2 tracks
Teknium7e17ff0ab346
diff --cc hermes_cli/plugin_validate.pyindex 74d0849a051,00000000000..6b3be693675mode 100644,000000..100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@@ -1,434 -1,0 +1,440 @@@+"""``hermes plugins validate`` — admission checks for a plugin directory.++This is the command the plugin-catalog admission CI (and the+``.github/actions/plugin-validate`` composite action) runs against a+candidate plugin. It performs static manifest checks plus a+subprocess-isolated capability probe: the plugin is imported and its+``register(ctx)`` called against a minimal recording stub context in a+scratch child process (with a throwaway ``HERMES_HOME``), so a crashing or+malicious plugin cannot take down the CLI, and the *actually registered*+tools/hooks/middleware are compared against the manifest's declared+``provides_*`` lists.+"""++from __future__ import annotations++import json+import os+import re+import subprocess+import sys+import tempfile+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++_UPPER_SNAKE_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")- _CONFIG_TYPES = {"str", "bool", "int"}++_CONFIG_TYPES = {++ "str", "string", "int", "integer", "float", "number",++ "bool", "boolean", "list", "array", "dict", "mapping", "map",++}+_PROBE_TIMEOUT = 30+_PROBE_SENTINEL = "HERMES_VALIDATE_JSON:"+++@dataclass+class ValidationReport:+ """Result of validating one plugin directory."""++ checks: List[Tuple[str, bool, str]] = field(default_factory=list)+ warnings: List[str] = field(default_factory=list)++ @property+ def failures(self) -> List[str]:+ return [detail or name for name, ok, detail in self.checks if not ok]++ @property+ def ok(self) -> bool:+ return all(ok for _name, ok, _detail in self.checks)++ @property+ def exit_code(self) -> int:+ return 0 if self.ok else 1++ def add(self, name: str, ok: bool, detail: str = "") -> None:+ self.checks.append((name, ok, detail))++ def warn(self, message: str) -> None:+ self.warnings.append(message)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "ok": self.ok,+ "checks": [+ {"name": name, "ok": ok, "detail": detail}+ for name, ok, detail in self.checks+ ],+ "warnings": list(self.warnings),+ }+++# ─── Static checks ───────────────────────────────────────────────────────────+++def _requires_hermes_spec_valid(spec: str) -> bool:+ """Strictly validate a ``requires_hermes`` spec.++ Unlike :func:`hermes_cli.plugins._version_satisfies` (permissive at load+ time), validation REJECTS clauses whose version segment doesn't parse —+ a typo'd spec should fail admission, not silently gate nothing.+ """+ from hermes_cli.plugins import _VERSION_COMPARATOR_RE, _version_tuple++ for clause in spec.split(","):+ clause = clause.strip()+ if not clause:+ continue+ m = _VERSION_COMPARATOR_RE.match(clause)+ target = m.group(2) if m else clause+ if _version_tuple(target) is None:+ return False+ return True+++def _check_manifest_fields(report: ValidationReport, manifest: dict) -> None:+ missing = [+ f for f in ("name", "version", "description") if not manifest.get(f)+ ]+ if missing:+ report.add(+ "manifest fields",+ False,+ f"plugin.yaml missing required field(s): {', '.join(missing)}",+ )+ else:+ report.add("manifest fields", True, "name, version, description present")+++def _check_requires_hermes(report: ValidationReport, manifest: dict) -> None:+ spec = str(manifest.get("requires_hermes") or "").strip()+ if not spec:+ report.add("requires_hermes", True, "not declared")+ return+ if _requires_hermes_spec_valid(spec):+ report.add("requires_hermes", True, f"spec {spec!r} parses")+ else:+ report.add(+ "requires_hermes",+ False,+ f"requires_hermes spec {spec!r} does not parse "+ "(expected e.g. \">=0.19\" or \">=0.19, <1.0\")",+ )+++def _check_config_spec(report: ValidationReport, manifest: dict) -> None:- raw = manifest.get("config")++ """Validate the manifest ``config_schema`` mapping (#64165 format)."""++ raw = manifest.get("config_schema")+ if raw in (None, [], {}):- report.add("config spec", True, "not declared")++ report.add("config schema", True, "not declared")+ return+ problems: List[str] = []- if not isinstance(raw, list):- problems.append("config: must be a list of mappings")++ if not isinstance(raw, dict):++ problems.append("config_schema: must be a mapping of key -> spec")+ else:- for i, item in enumerate(raw):- if not isinstance(item, dict) or not item.get("key"):- problems.append(f"config[{i}]: must be a mapping with a 'key'")++ for skey, spec in raw.items():++ if not isinstance(spec, dict):++ problems.append(++ f"config_schema.{skey}: must be a mapping (e.g. {{type: str}})"++ )+ continue- typ = item.get("type")- if typ is not None and str(typ) not in _CONFIG_TYPES:++ typ = spec.get("type")++ if typ is not None and str(typ).lower() not in _CONFIG_TYPES:+ problems.append(- f"config[{i}] ({item['key']}): type must be one of "++ f"config_schema.{skey}: type must be one of "+ f"{'/'.join(sorted(_CONFIG_TYPES))}"+ )- secret = item.get("secret")- if secret is not None and not isinstance(secret, bool):++ required = spec.get("required")++ if required is not None and not isinstance(required, bool):+ problems.append(- f"config[{i}] ({item['key']}): secret must be a boolean"++ f"config_schema.{skey}: required must be a boolean"+ )+ if problems:- report.add("config spec", False, "; ".join(problems))++ report.add("config schema", False, "; ".join(problems))+ else:- report.add("config spec", True, "shape valid")++ report.add("config schema", True, "shape valid")+++def _check_requires_env(report: ValidationReport, manifest: dict) -> None:+ raw = manifest.get("requires_env") or []+ problems: List[str] = []+ if not isinstance(raw, list):+ problems.append("requires_env: must be a list")+ raw = []+ for i, entry in enumerate(raw):+ if isinstance(entry, str):+ name = entry+ elif isinstance(entry, dict):+ name = str(entry.get("name") or "")+ else:+ problems.append(f"requires_env[{i}]: must be a string or mapping")+ continue+ if not _UPPER_SNAKE_RE.match(name):+ problems.append(+ f"requires_env[{i}]: {name!r} is not UPPER_SNAKE_CASE"+ )+ if problems:+ report.add("requires_env", False, "; ".join(problems))+ else:+ report.add("requires_env", True, "all entries UPPER_SNAKE")+++# ─── Capability probe (subprocess-isolated) ──────────────────────────────────++# Self-contained harness run in a scratch child process. Imports the plugin+# module using the same file-location mechanics PluginManager uses, calls+# register() against a recording stub ctx, and prints a sentinel-prefixed+# JSON line of what was actually registered. Deliberately imports NOTHING+# from hermes so a hostile plugin only sees a bare interpreter.+_PROBE_SCRIPT = r"""+import importlib.util+import json+import sys++plugin_dir = sys.argv[1]+sentinel = sys.argv[2]++recorded = {"tools": [], "hooks": [], "middleware": [], "commands": []}+++class RecordingContext:+ plugin_config = {}+ profile_name = "default"++ def register_tool(self, name, *args, **kwargs):+ recorded["tools"].append(str(name))++ def register_hook(self, hook_name, callback):+ recorded["hooks"].append(str(hook_name))++ def register_middleware(self, kind, callback):+ recorded["middleware"].append(str(kind))++ def register_command(self, name, *args, **kwargs):+ recorded["commands"].append(str(name))++ def register_cli_command(self, name, *args, **kwargs):+ recorded["commands"].append(str(name))++ def __getattr__(self, _name):+ # Any other registration surface (platforms, providers, skills,+ # context engines, ...) is accepted as a no-op — the probe only+ # audits the declared-capability categories.+ def _noop(*args, **kwargs):+ return None++ return _noop+++def emit(payload):+ print(sentinel + json.dumps(payload))+++try:+ spec = importlib.util.spec_from_file_location(+ "hermes_validate_probe_plugin",+ plugin_dir + "/__init__.py",+ submodule_search_locations=[plugin_dir],+ )+ module = importlib.util.module_from_spec(spec)+ module.__path__ = [plugin_dir]+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+except Exception as exc:+ emit({"error": "import failed: %s" % exc})+ sys.exit(0)++register = getattr(module, "register", None)+if register is None:+ emit({"error": "no register() function"})+ sys.exit(0)++try:+ register(RecordingContext())+except Exception as exc:+ emit({"error": "register() raised: %s" % exc})+ sys.exit(0)++emit(recorded)+"""+++def _run_capability_probe(plugin_dir: Path) -> Tuple[Optional[dict], str]:+ """Run the recording probe in a scratch subprocess.++ Returns ``(recorded, error)`` — exactly one is meaningful: *recorded*+ is the ``{tools, hooks, middleware, commands}`` dict on success, and+ *error* is a human-readable failure description otherwise.+ """+ with tempfile.TemporaryDirectory(prefix="hermes-validate-") as scratch:+ env = dict(os.environ)+ env["HERMES_HOME"] = scratch+ try:+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ _PROBE_SCRIPT,+ str(plugin_dir),+ _PROBE_SENTINEL,+ ],+ capture_output=True,+ text=True,+ timeout=_PROBE_TIMEOUT,+ env=env,+ )+ except subprocess.TimeoutExpired:+ return None, f"capability probe timed out after {_PROBE_TIMEOUT}s"++ payload: Optional[dict] = None+ for line in (result.stdout or "").splitlines():+ if line.startswith(_PROBE_SENTINEL):+ try:+ payload = json.loads(line[len(_PROBE_SENTINEL):])+ except json.JSONDecodeError:+ payload = None++ if payload is None:+ err = (result.stderr or "").strip()+ return None, (+ "capability probe produced no result "+ f"(exit {result.returncode})" + (f": {err}" if err else "")+ )+ if "error" in payload:+ return None, str(payload["error"])+ return payload, ""+++def _declared_list(manifest: dict, key: str) -> List[str]:+ raw = manifest.get(key) or []+ if not isinstance(raw, list):+ return []+ return [str(item) for item in raw if isinstance(item, str)]+++def _check_capabilities(+ report: ValidationReport, manifest: dict, plugin_dir: Path+) -> Optional[dict]:+ """Probe actual registrations and diff against declared capabilities.++ Returns the recorded dict (for the built-in collision check) or None+ when the probe failed / was skipped.+ """+ if not (plugin_dir / "__init__.py").is_file():+ report.warn(+ "no __init__.py — capability probe skipped (manifest-only plugin)"+ )+ report.add("capability probe", True, "skipped (no __init__.py)")+ return None++ recorded, error = _run_capability_probe(plugin_dir)+ if recorded is None:+ report.add("capability probe", False, error)+ return None+ report.add("capability probe", True, "register() ran in isolation")++ for kind, manifest_key in (+ ("tools", "provides_tools"),+ ("hooks", "provides_hooks"),+ ("middleware", "provides_middleware"),+ ):+ declared = set(_declared_list(manifest, manifest_key))+ actual = set(recorded.get(kind) or [])+ undeclared = sorted(actual - declared)+ unregistered = sorted(declared - actual)+ if undeclared:+ report.add(+ f"declared {kind}",+ False,+ f"undeclared {kind} registered (not in {manifest_key}): "+ f"{', '.join(undeclared)}",+ )+ else:+ report.add(f"declared {kind}", True, "matches registrations")+ if unregistered:+ report.warn(+ f"{manifest_key} declares {', '.join(unregistered)} "+ f"but register() did not register them"+ )+ return recorded+++def _builtin_tool_names() -> List[str]:+ """Return the built-in tool registry names (discovery-timing safe).++ ``tools.registry`` starts empty — built-in tool modules self-register on+ import, so we must run ``discover_builtin_tools()`` first (idempotent;+ see the AGENTS.md discover_plugins timing pitfall).+ """+ try:+ from tools.registry import discover_builtin_tools, registry++ discover_builtin_tools()+ return list(registry.get_all_tool_names())+ except Exception:+ return []+++def _check_builtin_collisions(+ report: ValidationReport, manifest: dict, recorded: Optional[dict]+) -> None:+ candidate_tools = set(_declared_list(manifest, "provides_tools"))+ if recorded:+ candidate_tools.update(recorded.get("tools") or [])+ if not candidate_tools:+ report.add("built-in tool collisions", True, "no tools to check")+ return+ builtin = set(_builtin_tool_names())+ collisions = sorted(candidate_tools & builtin)+ if collisions:+ report.add(+ "built-in tool collisions",+ False,+ "tool name(s) collide with built-in tools: "+ f"{', '.join(collisions)}",+ )+ else:+ report.add("built-in tool collisions", True, "no collisions")+++# ─── Entry point ─────────────────────────────────────────────────────────────+++def validate_plugin_dir(plugin_dir: Path) -> ValidationReport:+ """Run every admission check against *plugin_dir* and return the report."""+ report = ValidationReport()+ plugin_dir = Path(plugin_dir)++ if not plugin_dir.is_dir():+ report.add(+ "plugin directory", False, f"{plugin_dir} is not a directory"+ )+ return report++ manifest_file = plugin_dir / "plugin.yaml"+ if not manifest_file.is_file():+ manifest_file = plugin_dir / "plugin.yml"+ if not manifest_file.is_file():+ report.add("manifest", False, "no plugin.yaml in the plugin directory")+ return report++ import yaml++ try:+ manifest = yaml.safe_load(+ manifest_file.read_text(encoding="utf-8")+ )+ except Exception as exc:+ report.add("manifest", False, f"plugin.yaml failed to parse: {exc}")+ return report+ if not isinstance(manifest, dict):+ report.add("manifest", False, "plugin.yaml must be a mapping")+ return report+ report.add("manifest", True, "plugin.yaml parses")++ _check_manifest_fields(report, manifest)+ _check_requires_hermes(report, manifest)+ _check_config_spec(report, manifest)+ _check_requires_env(report, manifest)+ recorded = _check_capabilities(report, manifest, plugin_dir)+ _check_builtin_collisions(report, manifest, recorded)+ return reportdiff --cc hermes_cli/plugins.pyindex 1a5e93949fd,9028e285307..24bdcd4d42e--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@@ -365,6 -683,413 +770,415 @@@ def _get_enabled_plugins() -> Optional[_VALID_PLUGIN_KINDS: Set[str] = {"standalone", "backend", "exclusive", "platform", "model-provider"}+ def _portable_skill_namespace(key: str) -> str:+ """Return a readable, collision-resistant namespace for a portable plugin."""++ slug = "".join(+ ch if ch.isascii() and (ch.isalnum() or ch in "_-") else "-"+ for ch in key.lower()+ )+ slug = slug.strip("-_") or "plugin"+ digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]+ return f"agent-plugin-{slug}-{digest}"+++ def _display_author(value: object) -> str:+ """Normalize a manifest author value for the string PluginManifest field."""+ if isinstance(value, Mapping):+ return ", ".join(+ str(value[field])+ for field in ("name", "email", "url")+ if value.get(field)+ )+ return "" if value is None else str(value)+++ # ── Manifest v2 (#64165) parsing helpers ──────────────────────────────────++ # Fields the current parser understands. Anything else in plugin.yaml is+ # forward-compat surface: warn (once per manifest, at debug for v1 files to+ # avoid churning existing plugins, at warning for v2+) and continue loading.+ _KNOWN_MANIFEST_FIELDS: Set[str] = {+ # v1+ "name", "version", "description", "author", "requires_env",+ "provides_tools", "provides_hooks", "kind", "hooks", "label",+ "optional_env", "platforms", "external_dependencies", "pip_dependencies",+ "provides_browser_providers", "provides_web_providers",+ # v2 (#64165)+ "manifest_version", "api_version", "requires_plugins",+ "python_dependencies", "config_schema", "license", "homepage", "tags",+ # owned by sibling sub-issues but reserved so their manifests don't warn+ "capabilities", "emits", "listens", "hermes", "depends",++ # plugin catalog (#69446)++ "requires_hermes",+ }++ # Highest manifest schema version this Hermes understands.+ SUPPORTED_MANIFEST_VERSION = 2++ _CONFIG_SCHEMA_TYPES: Dict[str, tuple] = {+ "str": (str,),+ "string": (str,),+ "int": (int,),+ "integer": (int,),+ "float": (int, float),+ "number": (int, float),+ "bool": (bool,),+ "boolean": (bool,),+ "list": (list,),+ "array": (list,),+ "dict": (dict,),+ "object": (dict,),+ }+++ def _parse_manifest_v2_fields(data: Mapping, key: str) -> Dict[str, Any]:+ """Validate and normalize the manifest v2 fields (#64165).++ Returns kwargs for :class:`PluginManifest`. Every problem is a warning,+ never a load failure — v2 metadata is advisory and additive.+ """+ out: Dict[str, Any] = {}++ # manifest_version — absent means v1 (supported forever).+ raw_mv = data.get("manifest_version", 1)+ try:+ mv = int(raw_mv)+ except (TypeError, ValueError):+ logger.warning(+ "Plugin %s: manifest_version %r is not an integer; treating as 1",+ key, raw_mv,+ )+ mv = 1+ if mv > SUPPORTED_MANIFEST_VERSION:+ logger.warning(+ "Plugin %s: manifest_version %d is newer than this Hermes "+ "supports (%d); loading anyway and ignoring unknown fields",+ key, mv, SUPPORTED_MANIFEST_VERSION,+ )+ out["manifest_version"] = mv++ # api_version — plugin API generation (independent of manifest_version).+ raw_api = data.get("api_version")+ if raw_api is None:+ out["api_version"] = None+ else:+ try:+ out["api_version"] = int(raw_api)+ except (TypeError, ValueError):+ logger.warning(+ "Plugin %s: api_version %r is not an integer; ignoring", key, raw_api,+ )+ out["api_version"] = None++ # requires_plugins — list of {id, version_range?} (str shorthand ok).+ deps: List[Dict[str, Any]] = []+ raw_deps = data.get("requires_plugins")+ if raw_deps is not None and not isinstance(raw_deps, list):+ logger.warning(+ "Plugin %s: requires_plugins must be a list; ignoring", key,+ )+ raw_deps = None+ for item in raw_deps or []:+ if isinstance(item, str):+ deps.append({"id": item, "version_range": None})+ elif isinstance(item, Mapping) and isinstance(item.get("id"), str) and item["id"]:+ vr = item.get("version_range")+ deps.append({+ "id": item["id"],+ "version_range": str(vr) if vr is not None else None,+ })+ else:+ logger.warning(+ "Plugin %s: requires_plugins entry %r must be a plugin id "+ "string or a {id, version_range} mapping; skipping", key, item,+ )+ out["requires_plugins"] = deps++ # python_dependencies — declared pip requirement strings. Validated and+ # surfaced ONLY; never auto-installed (isolation design deferred).+ pydeps: List[str] = []+ raw_pydeps = data.get("python_dependencies")+ if raw_pydeps is not None and not isinstance(raw_pydeps, list):+ logger.warning(+ "Plugin %s: python_dependencies must be a list of requirement "+ "strings; ignoring", key,+ )+ raw_pydeps = None+ for item in raw_pydeps or []:+ if isinstance(item, str) and item.strip():+ pydeps.append(item.strip())+ else:+ logger.warning(+ "Plugin %s: python_dependencies entry %r must be a non-empty "+ "requirement string; skipping", key, item,+ )+ out["python_dependencies"] = pydeps++ # config_schema — mapping of key -> {type?, default?, description?, required?}.+ raw_schema = data.get("config_schema")+ schema: Dict[str, Any] = {}+ if raw_schema is not None and not isinstance(raw_schema, Mapping):+ logger.warning(+ "Plugin %s: config_schema must be a mapping; ignoring", key,+ )+ raw_schema = None+ for skey, spec in (raw_schema or {}).items():+ if not isinstance(spec, Mapping):+ logger.warning(+ "Plugin %s: config_schema entry %r must be a mapping "+ "(e.g. {type: str}); skipping", key, skey,+ )+ continue+ stype = spec.get("type")+ if stype is not None and str(stype).lower() not in _CONFIG_SCHEMA_TYPES:+ logger.warning(+ "Plugin %s: config_schema key %r declares unknown type %r "+ "(known: %s); type check will be skipped for it",+ key, skey, stype, ", ".join(sorted(_CONFIG_SCHEMA_TYPES)),+ )+ schema[str(skey)] = dict(spec)+ out["config_schema"] = schema++ # Standard metadata.+ out["license"] = str(data.get("license") or "")+ out["homepage"] = str(data.get("homepage") or "")+ raw_tags = data.get("tags")+ if raw_tags is not None and not isinstance(raw_tags, list):+ logger.warning("Plugin %s: tags must be a list; ignoring", key)+ raw_tags = None+ out["tags"] = [str(t) for t in (raw_tags or [])]++ # Forward compat: unknown fields warn (never fail). Keep v1 manifests+ # quiet at warning level — they predate the known-field census.+ unknown = sorted(set(data.keys()) - _KNOWN_MANIFEST_FIELDS)+ if unknown:+ log = logger.warning if mv >= 2 else logger.debug+ log(+ "Plugin %s: unknown manifest field(s) ignored: %s "+ "(newer manifest schema or typo; plugin still loads)",+ key, ", ".join(unknown),+ )++ return out+++ def validate_config_schema(+ plugin_id: str,+ schema: Mapping,+ settings: Mapping,+ ) -> List[str]:+ """Validate a plugin's config entry against its declared config_schema.++ Returns a list of human-actionable warning strings. Never raises;+ schema mismatches must not block plugin load (#64165).+ """+ warnings: List[str] = []+ if not isinstance(schema, Mapping) or not isinstance(settings, Mapping):+ return warnings+ for skey, spec in schema.items():+ if not isinstance(spec, Mapping):+ continue+ present = skey in settings+ if not present:+ if spec.get("required") and "default" not in spec:+ warnings.append(+ f"plugins.entries.{plugin_id}.settings.{skey} is required "+ "by the plugin's config_schema but is not set"+ )+ continue+ stype = spec.get("type")+ expected = _CONFIG_SCHEMA_TYPES.get(str(stype).lower()) if stype else None+ if expected is not None:+ value = settings[skey]+ # bool is an int subclass — don't let True satisfy int/float.+ ok = isinstance(value, expected) and not (+ isinstance(value, bool) and bool not in expected+ )+ if not ok:+ warnings.append(+ f"plugins.entries.{plugin_id}.settings.{skey} should be "+ f"{stype} (got {type(value).__name__})"+ )+ return warnings+++ def resolve_plugin_load_order(+ manifests: Mapping[str, "PluginManifest"],+ ) -> List[str]:+ """Return plugin keys in dependency-respecting load order (#64165).++ When A requires B, B sorts before A (so B's ``register()`` runs first).+ Ties break alphabetically for determinism. Dependency cycles are+ detected, warned about, and the members of the cycle fall back to+ alphabetical order after every non-cycle plugin they depend on.+ Missing dependencies are warned about here (once, at discovery) but do+ not remove the dependent plugin from the order — loads never hard-fail+ on a missing advisory dependency.+ """+ import graphlib++ keys = sorted(manifests.keys())+ by_name: Dict[str, str] = {}+ for k in keys:+ name = manifests[k].name+ if name and name not in by_name:+ by_name[name] = k++ def _resolve_dep(dep_id: str) -> Optional[str]:+ if dep_id in manifests:+ return dep_id+ return by_name.get(dep_id)++ edges: Dict[str, Set[str]] = {k: set() for k in keys}+ for k in keys:+ for dep in manifests[k].requires_plugins:+ dep_id = dep.get("id") if isinstance(dep, Mapping) else None+ if not dep_id:+ continue+ resolved = _resolve_dep(dep_id)+ if resolved is None:+ logger.warning(+ "Plugin %s requires plugin '%s' which is not enabled/"+ "installed; loading anyway (probe availability at runtime "+ "via ctx.has_plugin). Run `hermes plugins enable %s` if "+ "it is installed.",+ k, dep_id, dep_id,+ )+ continue+ if resolved == k:+ logger.warning("Plugin %s declares a dependency on itself; ignoring", k)+ continue+ edges[k].add(resolved)++ sorter = graphlib.TopologicalSorter(edges)+ try:+ sorter.prepare()+ except graphlib.CycleError as exc:+ cycle = exc.args[1] if len(exc.args) > 1 else []+ logger.warning(+ "Plugin dependency cycle detected (%s); falling back to "+ "alphabetical load order for all plugins",+ " -> ".join(str(c) for c in cycle),+ )+ return keys++ ordered: List[str] = []+ while sorter.is_active():+ ready = sorted(sorter.get_ready())+ ordered.extend(ready)+ sorter.done(*ready)+ return ordered+++ def _detect_kind_from_source(source_text: str) -> Optional[str]:+ """Return the plugin kind implied by source markers, or ``None``.++ Mirrors ``plugins/memory/__init__.py:_is_memory_provider_dir``: a+ module that registers a memory provider (``register_memory_provider``+ or ``MemoryProvider``) belongs to the memory-provider discovery+ system (``exclusive``); a module that registers a model provider+ (``register_provider`` + ``ProviderProfile``) belongs to the+ providers discovery (``model-provider``). Applied to both directory+ plugins and pip entry-point plugins so neither is eagerly imported+ by the general PluginManager.+ """+ if "register_memory_provider" in source_text or "MemoryProvider" in source_text:+ return "exclusive"+ if "register_provider" in source_text and "ProviderProfile" in source_text:+ return "model-provider"+ return None+++ def _read_source_from_origin(origin: Optional[str], limit: int = 8192) -> str:+ """Read the first ``limit`` chars of a module's source file.++ Returns ``""`` on any failure (callers fall back to ``standalone``).+ ``.pyc``/``.pyo`` origins are mapped back to their source path so+ source is still scanned when only the bytecode cache is present.+ """+ if not origin:+ return ""+ if origin.endswith((".pyc", ".pyo")):+ try:+ origin = importlib.util.source_from_cache(origin)+ except Exception:+ return ""+ if not origin.endswith(".py"):+ return ""+ try:+ return Path(origin).read_text(encoding="utf-8", errors="replace")[:limit]+ except Exception:+ return ""+++ def resolve_module_origin(module_name: str) -> Optional[str]:+ """Return a module's source path WITHOUT importing it, or ``None``.++ ``importlib.util.find_spec`` on a dotted name imports the parent+ package first (executing its ``__init__.py``), which would run+ arbitrary package initialization during discovery and pay the very+ import cost this exists to avoid — a provider whose heavy imports+ live in ``package/__init__.py`` would still pay them.++ Only the top-level name is resolved with ``find_spec`` (import-free+ for top-level names); the remaining dotted segments are walked+ through ``submodule_search_locations`` by hand, mirroring the file+ layout conventions of the default PathFinder (``part.py`` module or+ ``part/__init__.py`` package). Namespace packages, zipped modules,+ extension modules, and anything else unexpected return ``None``.++ Shared with ``plugins/memory/__init__.py``, which needs the directory+ of a pip-installed provider to find its ``config_schema.py`` and+ ``cli.py`` — both of which are loaded by path precisely so the+ provider module never has to be imported.+ """+ parts = [p for p in module_name.split(".") if p]+ if not parts:+ return None+ try:+ spec = importlib.util.find_spec(parts[0])+ if spec is None or not spec.origin:+ return None+ if len(parts) == 1:+ return spec.origin++ search_paths = spec.submodule_search_locations+ if not search_paths:+ return None+ for i, part in enumerate(parts[1:], start=2):+ found_origin = None+ next_paths = None+ for base in search_paths:+ base = Path(base)+ pkg_init = base / part / "__init__.py"+ if pkg_init.is_file():+ found_origin = str(pkg_init)+ next_paths = [base / part]+ break+ mod_file = base / (part + ".py")+ if mod_file.is_file():+ found_origin = str(mod_file)+ break+ if found_origin is None:+ return None+ if i == len(parts) or next_paths is None:+ return found_origin+ search_paths = next_paths+ return None+ except Exception:+ return None+++ def _resolve_module_source(module_name: str, limit: int = 8192) -> str:+ """First ``limit`` chars of a module's source, without importing it.++ Empty string when the module cannot be resolved or read, which+ callers treat as ``standalone`` — the safe default.+ """+ return _read_source_from_origin(resolve_module_origin(module_name), limit)++@dataclassclass PluginManifest:"""Parsed representation of a plugin.yaml manifest."""@@@ -400,16 -1125,88 +1214,92 @@@# category plugin at ``plugins/image_gen/openai/`` the key is# ``image_gen/openai``. When empty, falls back to ``name``.key: str = ""+ # Minimum/exact Hermes version requirement, e.g. ``">=0.19"``. Empty =+ # no requirement. Checked at load time; unsatisfied plugins are recorded+ # with an error and skipped (no register() call, no traceback).+ requires_hermes: str = ""- # Declared config keys from the manifest's ``config:`` section — a list- # of ``{key, prompt, type (str|bool|int), default, secret (bool)}``- # dicts. secret=true values are prompted into ~/.hermes/.env; secret- # =false values live under ``plugins.entries.<plugin_id>.<key>`` in- # config.yaml. Exposed to plugins via ``ctx.plugin_config``.- config_spec: List[Dict[str, Any]] = field(default_factory=list)+ portable: bool = False+ skill_namespace: str = ""+ # Declared capability ids from the manifest ``capabilities:`` list+ # (#64228). Normalized to KNOWN ids only — see+ # ``hermes_cli.plugin_capabilities.CAPABILITY_REGISTRY``. Declaration is+ # consent metadata, not a grant: a capability is live only when the user+ # granted it (``plugins.entries.<id>.granted_capabilities``) or the+ # deprecated legacy ``allow_*`` key is set.+ capabilities: List[str] = field(default_factory=list)+ # ── Manifest v2 fields (#64165) — all optional and additive ──────────+ # Manifest SCHEMA version. Absent (v1) manifests are fully supported+ # forever. This versions the *file format* only; it is deliberately+ # independent from ``api_version`` (the runtime plugin API generation).+ manifest_version: int = 1+ # Runtime plugin API generation the plugin targets (ctx surface /+ # hook signatures). ``None`` = unspecified (treated as current-compatible).+ api_version: Optional[int] = None+ # Inter-plugin dependencies: list of {"id": str, "version_range": str|None}.+ # Advisory: a missing dependency logs a warning but the plugin still+ # loads (plugins can probe availability via ``ctx.has_plugin``). Load+ # ORDER honors these edges: if A requires B, B registers first.+ requires_plugins: List[Dict[str, Any]] = field(default_factory=list)+ # Declared pip dependencies. VALIDATED AND SURFACED ONLY — Hermes never+ # auto-installs these (isolation design for the install seam is a+ # deferred follow-up; see #64165 round-2 review and #15220).+ python_dependencies: List[str] = field(default_factory=list)+ # JSON-schema-ish mapping describing keys under+ # ``plugins.entries.<id>.settings``. Validated at load; mismatches are+ # warnings, never load failures.+ config_schema: Dict[str, Any] = field(default_factory=dict)+ # Formalized standard metadata.+ license: str = ""+ homepage: str = ""+ tags: List[str] = field(default_factory=list)+ # Inter-plugin event bus declarations (advisory in v1 — NOT enforced).+ # ``emits`` lists the bare event names this plugin publishes under its own+ # ``<key>:`` namespace (e.g. ``["ping"]`` → publishes ``<key>:ping``).+ # ``listens`` lists the fully-qualified ``<plugin>:<event>`` names this+ # plugin subscribes to. Both are purely for discoverability+ # (``hermes plugins show``); a plugin may emit/subscribe without declaring.+ emits: List[str] = field(default_factory=list)+ listens: List[str] = field(default_factory=list)+++ @dataclass(frozen=True)+ class PluginSystemPromptSection:+ """A plugin-owned section rendered once for each new session."""++ id: str+ content: Union[str, Callable[[Mapping[str, Any]], str]]+ position: str+ max_chars: int+ plugin: str+++ @dataclass(frozen=True)+ class RenderedPluginSystemPromptSection:+ """Validated prompt bytes frozen on the owning AIAgent."""++ id: str+ content: str+ position: str+ plugin: str+++ @dataclass(frozen=True)+ class _EventSubscription:+ """Host-owned subscription ledger entry."""++ owner: str+ callback: Callable+++ @dataclass(frozen=True)+ class _QueuedPluginEvent:+ """Immutable dispatch envelope consumed by the event worker."""++ event: str+ payload: Dict[str, Any]+ subscriptions: tuple[_EventSubscription, ...]+ depth: int+ generation: int@dataclass@@@ -1793,8 -4833,12 +4926,13 @@@ class PluginManagerpath=str(plugin_dir),kind=kind,key=key,+ requires_hermes=str(data.get("requires_hermes") or "").strip(),- config_spec=config_spec,+ capabilities=_parse_declared_capabilities(+ data.get("capabilities"), name+ ),+ **v2_fields,+ emits=data.get("emits") or [],+ listens=data.get("listens") or [],)except Exception as exc:logger.warning(@@@ -1898,25 -5217,12 +5311,30 @@@def _load_plugin(self, manifest: PluginManifest) -> None:"""Import a plugin module and call its ``register(ctx)`` function."""+ with self._discovery_lock, _plugin_home_scope(self.home_path):+ self._load_plugin_scoped(manifest)++ def _load_plugin_scoped(self, manifest: PluginManifest) -> None:+ """Load one plugin with the manager's home bound as current."""loaded = LoadedPlugin(manifest=manifest)++ # requires_hermes gate — skip cleanly (no import, no traceback) when+ # the running Hermes version doesn't satisfy the manifest spec.+ if manifest.requires_hermes:+ current = _running_hermes_version()+ if not _version_satisfies(manifest.requires_hermes, current):+ loaded.enabled = False+ loaded.error = (+ f"requires hermes {manifest.requires_hermes}, "+ f"running {current}"+ )+ self._plugins[manifest.key or manifest.name] = loaded+ logger.warning(+ "Plugin '%s' skipped: %s",+ manifest.key or manifest.name, loaded.error,+ )+ return+logger.debug("Loading plugin '%s' (source=%s, kind=%s, path=%s)",manifest.key or manifest.name, manifest.source, manifest.kind, manifest.path,diff --cc hermes_cli/plugins_cmd.pyindex 363d647a6db,912d93208d2..00ddbe65e1d--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -446,66 -557,194 +557,227 @@@ def _require_installed_plugin(name: str# ---------------------------------------------------------------------------+ _EXACT_COMMIT_RE = re.compile(r"^[0-9a-fA-F]{40}$")+ _INSTALL_METADATA_FILE = ".install-metadata.json"++ def _install_metadata_path() -> Path:+ return get_hermes_home() / "plugins" / _INSTALL_METADATA_FILE+++ def _read_install_metadata() -> dict[str, dict[str, object]]:+ """Read profile-local, non-secret plugin source metadata from disk."""+ path = _install_metadata_path()+ if not path.exists():+ return {}+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise PluginOperationError(f"Could not read plugin install metadata: {exc}") from exc+ if not isinstance(value, dict):+ raise PluginOperationError("Plugin install metadata must be a JSON object.")+ return value+++ def _write_install_metadata(metadata: dict[str, dict[str, object]]) -> None:+ """Atomically replace the profile-local plugin install metadata sidecar."""+ path = _install_metadata_path()+ atomic_write_text(+ path,+ json.dumps(metadata, indent=2, sort_keys=True) + "\n",+ tmp_prefix=f"{path.name}.tmp-",+ )+++ def _normalize_exact_revision(ref: str) -> str:+ if not isinstance(ref, str) or not _EXACT_COMMIT_RE.fullmatch(ref):+ raise PluginOperationError("--ref must be a full 40-character commit SHA.")+ return ref.lower()+++ def _safe_git_error(result: subprocess.CompletedProcess, source_url: str = "") -> str:+ """Return diagnosable Git output without echoing embedded credentials."""+ from agent.redact import redact_sensitive_text++ error = (result.stderr or result.stdout or "").strip()+ if source_url:+ error = error.replace(source_url, _scrub_git_url(source_url))+ return redact_sensitive_text(error)+++ def _git_head_revision(repo: Path, git_exe: str) -> str:+ result = subprocess.run(+ [git_exe, "rev-parse", "HEAD"],+ cwd=str(repo),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=15,+ stdin=subprocess.DEVNULL,+ env=noninteractive_git_env(),+ )+ if result.returncode != 0:+ err = _safe_git_error(result)+ raise PluginOperationError(f"Could not determine installed Git revision:\n{err}")+ return result.stdout.strip().lower()+++ def _checkout_exact_revision(repo: Path, git_exe: str, revision: str) -> None:+ """Fetch and detach at one immutable commit, then verify the resulting HEAD."""+ try:+ fetched = subprocess.run(+ [git_exe, "fetch", "--depth", "1", "origin", revision],+ cwd=str(repo),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=60,+ stdin=subprocess.DEVNULL,+ env=noninteractive_git_env(),+ )+ except subprocess.TimeoutExpired as exc:+ raise PluginOperationError(+ f"Git fetch of commit '{revision}' timed out after 60 seconds."+ ) from exc+ if fetched.returncode != 0:+ err = _safe_git_error(fetched)+ raise PluginOperationError(+ f"Git commit '{revision}' could not be fetched:\n{err}"+ )+ try:+ checked_out = subprocess.run(+ [git_exe, "checkout", "--detach", revision],+ cwd=str(repo),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=60,+ stdin=subprocess.DEVNULL,+ env=noninteractive_git_env(),+ )+ except subprocess.TimeoutExpired as exc:+ raise PluginOperationError(+ f"Git checkout of commit '{revision}' timed out after 60 seconds."+ ) from exc+ if checked_out.returncode != 0:+ err = _safe_git_error(checked_out)+ raise PluginOperationError(+ f"Git checkout of commit '{revision}' failed:\n{err}"+ )+ actual = _git_head_revision(repo, git_exe)+ if actual != revision:+ raise PluginOperationError(+ f"Checked-out revision '{actual}' does not match requested commit '{revision}'."+ )+++ def _scrub_git_url(git_url: str) -> str:+ """Strip credentials and query/fragment data from an HTTP Git URL."""+ parsed = urllib.parse.urlsplit(git_url)+ if parsed.scheme in {"http", "https"} and parsed.hostname:+ host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname+ if parsed.port is not None:+ host = f"{host}:{parsed.port}"+ return urllib.parse.urlunsplit(+ (parsed.scheme, host, parsed.path, "", "")+ )+ return git_url+++ def _canonical_source(git_url: str, subdir: Optional[str]) -> str:+ scrubbed = _scrub_git_url(git_url)+ return f"{scrubbed}#{subdir}" if subdir else scrubbed+++ def _scrub_cloned_origin(repo: Path, git_exe: str, git_url: str) -> None:+ """Ensure credentials used for cloning do not survive in ``.git/config``."""+ scrubbed = _scrub_git_url(git_url)+ if scrubbed == git_url:+ return+ result = subprocess.run(+ [git_exe, "remote", "set-url", "origin", scrubbed],+ cwd=str(repo),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=15,+ stdin=subprocess.DEVNULL,+ env=noninteractive_git_env(),+ )+ if result.returncode != 0:+ err = _safe_git_error(result, git_url)+ raise PluginOperationError(f"Could not sanitize installed Git remote:\n{err}")+++def _raise_removed(removed) -> None:+ """Raise PluginOperationError describing a blocklisted plugin."""+ detail = removed.reason or "no reason recorded"+ if removed.date:+ detail += f" (removed {removed.date})"+ raise PluginOperationError(+ f"Plugin '{removed.name}' was removed from the Hermes plugin "+ f"catalog and is blocked from installation: {detail}"+ )++def _install_plugin_core(identifier: str,*,force: bool,ref: Optional[str] = None,+ scan_decision_cb=None,+ skip_removed_check: bool = False,) -> tuple[Path, dict, str]:- """Clone Git plugin into ``~/.hermes/plugins``.-- ``ref`` — optional git commit SHA (or tag) checked out after clone.- When given, the clone is full-depth (no ``--depth 1``) so any commit is- reachable.- """Clone a Git plugin and atomically record its source and exact revision."""++ """Clone a Git plugin and atomically record its source and exact revision.++ Unless ``skip_removed_check`` is set, the identifier and the resolved+ repo URL are checked against the plugin catalog's removed blocklist+ (``plugin-catalog/removed.yaml``); a hit raises ``PluginOperationError``+ with the recorded reason and date.-- Returns ``(target_dir, installed_manifest, canonical_name)``.- Raises ``PluginOperationError`` on failure.+ """- import tempfile-+ requested_revision = _normalize_exact_revision(ref) if ref is not None else None+ if not skip_removed_check:+ from hermes_cli.plugin_catalog import find_removed++ # Check the raw identifier first (catches catalog names before URL+ # resolution), then the resolved repo URL below.+ removed = find_removed(identifier)+ if removed is not None:+ _raise_removed(removed)-try:git_url, subdir = _resolve_git_url(identifier)except ValueError as e:raise PluginOperationError(str(e)) from e+ if not skip_removed_check:+ from hermes_cli.plugin_catalog import find_removed++ removed = find_removed(git_url)+ if removed is not None:+ _raise_removed(removed)+plugins_dir = _plugins_dir()+ source = _canonical_source(git_url, subdir)+ old_metadata = _read_install_metadata()++ # Reinstalling the same pinned source retains its pin, even if its plugin+ # directory was manually removed. Moving a pin requires an explicit --ref.+ if requested_revision is None:+ matching_pins = [+ entry+ for entry in old_metadata.values()+ if entry.get("source") == source and entry.get("pinned") is True+ ]+ if len(matching_pins) == 1:+ revision = matching_pins[0].get("revision")+ if isinstance(revision, str):+ requested_revision = _normalize_exact_revision(revision)- with tempfile.TemporaryDirectory() as tmp:+ with tempfile.TemporaryDirectory(prefix=".install-", dir=plugins_dir) as tmp:tmp_clone = Path(tmp) / "plugin"-git_exe = _resolve_git_executable()if not git_exe:raise PluginOperationError("git is not installed or not in PATH.")@@@ -613,98 -892,74 +925,185 @@@return target, installed_manifest, installed_name+# ---------------------------------------------------------------------------+# Catalog integration helpers+# ---------------------------------------------------------------------------++_CATALOG_SIDECAR = ".hermes-catalog.json"+++def _looks_like_catalog_name(identifier: str) -> bool:+ """True when *identifier* could be a catalog entry name (not a URL/shorthand)."""+ if not identifier or "/" in identifier or "\\" in identifier:+ return False+ if identifier.startswith(("https://", "http://", "git@", "ssh://", "file://")):+ return False+ from hermes_cli.plugin_catalog import _NAME_RE++ return bool(_NAME_RE.match(identifier))+++def _get_live_catalog_entry(name: str):+ """Look up *name* in the live-refreshed catalog (falls back in-tree)."""+ from hermes_cli.plugin_catalog import load_catalog_live++ for entry in load_catalog_live():+ if entry.name == name:+ return entry+ return None+++def _catalog_install_identifier(entry) -> str:+ """Build the ``_install_plugin_core`` identifier for a catalog entry.++ Uses the explicit ``#subdir`` fragment form understood by+ :func:`_resolve_git_url` when the entry lives in a repo subdirectory.+ """+ if entry.subdir:+ return f"{entry.repo}#{entry.subdir}"+ return entry.repo+++def _write_catalog_sidecar(target: Path, entry) -> None:+ """Record catalog provenance in ``.hermes-catalog.json`` inside *target*.++ The sidecar is how ``update``/``list``/``doctor`` know the plugin came+ from the catalog (and at which pin).+ """+ import datetime++ sidecar = {+ "catalog_name": entry.name,+ "repo": entry.repo,+ "sha": entry.sha,+ "installed_at": datetime.datetime.now(datetime.timezone.utc)+ .isoformat(timespec="seconds")+ .replace("+00:00", "Z"),+ "tier": entry.tier,+ }+ try:+ (target / _CATALOG_SIDECAR).write_text(+ json.dumps(sidecar, indent=2) + "\n", encoding="utf-8"+ )+ except OSError as exc:+ logger.warning("Failed to write catalog sidecar in %s: %s", target, exc)+++def _read_catalog_sidecar(plugin_dir: Path) -> Optional[dict]:+ """Return the parsed catalog provenance sidecar, or None."""+ path = plugin_dir / _CATALOG_SIDECAR+ if not path.is_file():+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ # Unreadable / corrupt sidecar — treat as a non-catalog install.+ return None+ return data if isinstance(data, dict) else None++++# Public aliases used by the dashboard web server.++write_catalog_sidecar = _write_catalog_sidecar++read_catalog_sidecar = _read_catalog_sidecar++++++def _removed_annotation(name: str, dir_path) -> Optional[str]:++ """Return the removed-blocklist reason when *name* matches, else None."""++ try:++ from hermes_cli.plugin_catalog import find_removed++ except Exception:++ return None++ candidates = [name]++ if dir_path:++ try:++ sidecar = _read_catalog_sidecar(Path(dir_path))++ except Exception:++ sidecar = None++ if sidecar:++ candidates.extend(++ str(v) for v in (sidecar.get("catalog_name"), sidecar.get("repo")) if v++ )++ for candidate in candidates:++ removed = find_removed(candidate)++ if removed is not None:++ return removed.reason or "no reason recorded"++ return None+++++ def _looks_like_bare_index_name(identifier: str) -> bool:+ """True when *identifier* is a bare plugin name (no slash, not a URL).++ Bare names are resolved through the community plugin index; anything with+ a slash or URL scheme keeps the existing owner/repo / Git URL semantics.+ """+ if "/" in identifier or "\\" in identifier:+ return False+ return not identifier.startswith(("https://", "http://", "git@", "ssh://", "file://"))+++ def _resolve_index_name(identifier: str, console) -> tuple[str, Optional[str]]:+ """Resolve a bare plugin name to ``(install_identifier, pinned_ref)``.++ Exits with an error when the name is unknown, or lists candidates and+ exits when the name is ambiguous. The returned ref is only used when it+ is an exact 40-character commit SHA (the pin format the installer+ accepts); tag refs are surfaced as advisory output instead.+ """+ from hermes_cli.plugin_index import SECURITY_FOOTER, load_index, resolve_name++ entries, source = load_index()+ entry, candidates = resolve_name(entries, identifier)+ if entry is None:+ if len(candidates) > 1:+ console.print(+ f"[red]Error:[/red] Plugin name '{identifier}' is ambiguous in the "+ f"community index ({source}). Candidates:"+ )+ for c in candidates:+ console.print(f" {c.name} → {c.install_identifier}")+ console.print("Re-run with the exact name or the owner/repo identifier.")+ else:+ console.print(+ f"[red]Error:[/red] Plugin '{identifier}' was not found in the "+ f"community index ({source}). Use `hermes plugins search <term>` to "+ "browse, or install directly with an owner/repo identifier."+ )+ sys.exit(1)++ pinned_ref: Optional[str] = None+ if entry.ref and _EXACT_COMMIT_RE.fullmatch(entry.ref):+ pinned_ref = entry.ref.lower()+ elif entry.ref:+ console.print(+ f"[dim]Index pins ref '{entry.ref}' (not an exact commit SHA); "+ "installing the default branch head instead.[/dim]"+ )+ console.print(+ f"[dim]Resolved '{entry.name}' via community index ({source}) → "+ f"{entry.install_identifier}"+ + (f" @ {pinned_ref[:12]}[/dim]" if pinned_ref else "[/dim]")+ )+ console.print(f"[dim]{SECURITY_FOOTER}[/dim]")+ return entry.install_identifier, pinned_ref++def cmd_install(identifier: str,force: bool = False,enable: Optional[bool] = None,+ ref: Optional[str] = None,+ allow_removed: bool = False,) -> None:- """Install a plugin from the catalog, a Git URL, or owner/repo shorthand.- """Install a plugin from a Git URL, owner/repo shorthand, or index name.++ """Install a plugin from the curated catalog, community index, or Git URL.+- When *identifier* matches a catalog entry name (and is not a URL or- ``owner/repo`` shorthand), the install resolves to the entry's pinned- commit SHA and records catalog provenance in a ``.hermes-catalog.json``- sidecar. Raw git URLs keep the direct flow but are flagged as custom- (unreviewed) sources.++ Bare names are resolved first against the curated in-tree catalog++ (``plugin-catalog/``) — a hit pins the install to the catalog's reviewed++ commit SHA and records provenance in a ``.hermes-catalog.json`` sidecar.++ Names not in the catalog fall back to the community plugin index++ (unreviewed; index pin honored). URLs/shorthand install directly and are++ flagged as custom sources. An explicit ``--ref`` always wins over any pin.- Bare names (no slash, no URL scheme) are resolved through the community- plugin index to ``owner/repo`` plus the index-pinned ref. An explicit- ``--ref`` always wins over the index pin.+ ``allow_removed=True`` bypasses the removed-blocklist check (loudly).After install, prompt "Enable now? [y/N]" unless *enable* is provided(True = auto-enable without prompting, False = install disabled).@@@ -713,50 -968,10 +1112,53 @@@console = Console()- if _looks_like_bare_index_name(identifier):+ entry = None+ if _looks_like_catalog_name(identifier):++ entry = _get_live_catalog_entry(identifier)++ if entry is not None:+ from hermes_cli.plugin_catalog import (+ entry_capability_summary,+ find_removed,+ )+- entry = _get_live_catalog_entry(identifier)- if entry is None:- console.print(- f"[red]Error:[/red] '{identifier}' is not in the Hermes "- "plugin catalog and is not a Git URL or owner/repo "- "shorthand.\n"- "Browse available entries with `hermes plugins search`."- )- sys.exit(1)+ if not allow_removed:+ removed = find_removed(entry.name) or find_removed(entry.repo)+ if removed is not None:+ try:+ _raise_removed(removed)+ except PluginOperationError as e:+ console.print(f"[red]Error:[/red] {e}")+ sys.exit(1)+ console.print(+ f"[bold]{entry.name}[/bold] "+ f"[cyan]\\[{entry.tier}][/cyan] "+ f"[dim]pinned @ {entry.sha[:8]}[/dim]"+ )+ console.print(entry_capability_summary(entry))+ identifier = _catalog_install_identifier(entry)++ if ref is None:++ ref = entry.sha++ elif _looks_like_bare_index_name(identifier):++ console.print(++ "[yellow]Warning:[/yellow] not in the curated Hermes catalog — "++ "resolving through the community index (unreviewed)."++ )+ identifier, index_ref = _resolve_index_name(identifier, console)+ if ref is None:+ ref = index_ref+ else:+ console.print(+ "[yellow]Warning:[/yellow] custom (unreviewed) source — "+ "not from the Hermes catalog."+ )++ if allow_removed:+ console.print(+ "[bold red]WARNING:[/bold red] [red]--allow-removed set — "+ "skipping the removed-plugin blocklist check. This plugin may "+ "have been removed from the catalog for security reasons. "+ "Proceed at your own risk.[/red]"+ )try:git_url, _subdir = _resolve_git_url(identifier)@@@ -779,17 -1011,17 +1198,21 @@@target, installed_manifest, installed_name = _install_plugin_core(identifier,force=force,- ref=entry.sha if entry is not None else None,+ ref=ref,+ scan_decision_cb=_interactive_scan_decision,+ skip_removed_check=allow_removed,)+ except PluginScanBlocked as e:+ console.print(f"[red]Blocked:[/red] {e}")+ sys.exit(1)except PluginOperationError as e:console.print(f"[red]Error:[/red] {e}")sys.exit(1)+ if entry is not None:+ _write_catalog_sidecar(target, entry)+- if not (target / "plugin.yaml").exists() and not (target / "plugin.yml").exists() and not (+ if not (target / "plugin.yaml").exists() and not (target / "plugin.yml").exists() and not (target / "plugin.json").exists() and not (target / "__init__.py").exists():console.print(@@@ -854,11 -1094,22 +1285,28 @@@ def cmd_update(name: str) -> Noneconsole.print(f"[red]Error:[/red] {e}")sys.exit(1)++ # Catalog installs re-pin to the current catalog SHA — never `git pull`.+ sidecar = _read_catalog_sidecar(target)+ if sidecar is not None and sidecar.get("catalog_name"):+ _update_catalog_plugin(name, target, sidecar, console)+ return++ try:+ metadata = _read_install_metadata()+ except PluginOperationError as exc:+ console.print(f"[red]Error:[/red] {exc}")+ sys.exit(1)+ install_record = metadata.get(target.name, {})+ if install_record.get("pinned") is True:+ recorded_source = escape(str(install_record.get("source", "<source>")))+ console.print(+ f"[red]Error:[/red] Plugin '{name}' is pinned to "+ f"{install_record.get('revision')}. To move it, run "+ f"`hermes plugins install {recorded_source} --force "+ "--ref <40-character commit SHA>`."+ )+ sys.exit(1)+if not (target / ".git").exists():console.print(f"[red]Error:[/red] Plugin '{name}' was not installed from git "@@@ -886,55 -1204,35 +1401,84 @@@console.print(f"[dim]{out}[/dim]")+ def _remove_plugin_core(target: Path) -> None:+ """Remove one plugin and its metadata without splitting their state."""+ metadata = _read_install_metadata()+ if target.name not in metadata:+ shutil.rmtree(target)+ return++ updated = dict(metadata)+ updated.pop(target.name)+ staging = Path(+ tempfile.mkdtemp(prefix=f".{target.name}.remove-", dir=target.parent)+ )+ backup = staging / "plugin"+ os.replace(target, backup)+ try:+ _write_install_metadata(updated)+ except Exception:+ try:+ os.replace(backup, target)+ except OSError as restore_exc:+ raise PluginOperationError(+ f"Plugin metadata update failed and '{target.name}' could not be "+ f"restored automatically; recovery copy remains at {backup}."+ ) from restore_exc+ shutil.rmtree(staging, ignore_errors=True)+ raise+ shutil.rmtree(staging)+++def _update_catalog_plugin(name: str, target: Path, sidecar: dict, console) -> None:+ """Re-pin a catalog-installed plugin to the current catalog SHA."""+ catalog_name = str(sidecar.get("catalog_name") or name)+ entry = _get_live_catalog_entry(catalog_name)+ if entry is None:+ console.print(+ f"[red]Error:[/red] Plugin '{catalog_name}' is no longer in the "+ "catalog — it may have been removed. Check "+ "`hermes plugins doctor` and the removed blocklist."+ )+ sys.exit(1)++ installed_sha = str(sidecar.get("sha") or "").strip().lower()+ if installed_sha == entry.sha:+ console.print(+ f"[green]✓[/green] Plugin [bold]{catalog_name}[/bold] is "+ f"already at catalog pin ({entry.sha[:8]})."+ )+ return++ console.print(+ f"[dim]Updating {catalog_name} to catalog pin:[/dim] "+ f"{installed_sha[:8] or '(unknown)'} → {entry.sha[:8]}"+ )++ # Preserve enabled state across the force reinstall.+ was_enabled = _get_enabled_set()++ try:+ new_target, _manifest, _installed_name = _install_plugin_core(+ _catalog_install_identifier(entry),+ force=True,+ ref=entry.sha,+ )+ except PluginOperationError as e:+ console.print(f"[red]Error:[/red] {e}")+ sys.exit(1)++ _write_catalog_sidecar(new_target, entry)+ # Restore the pre-update enabled/disabled state verbatim (the reinstall+ # itself never touches it, but be explicit in case core ever does).+ _save_enabled_set(was_enabled)++ console.print(+ f"[green]✓[/green] Plugin [bold]{catalog_name}[/bold] updated to "+ f"{entry.sha[:8]}."+ )++def cmd_remove(name: str) -> None:"""Remove an installed plugin by name."""from rich.console import Console@@@ -1484,356 -2005,15 +2252,30 @@@ def cmd_list(args: Any | None = None) -status = "[green]enabled[/green]"else:status = "[yellow]not enabled[/yellow]"- catalog = _catalog_annotation(_dir)- source_label = f"{source} [cyan]{catalog}[/cyan]" if catalog else source- table.add_row(name, status, str(version), description, source_label)- table.add_row(name, status, str(version), description, source)++ source_label = source++ if _dir:++ sidecar = _read_catalog_sidecar(Path(_dir))++ if sidecar and sidecar.get("catalog_name"):++ tier = str(sidecar.get("tier") or "community")++ sha = str(sidecar.get("sha") or "")++ source_label = f"catalog:{tier}@{sha[:8]}"+ removed_reason = _removed_annotation(name, _dir)+ if removed_reason is not None:+ removed_lines.append(+ f"[red bold]✗ {name} — REMOVED from catalog: "+ f"{removed_reason}[/red bold]"+ )++ table.add_row(name, status, str(version), description, source_label)console.print()console.print(table)- for line in removed_lines:- console.print(line)- console.print()- console.print("[dim]Compact view:[/dim] hermes plugins list --plain --no-bundled")- console.print("[dim]Interactive toggle:[/dim] hermes plugins")- console.print("[dim]Enable/disable:[/dim] hermes plugins enable/disable <name>")- console.print("[dim]Plugins are opt-in by default — only 'enabled' plugins load.[/dim]")--- # ---------------------------------------------------------------------------- # Catalog commands — search / browse / info / validate / doctor- # ------------------------------------------------------------------------------ def _entry_capability_counts(entry) -> str:- """Compact capability summary like ``2 tools, 1 hook`` for table rows."""- caps = entry.capabilities- parts: list[str] = []- for count, singular in (- (len(caps.provides_tools), "tool"),- (len(caps.provides_hooks), "hook"),- (len(caps.provides_middleware), "middleware"),- ):- if count:- plural = "" if count == 1 or singular == "middleware" else "s"- parts.append(f"{count} {singular}{plural}")- if caps.requires_env:- parts.append(f"{len(caps.requires_env)} env")- return ", ".join(parts) or "—"--- def _render_catalog_entries(entries, console) -> None:- """Render catalog entries as the shared search/browse Rich table."""- from rich.table import Table-- table = Table(title="Hermes Plugin Catalog", show_lines=False)- table.add_column("Name", style="bold")- table.add_column("Tier")- table.add_column("Description")- table.add_column("Pinned", style="dim")- table.add_column("Capabilities", style="dim")-- for entry in entries:- tier = (- "[cyan]official[/cyan]"- if entry.tier == "official"- else "[magenta]community[/magenta]"- )- description = entry.description- if len(description) > 60:- description = description[:57] + "..."- table.add_row(- entry.name,- tier,- description,- entry.sha[:8],- _entry_capability_counts(entry),- )-- console.print()- console.print(table)- console.print()- console.print("[dim]Details:[/dim] hermes plugins info <name>")- console.print("[dim]Install:[/dim] hermes plugins install <name>")--- def cmd_search(query: str = "") -> None:- """Search the plugin catalog (live index when reachable)."""- from rich.console import Console-- from hermes_cli.plugin_catalog import filter_entries, load_catalog_live-- console = Console()- entries = filter_entries(load_catalog_live(), query)- if not entries:- if query:- console.print(- f"[dim]No catalog entries match '{query}'. "- "Browse everything with `hermes plugins browse`.[/dim]"- )- else:- console.print("[dim]No catalog entries available.[/dim]")- return- _render_catalog_entries(entries, console)--- def cmd_browse() -> None:- """List every plugin catalog entry."""- cmd_search("")--- def cmd_info(name: str) -> None:- """Show the full catalog entry for *name*."""- from rich.console import Console-- from hermes_cli.plugin_catalog import find_removed-- console = Console()- entry = _get_live_catalog_entry(name)- if entry is None:- console.print(- f"[red]Error:[/red] '{name}' is not in the plugin catalog. "- "Browse entries with `hermes plugins search`."- )- sys.exit(1)-- caps = entry.capabilities- console.print()- console.print(f"[bold]{entry.name}[/bold] [cyan]\\[{entry.tier}][/cyan]")- if entry.description:- console.print(entry.description)- console.print()- console.print(f"[dim]Repo:[/dim] {entry.repo}")- if entry.subdir:- console.print(f"[dim]Subdir:[/dim] {entry.subdir}")- console.print(f"[dim]Pinned SHA:[/dim] {entry.sha}")- console.print(f"[dim]Maintainer:[/dim] {entry.maintainer}")- if entry.requires_hermes:- console.print(f"[dim]Requires:[/dim] hermes {entry.requires_hermes}")- if entry.platforms:- console.print(f"[dim]Platforms:[/dim] {', '.join(entry.platforms)}")- if entry.docs_url:- console.print(f"[dim]Docs:[/dim] {entry.docs_url}")- console.print()- console.print(f"[dim]Tools:[/dim] {', '.join(caps.provides_tools) or '(none)'}")- console.print(f"[dim]Hooks:[/dim] {', '.join(caps.provides_hooks) or '(none)'}")- console.print(f"[dim]Middleware:[/dim] {', '.join(caps.provides_middleware) or '(none)'}")- console.print(f"[dim]Env vars:[/dim] {', '.join(caps.requires_env) or '(none)'}")- console.print()-- removed = find_removed(entry.name) or find_removed(entry.repo)- if removed is not None:- detail = removed.reason or "no reason recorded"- if removed.date:- detail += f" (removed {removed.date})"- console.print(- f"[red bold]✗ REMOVED from catalog: {detail}[/red bold]"- )- console.print()-- console.print(f"[dim]Install:[/dim] hermes plugins install {entry.name}")- console.print()--- def cmd_validate(path: str, as_json: bool = False) -> None:- """Validate a plugin directory for catalog admission. Exits 0/1."""- from rich.console import Console-- from hermes_cli.plugin_validate import validate_plugin_dir-- report = validate_plugin_dir(Path(path))-- if as_json:- print(json.dumps(report.to_dict(), indent=2))- sys.exit(report.exit_code)-- console = Console()- console.print()- for name, ok, detail in report.checks:- mark = "[green]✓[/green]" if ok else "[red]✗[/red]"- line = f"{mark} {name}"- if detail:- line += f" [dim]— {detail}[/dim]"- console.print(line)- for warning in report.warnings:- console.print(f"[yellow]⚠ {warning}[/yellow]")- console.print()- if report.ok:- console.print("[green bold]Validation passed.[/green bold]")- else:- console.print("[red bold]Validation failed.[/red bold]")- sys.exit(report.exit_code)--- def _runtime_load_errors() -> dict[str, str]:- """Return ``{plugin_key: error}`` from a fresh PluginManager scan.-- Uses the idempotent ``discover_plugins()`` path so we don't need a full- agent boot; failures are non-fatal (doctor still reports what it can).- """- try:- from hermes_cli.plugins import discover_plugins, get_plugin_manager-- discover_plugins()- manager = get_plugin_manager()- return {- key: loaded.error- for key, loaded in manager._plugins.items()- if loaded.error- }- except Exception as exc:- logger.debug("doctor: runtime plugin scan failed: %s", exc)- return {}--- def _doctor_plugin_report(name: str, dir_path: Path, key: str,- enabled: set, disabled: set,- load_errors: dict[str, str]) -> dict:- """Collect doctor facts for one installed plugin directory."""- from hermes_cli.plugins import _running_hermes_version, _version_satisfies-- manifest = _read_manifest(dir_path)- facts: dict[str, Any] = {- "name": name,- "manifest_ok": bool(manifest.get("name")),- "status": _plugin_status(name, enabled, disabled, key=key),- "load_error": load_errors.get(key) or load_errors.get(name) or "",- "missing_env": _missing_requires_env_names(manifest),- "requires_hermes": "",- "catalog": "",- "pin": "",- "removed": "",- }-- spec = str(manifest.get("requires_hermes") or "").strip()- if spec:- current = _running_hermes_version()- if _version_satisfies(spec, current):- facts["requires_hermes"] = f"{spec} ✓"- else:- facts["requires_hermes"] = f"{spec} ✗ (running {current})"-- sidecar = _read_catalog_sidecar(dir_path)- if sidecar and sidecar.get("catalog_name"):- tier = str(sidecar.get("tier") or "community")- sha = str(sidecar.get("sha") or "")- facts["catalog"] = f"catalog:{tier}@{sha[:8]}"- entry = _get_live_catalog_entry(str(sidecar["catalog_name"]))- if entry is None:- facts["pin"] = "entry gone from catalog"- elif entry.sha != sha:- facts["pin"] = (- f"behind catalog pin ({sha[:8]} → {entry.sha[:8]}) — "- "run `hermes plugins update`"- )- else:- facts["pin"] = "at catalog pin"-- removed_reason = _removed_annotation(name, dir_path)- if removed_reason is not None:- facts["removed"] = removed_reason- return facts--- def cmd_doctor(name: Optional[str] = None) -> None:- """Diagnose installed plugins (or a single one when *name* given)."""- from rich.console import Console- from rich.table import Table-- console = Console()- plugins_dir = _plugins_dir()- installed = [- (d.name, d) for d in sorted(plugins_dir.iterdir()) if d.is_dir()- ]- if name is not None:- installed = [(n, d) for n, d in installed if n == name]- if not installed:- console.print(- f"[red]Error:[/red] Plugin '{name}' not found in {plugins_dir}."- )- sys.exit(1)-- if not installed:- console.print("[dim]No plugins installed under[/dim] "- f"{plugins_dir}")- return-- enabled = _get_enabled_set()- disabled = _get_disabled_set()- load_errors = _runtime_load_errors()-- reports = [- _doctor_plugin_report(n, d, n, enabled, disabled, load_errors)- for n, d in installed- ]-- if name is not None:- facts = reports[0]- console.print()- console.print(f"[bold]{facts['name']}[/bold]")- console.print(- f"[dim]Manifest:[/dim] "- + ("[green]ok[/green]" if facts["manifest_ok"]- else "[red]missing/invalid plugin.yaml[/red]")- )- console.print(f"[dim]Status:[/dim] {facts['status']}")- if facts["load_error"]:- console.print(f"[dim]Load error:[/dim] [red]{facts['load_error']}[/red]")- if facts["missing_env"]:- console.print(- f"[dim]Missing env:[/dim] [yellow]{', '.join(facts['missing_env'])}[/yellow]"- )- if facts["requires_hermes"]:- console.print(f"[dim]Requires:[/dim] hermes {facts['requires_hermes']}")- if facts["catalog"]:- console.print(f"[dim]Provenance:[/dim] {facts['catalog']}")- console.print(f"[dim]Pin:[/dim] {facts['pin']}")- if facts["removed"]:- console.print(- f"[red bold]✗ REMOVED from catalog: {facts['removed']}[/red bold]"- )- console.print()- return-- table = Table(title="Plugin Doctor", show_lines=False)- table.add_column("Name", style="bold")- table.add_column("Manifest")- table.add_column("Status")- table.add_column("Issues")- table.add_column("Catalog", style="dim")-- for facts in reports:- issues: list[str] = []- if facts["load_error"]:- issues.append(f"[red]{facts['load_error']}[/red]")- if facts["missing_env"]:- issues.append(- f"[yellow]missing env: {', '.join(facts['missing_env'])}[/yellow]"- )- if facts["requires_hermes"] and "✗" in facts["requires_hermes"]:- issues.append(f"[red]requires hermes {facts['requires_hermes']}[/red]")- if facts["removed"]:- issues.append(- f"[red bold]REMOVED from catalog: {facts['removed']}[/red bold]"- )- if facts["pin"] and "behind" in facts["pin"]:- issues.append(f"[yellow]{facts['pin']}[/yellow]")- table.add_row(- facts["name"],- "[green]ok[/green]" if facts["manifest_ok"] else "[red]bad[/red]",- facts["status"],- "\n".join(issues) or "[dim]—[/dim]",- facts["catalog"] or "[dim]—[/dim]",- )-- console.print()- console.print(table)++ for line in removed_lines:++ console.print(line)console.print()+ console.print("[dim]Compact view:[/dim] hermes plugins list --plain --no-bundled")+ console.print("[dim]Interactive toggle:[/dim] hermes plugins")+ console.print("[dim]Enable/disable:[/dim] hermes plugins enable/disable <name>")+ console.print("[dim]Plugins are opt-in by default — only 'enabled' plugins load.[/dim]")# ---------------------------------------------------------------------------@@@ -2418,58 -2641,44 +2903,79 @@@ def dashboard_install_plugin*,force: bool,enable: bool,+ catalog_name: Optional[str] = None,) -> dict[str, Any]:- """Non-interactive install for the web dashboard. Returns a JSON-serializable dict."""+ """Non-interactive install for the web dashboard. Returns a JSON-serializable dict.++ When *catalog_name* is given the identifier is resolved from the plugin+ catalog and the pinned commit SHA is checked out (``ref=``). Removed+ (blocklisted) plugins are refused with the recorded reason — the+ dashboard deliberately has no bypass flag (CLI-only decision).+ """warnings: list[str] = []- try:- git_url, _subdir = _resolve_git_url(identifier)- if git_url.startswith(("http://", "file://")):- warnings.append(- "Insecure URL scheme; prefer https:// or git@ for production installs.",- )- except ValueError:- pass+ entry = None+ ref: Optional[str] = None++ if catalog_name:+ from hermes_cli.plugin_catalog import find_removed, get_catalog_entry++ removed = find_removed(catalog_name)+ if removed is not None:+ detail = removed.reason or "no reason recorded"+ if removed.date:+ detail += f" (removed {removed.date})"+ return {+ "ok": False,+ "error": (+ f"Plugin '{removed.name}' was removed from the Hermes "+ f"plugin catalog and is blocked from installation: {detail}"+ ),+ }+ entry = get_catalog_entry(catalog_name)+ if entry is None:+ return {+ "ok": False,+ "error": f"'{catalog_name}' is not in the Hermes plugin catalog.",+ }- identifier = f"{entry.repo}#{entry.subdir}" if entry.subdir else entry.repo++ identifier = _catalog_install_identifier(entry)+ ref = entry.sha+ else:+ try:+ git_url, _subdir = _resolve_git_url(identifier)+ if git_url.startswith(("http://", "file://")):+ warnings.append(+ "Insecure URL scheme; prefer https:// or git@ for production installs.",+ )+ except ValueError:+ passtry:target, installed_manifest, installed_name = _install_plugin_core(identifier,force=force,+ ref=ref,)+ except PluginScanBlocked as exc:+ findings = []+ if exc.scan_result is not None:+ findings = [+ {+ "pattern_id": f.pattern_id,+ "severity": f.severity,+ "category": f.category,+ "file": f.file,+ "line": f.line,+ "description": f.description,+ }+ for f in exc.scan_result.findings+ ]+ return {+ "ok": False,+ "error": str(exc),+ "scan_blocked": True,+ "scan_verdict": getattr(exc.scan_result, "verdict", "dangerous"),+ "scan_findings": findings,+ }except PluginOperationError as exc:return {"ok": False, "error": str(exc)}@@@ -2697,6 -3048,76 +3351,247 @@@ def dashboard_remove_user_plugin(name:return {"ok": True, "name": name}+ def cmd_plugin_doctor(target: str = ".", *, ci: bool = False) -> None:+ """Validate one plugin through runtime discovery and registration."""+ from rich.console import Console++ from hermes_cli.plugin_dev import doctor_plugin++ report = doctor_plugin(target)+ Console().print(report.format_text())+ if ci and not report.ok:+ raise SystemExit(1)++++def _entry_capability_counts(entry) -> str:++ """Compact capability summary like ``2 tools, 1 hook`` for table rows."""++ caps = entry.capabilities++ parts: list[str] = []++ for count, singular in (++ (len(caps.provides_tools), "tool"),++ (len(caps.provides_hooks), "hook"),++ (len(caps.provides_middleware), "middleware"),++ ):++ if count:++ plural = "" if count == 1 or singular == "middleware" else "s"++ parts.append(f"{count} {singular}{plural}")++ if caps.requires_env:++ parts.append(f"{len(caps.requires_env)} env")++ return ", ".join(parts) or "—"++++++def _render_catalog_entries(entries, console) -> None:++ """Render catalog entries as the shared search/browse Rich table."""++ from rich.table import Table++++ table = Table(title="Hermes Plugin Catalog (curated)", show_lines=False)++ table.add_column("Name", style="bold")++ table.add_column("Tier")++ table.add_column("Description")++ table.add_column("Pinned", style="dim")++ table.add_column("Capabilities", style="dim")++++ for entry in entries:++ tier = (++ "[cyan]official[/cyan]"++ if entry.tier == "official"++ else "[magenta]community[/magenta]"++ )++ description = entry.description++ if len(description) > 60:++ description = description[:57] + "..."++ table.add_row(++ entry.name,++ tier,++ description,++ entry.sha[:8],++ _entry_capability_counts(entry),++ )++++ console.print()++ console.print(table)++ console.print()++ console.print("[dim]Details:[/dim] hermes plugins info <name>")++ console.print("[dim]Install:[/dim] hermes plugins install <name>")++++++def cmd_browse() -> None:++ """List every curated plugin catalog entry."""++ from rich.console import Console++++ from hermes_cli.plugin_catalog import load_catalog_live++++ console = Console()++ entries = load_catalog_live()++ if not entries:++ console.print("[dim]No catalog entries available.[/dim]")++ return++ _render_catalog_entries(entries, console)++++++def cmd_info(name: str) -> None:++ """Show the full catalog entry for *name* (falls back to installed info)."""++ from rich.console import Console++++ from hermes_cli.plugin_catalog import find_removed++++ console = Console()++ entry = _get_live_catalog_entry(name)++ if entry is None:++ # Not a catalog entry — show installed-plugin details instead.++ cmd_show(name)++ return++++ caps = entry.capabilities++ console.print()++ console.print(f"[bold]{entry.name}[/bold] [cyan]\\[{entry.tier}][/cyan]")++ if entry.description:++ console.print(entry.description)++ console.print()++ console.print(f"[dim]Repo:[/dim] {entry.repo}")++ if entry.subdir:++ console.print(f"[dim]Subdir:[/dim] {entry.subdir}")++ console.print(f"[dim]Pinned SHA:[/dim] {entry.sha}")++ console.print(f"[dim]Maintainer:[/dim] {entry.maintainer}")++ if entry.requires_hermes:++ console.print(f"[dim]Requires:[/dim] hermes {entry.requires_hermes}")++ if entry.platforms:++ console.print(f"[dim]Platforms:[/dim] {', '.join(entry.platforms)}")++ if entry.docs_url:++ console.print(f"[dim]Docs:[/dim] {entry.docs_url}")++ console.print()++ console.print(f"[dim]Tools:[/dim] {', '.join(caps.provides_tools) or '(none)'}")++ console.print(f"[dim]Hooks:[/dim] {', '.join(caps.provides_hooks) or '(none)'}")++ console.print(f"[dim]Middleware:[/dim] {', '.join(caps.provides_middleware) or '(none)'}")++ console.print(f"[dim]Env vars:[/dim] {', '.join(caps.requires_env) or '(none)'}")++ console.print()++++ removed = find_removed(entry.name) or find_removed(entry.repo)++ if removed is not None:++ detail = removed.reason or "no reason recorded"++ if removed.date:++ detail += f" (removed {removed.date})"++ console.print(++ f"[red bold]✗ REMOVED from catalog: {detail}[/red bold]"++ )++ console.print()++++ console.print(f"[dim]Install:[/dim] hermes plugins install {entry.name}")++ console.print()++++++def cmd_validate(path: str, as_json: bool = False) -> None:++ """Validate a plugin directory for catalog admission. Exits 0/1."""++ from rich.console import Console++++ from hermes_cli.plugin_validate import validate_plugin_dir++++ report = validate_plugin_dir(Path(path))++++ if as_json:++ print(json.dumps(report.to_dict(), indent=2))++ sys.exit(report.exit_code)++++ console = Console()++ console.print()++ for check_name, ok, detail in report.checks:++ mark = "[green]✓[/green]" if ok else "[red]✗[/red]"++ line = f"{mark} {check_name}"++ if detail:++ line += f" [dim]— {detail}[/dim]"++ console.print(line)++ for warning in report.warnings:++ console.print(f"[yellow]⚠ {warning}[/yellow]")++ console.print()++ if report.ok:++ console.print("[green bold]Validation passed.[/green bold]")++ else:++ console.print("[red bold]Validation failed.[/red bold]")++ sys.exit(report.exit_code)+++++ def cmd_search(+ term: str = "",+ *,+ json_output: bool = False,+ capability: Optional[str] = None,+ refresh: bool = False,+ ) -> None:+ """Search the community plugin index (fuzzy on name/description/tags)."""+ from rich.console import Console++ from hermes_cli.plugin_index import (+ SECURITY_FOOTER,+ load_index,+ search_index,+ )++ console = Console()++++ # Curated catalog first — reviewed, SHA-pinned entries.++ catalog_matches = []++ try:++ from hermes_cli.plugin_catalog import filter_entries, load_catalog_live++++ catalog_matches = filter_entries(load_catalog_live(), term)++ except Exception as exc:++ logger.debug("catalog search unavailable: %s", exc)+++ entries, source = load_index(refresh=refresh)+ results = search_index(entries, term, capability=capability)++ if json_output:+ print(+ json.dumps(+ {+ "source": source,+ "query": term,++ "catalog_results": [++ {++ "name": e.name,++ "description": e.description,++ "repo": e.repo,++ "sha": e.sha,++ "tier": e.tier,++ }++ for e in catalog_matches++ ],+ "results": [e.to_dict() for e in results],+ "note": SECURITY_FOOTER,+ },+ indent=2,+ )+ )+ return+++ if catalog_matches:++ _render_catalog_entries(catalog_matches, console)+++ if not results:- console.print(- f"[yellow]No plugins matched '{term}'[/yellow] "- f"[dim](index source: {source})[/dim]"- )++ if not catalog_matches:++ console.print(++ f"[yellow]No plugins matched '{term}'[/yellow] "++ f"[dim](index source: {source})[/dim]"++ )+ return++ from rich.table import Table++ table = Table(title=f"Community plugins ({len(results)} match{'es' if len(results) != 1 else ''})")+ table.add_column("Name", style="bold")+ table.add_column("Description")+ table.add_column("Author")+ table.add_column("Tags", style="dim")+ for e in results:+ desc = e.description+ if len(desc) > 70:+ desc = desc[:67] + "..."+ table.add_row(e.name, desc, e.author, ", ".join(e.tags))+ console.print(table)+ console.print(f"[dim]Index source: {source}. Install: hermes plugins install <name>[/dim]")+ console.print(f"[dim]{SECURITY_FOOTER}[/dim]")++def plugins_command(args) -> None:"""Dispatch hermes plugins subcommands."""action = getattr(args, "plugins_action", None)@@@ -2712,18 -3133,15 +3607,20 @@@args.identifier,force=getattr(args, "force", False),enable=enable_arg,+ ref=getattr(args, "ref", None),+ allow_removed=getattr(args, "allow_removed", False),)- elif action == "search":- cmd_search(getattr(args, "query", "") or "")+ elif action == "browse":+ cmd_browse()- elif action == "info":- cmd_info(args.name)+ elif action == "validate":+ cmd_validate(args.path, as_json=getattr(args, "json", False))- elif action == "doctor":- cmd_doctor(getattr(args, "name", None))+ elif action == "search":+ cmd_search(+ getattr(args, "term", "") or "",+ json_output=getattr(args, "json", False),+ capability=getattr(args, "capability", None),+ refresh=getattr(args, "refresh", False),+ )elif action == "update":cmd_update(args.name)elif action in {"remove", "rm", "uninstall"}:@@@ -2739,8 -3157,18 +3636,20 @@@cmd_enable(args.name, allow_tool_override=allow_override)elif action == "disable":cmd_disable(args.name)+ elif action == "capabilities":+ cmd_capabilities(getattr(args, "name", None))elif action in {"list", "ls"}:cmd_list(args)+ elif action == "doctor":+ cmd_plugin_doctor(args.target, ci=getattr(args, "ci", False))+ elif action == "pack":+ from hermes_cli.plugin_packs import pack_command++ pack_command(args)- elif action in {"show", "info"}:++ elif action == "info":++ cmd_info(args.name)++ elif action == "show":+ cmd_show(args.name)elif action is None:cmd_toggle()else:diff --cc hermes_cli/subcommands/plugins.pyindex 636b22ed72b,975770c2fd5..ea241fe3a01--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@@ -31,6 -38,11 +38,16 @@@ def build_plugins_parser(subparsers, *action="store_true",help="Remove existing plugin and reinstall",)+ plugins_install.add_argument(+ "--ref",+ metavar="COMMIT_SHA",+ help="Install exactly one immutable 40-character Git commit SHA",+ )++ plugins_install.add_argument(++ "--allow-removed",++ action="store_true",++ help="DANGEROUS: bypass the catalog removed-plugin blocklist check",++ )_install_enable_group = plugins_install.add_mutually_exclusive_group()_install_enable_group.add_argument("--enable",@@@ -42,52 -54,33 +59,48 @@@action="store_true",help="Install disabled (skip confirmation prompt); enable later with `hermes plugins enable <name>`",)- plugins_install.add_argument(- "--allow-removed",- action="store_true",- help="DANGEROUS: bypass the catalog removed-plugin blocklist check",- )plugins_search = plugins_subparsers.add_parser(- "search", help="Search the Hermes plugin catalog"+ "search", help="Search the community plugin index")plugins_search.add_argument(- "query",+ "term",nargs="?",default="",- help="Substring to match against entry names, descriptions, and tools",+ help="Search term matched fuzzily against name, description, and tags "+ "(omit to browse the full index)",)-- plugins_subparsers.add_parser(- "browse", help="Browse every plugin catalog entry"+ plugins_search.add_argument(+ "--json",+ action="store_true",+ help="Print machine-readable JSON",+ )+ plugins_search.add_argument(+ "--capability",+ metavar="CAP",+ help="Filter by declared capability (e.g. tools, platform, commands)",+ )+ plugins_search.add_argument(+ "--refresh",+ action="store_true",+ help="Bypass the local cache and re-fetch the index",)- plugins_info = plugins_subparsers.add_parser(- "info", help="Show full catalog details for an entry"++ plugins_subparsers.add_parser(++ "browse", help="Browse every curated plugin catalog entry"+ )- plugins_info.add_argument("name", help="Catalog entry name")++ plugins_validate = plugins_subparsers.add_parser(+ "validate",+ help="Validate a plugin directory for catalog admission (CI gate)",+ )+ plugins_validate.add_argument("path", help="Path to the plugin directory")+ plugins_validate.add_argument(+ "--json",+ action="store_true",+ help="Print machine-readable JSON (for CI)",+ )+- plugins_doctor = plugins_subparsers.add_parser(- "doctor", help="Diagnose installed plugins"- )- plugins_doctor.add_argument(- "name",- nargs="?",- default=None,- help="Plugin name to inspect in detail (default: all installed)",- )-plugins_update = plugins_subparsers.add_parser("update", help="Pull latest changes for an installed plugin")diff --cc hermes_cli/web_server.pyindex e40ed6a473f,73b2014e8e9..869596de16c--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@@ -18856,22 -18695,75 +18702,89 @@@ def _strip_dashboard_manifest(p: Dict[sreturn {k: v for k, v in p.items() if not k.startswith("_")}+def _plugin_runtime_status(aliases: set, enabled_set: set, disabled_set: set) -> str:+ """Map a plugin's name aliases onto enabled/disabled/inactive.++ Both the path-derived key (nested category plugins) and the bare+ manifest name count for enabled/disabled state, matching the runtime+ loader's back-compat lookup.+ """+ if aliases & disabled_set:+ return "disabled"+ if aliases & enabled_set:+ return "enabled"+ return "inactive"++- def _merged_plugins_hub() -> Dict[str, Any]:- """Agent discovery + dashboard manifests + optional provider picker metadata."""+ _PLUGINS_HUB_CACHE_TTL_SECONDS = 5.0+ _plugins_hub_cache: Optional[Dict[str, Any]] = None+ _plugins_hub_cache_expires_at = 0.0+ _plugins_hub_cache_lock = threading.Lock()+++ def _invalidate_plugins_hub_cache() -> None:+ global _plugins_hub_cache, _plugins_hub_cache_expires_at+ with _plugins_hub_cache_lock:+ _plugins_hub_cache = None+ _plugins_hub_cache_expires_at = 0.0+++ _plugins_hub_probe_inflight: set = set()+ _plugins_hub_probe_lock = threading.Lock()+++ def _schedule_check_fn_probe(fn) -> Optional[threading.Thread]:+ """Warm a cold ``check_fn`` verdict off the request path.++ The hub read path only consumes cached availability (never probes+ inline). But the only other warmer lives in the tool-schema build, which+ a dashboard-only session never runs — so a cold cache would report+ ``auth_required=False`` forever. Kick a daemon-thread probe on the miss;+ the short hub TTL picks up the verdict on the next fetch. Deduplicates+ concurrent probes per function. Returns the spawned thread (or ``None``+ when a probe for *fn* is already in flight).+ """+ with _plugins_hub_probe_lock:+ if fn in _plugins_hub_probe_inflight:+ return None+ _plugins_hub_probe_inflight.add(fn)++ def _probe():+ try:+ from tools.registry import _check_fn_cached++ _check_fn_cached(fn)+ except Exception:+ pass+ finally:+ with _plugins_hub_probe_lock:+ _plugins_hub_probe_inflight.discard(fn)++ thread = threading.Thread(+ target=_probe, name="plugins-hub-checkfn-probe", daemon=True+ )+ thread.start()+ return thread+++ def _merged_plugins_hub(force_refresh: bool = False) -> Dict[str, Any]:+ """Agent discovery + dashboard manifests + optional provider picker metadata.++ IMPORTANT: this powers a dashboard request path, so it must stay read-only+ and cheap. In particular, do not execute tool ``check_fn`` probes here —+ those can trigger imports, auth/network checks, and other synchronous work+ that starves the root event loop. We only consume last-known cached tool+ availability, and we memoize the assembled payload briefly to collapse the+ dashboard's bursty duplicate fetches.+ """+ global _plugins_hub_cache, _plugins_hub_cache_expires_at+ now = time.monotonic()+ if not force_refresh:+ with _plugins_hub_cache_lock:+ if _plugins_hub_cache is not None and now < _plugins_hub_cache_expires_at:+ return _plugins_hub_cache++ started_at = time.monotonic()from hermes_cli.plugins_cmd import (_discover_all_plugins,_get_current_context_engine,diff --cc tests/hermes_cli/test_plugin_catalog.pyindex 18096bfb5e8,00000000000..83ce653edd6mode 100644,000000..100644--- a/tests/hermes_cli/test_plugin_catalog.py+++ b/tests/hermes_cli/test_plugin_catalog.py@@@ -1,594 -1,0 +1,538 @@@+"""Tests for the Hermes plugin catalog (hermes_cli.plugin_catalog) and the+catalog-driven install/manifest extensions in plugins_cmd.py / plugins.py."""++from __future__ import annotations++import os+import subprocess+from pathlib import Path++import pytest+import yaml++from hermes_cli.plugin_catalog import (+ CATALOG_TIERS,+ PluginCatalogEntry,+ RemovedEntry,+ entry_capability_summary,+ find_removed,+ get_catalog_dir,+ get_catalog_entry,+ load_catalog,+ load_removed_list,+ search_catalog,+)+++VALID_SHA = "38fe0fb53eff98d477f807432e965429e665ca33"+++# ── Helpers ────────────────────────────────────────────────────────────────+++def _write_entry(catalog_dir: Path, name: str, **overrides) -> Path:+ """Write a minimal valid catalog entry yaml, applying overrides."""+ data = {+ "name": name,+ "repo": f"https://github.com/example/{name}",+ "sha": VALID_SHA,+ "description": f"Test entry {name}.",+ "maintainer": "Example",+ }+ data.update(overrides)+ catalog_dir.mkdir(parents=True, exist_ok=True)+ path = catalog_dir / f"{name}.yaml"+ path.write_text(yaml.safe_dump(data), encoding="utf-8")+ return path+++def _write_removed(catalog_dir: Path, removed: list) -> Path:+ catalog_dir.mkdir(parents=True, exist_ok=True)+ path = catalog_dir / "removed.yaml"+ path.write_text(yaml.safe_dump({"removed": removed}), encoding="utf-8")+ return path+++def catalog_dir(tmp_path, monkeypatch):+ d = tmp_path / "catalog"+ d.mkdir()+ monkeypatch.setenv("HERMES_PLUGIN_CATALOG_DIR", str(d))+ return d+++# ── get_catalog_dir ────────────────────────────────────────────────────────+++class TestGetCatalogDir:+ def test_env_override_wins(self, catalog_dir):+ assert get_catalog_dir() == catalog_dir++ def test_default_is_repo_plugin_catalog(self, monkeypatch):+ monkeypatch.delenv("HERMES_PLUGIN_CATALOG_DIR", raising=False)+ d = get_catalog_dir()+ assert d.name == "plugin-catalog"+++# ── load_catalog ───────────────────────────────────────────────────────────+++class TestLoadCatalog:+ def test_valid_entry_parses(self, catalog_dir):+ _write_entry(+ catalog_dir,+ "my-plugin",+ tier="official",+ requires_hermes=">=0.19",+ subdir="plugins/my-plugin",+ docs_url="https://example.com/docs",+ platforms=["linux"],+ capabilities={+ "provides_tools": ["my_tool"],+ "provides_hooks": ["on_start"],+ "provides_middleware": ["llm_request"],+ "requires_env": ["MY_API_KEY"],+ },+ )+ entries = load_catalog()+ assert len(entries) == 1+ e = entries[0]+ assert isinstance(e, PluginCatalogEntry)+ assert e.name == "my-plugin"+ assert e.repo == "https://github.com/example/my-plugin"+ assert e.sha == VALID_SHA+ assert e.tier == "official"+ assert e.requires_hermes == ">=0.19"+ assert e.subdir == "plugins/my-plugin"+ assert e.docs_url == "https://example.com/docs"+ assert e.platforms == ["linux"]+ assert e.capabilities.provides_tools == ["my_tool"]+ assert e.capabilities.provides_hooks == ["on_start"]+ assert e.capabilities.provides_middleware == ["llm_request"]+ assert e.capabilities.requires_env == ["MY_API_KEY"]++ def test_tier_defaults_to_community(self, catalog_dir):+ _write_entry(catalog_dir, "no-tier")+ (entry,) = load_catalog()+ assert entry.tier == "community"+ assert entry.tier in CATALOG_TIERS++ def test_bad_sha_rejected(self, catalog_dir, caplog):+ _write_entry(catalog_dir, "bad-sha", sha="main")+ _write_entry(catalog_dir, "short-sha", sha="38fe0fb")+ _write_entry(catalog_dir, "good", sha=VALID_SHA)+ with caplog.at_level("WARNING"):+ entries = load_catalog()+ assert [e.name for e in entries] == ["good"]++ def test_bad_name_rejected(self, catalog_dir, caplog):+ _write_entry(catalog_dir, "BadName")+ _write_entry(catalog_dir, "has spaces")+ with caplog.at_level("WARNING"):+ entries = load_catalog()+ assert entries == []++ def test_non_https_repo_rejected(self, catalog_dir, caplog):+ _write_entry(catalog_dir, "sshrepo", repo="[email protected]:x/y.git")+ with caplog.at_level("WARNING"):+ entries = load_catalog()+ assert entries == []++ def test_invalid_tier_rejected(self, catalog_dir, caplog):+ _write_entry(catalog_dir, "weird-tier", tier="platinum")+ with caplog.at_level("WARNING"):+ entries = load_catalog()+ assert entries == []++ def test_removed_yaml_is_not_an_entry(self, catalog_dir):+ _write_entry(catalog_dir, "real-entry")+ _write_removed(catalog_dir, [])+ entries = load_catalog()+ assert [e.name for e in entries] == ["real-entry"]++ def test_unparseable_yaml_skipped_without_raising(self, catalog_dir, caplog):+ (catalog_dir / "broken.yaml").write_text(+ "name: [unclosed", encoding="utf-8"+ )+ _write_entry(catalog_dir, "ok-entry")+ with caplog.at_level("WARNING"):+ entries = load_catalog()+ assert [e.name for e in entries] == ["ok-entry"]++ def test_missing_dir_returns_empty(self, tmp_path, monkeypatch):+ monkeypatch.setenv(+ "HERMES_PLUGIN_CATALOG_DIR", str(tmp_path / "does-not-exist")+ )+ assert load_catalog() == []+++# ── get_catalog_entry / search_catalog ─────────────────────────────────────+++class TestLookupAndSearch:+ def test_get_catalog_entry_by_name(self, catalog_dir):+ _write_entry(catalog_dir, "alpha")+ _write_entry(catalog_dir, "beta")+ entry = get_catalog_entry("beta")+ assert entry is not None and entry.name == "beta"+ assert get_catalog_entry("nope") is None++ def test_search_matches_name_case_insensitive(self, catalog_dir):+ _write_entry(catalog_dir, "weather-tools")+ _write_entry(catalog_dir, "other")+ results = search_catalog("WEATHER")+ assert [e.name for e in results] == ["weather-tools"]++ def test_search_matches_description(self, catalog_dir):+ _write_entry(catalog_dir, "abc", description="Fetches Stock Quotes.")+ results = search_catalog("stock")+ assert [e.name for e in results] == ["abc"]++ def test_search_matches_declared_tools(self, catalog_dir):+ _write_entry(+ catalog_dir,+ "toolful",+ capabilities={"provides_tools": ["get_forecast"]},+ )+ _write_entry(catalog_dir, "toolless")+ results = search_catalog("Forecast")+ assert [e.name for e in results] == ["toolful"]++ def test_empty_query_returns_all(self, catalog_dir):+ _write_entry(catalog_dir, "one")+ _write_entry(catalog_dir, "two")+ assert len(search_catalog("")) == 2+++# ── removed list ───────────────────────────────────────────────────────────+++class TestRemovedList:+ def test_load_removed_list(self, catalog_dir):+ _write_removed(+ catalog_dir,+ [+ {+ "name": "evil-plugin",+ "repo": "https://github.com/evil/evil-plugin",+ "reason": "Exfiltrated env vars",+ "date": "2026-07-02",+ }+ ],+ )+ removed = load_removed_list()+ assert len(removed) == 1+ r = removed[0]+ assert isinstance(r, RemovedEntry)+ assert r.name == "evil-plugin"+ assert r.reason == "Exfiltrated env vars"+ assert r.date == "2026-07-02"++ def test_missing_removed_yaml_returns_empty(self, catalog_dir):+ assert load_removed_list() == []+ assert find_removed("anything") is None++ def test_find_removed_by_name(self, catalog_dir):+ _write_removed(catalog_dir, [{"name": "evil-plugin", "reason": "bad"}])+ hit = find_removed("evil-plugin")+ assert hit is not None and hit.reason == "bad"++ def test_find_removed_by_repo_url_with_and_without_git_suffix(+ self, catalog_dir+ ):+ _write_removed(+ catalog_dir,+ [+ {+ "name": "evil-plugin",+ "repo": "https://github.com/evil/evil-plugin",+ "reason": "bad",+ }+ ],+ )+ assert find_removed("https://github.com/evil/evil-plugin") is not None+ assert find_removed("https://github.com/evil/evil-plugin.git") is not None+ assert find_removed("https://github.com/good/fine.git") is None+++# ── entry_capability_summary ───────────────────────────────────────────────+++class TestCapabilitySummary:+ def test_summary_contains_declared_capabilities(self):+ entry = PluginCatalogEntry(+ name="cap-plugin",+ repo="https://github.com/example/cap-plugin",+ sha=VALID_SHA,+ description="Does capable things.",+ maintainer="Example",+ )+ entry.capabilities.provides_tools = ["tool_a", "tool_b"]+ entry.capabilities.provides_hooks = ["session_start"]+ entry.capabilities.requires_env = ["CAP_API_KEY"]+ summary = entry_capability_summary(entry)+ assert "tool_a" in summary+ assert "tool_b" in summary+ assert "session_start" in summary+ assert "CAP_API_KEY" in summary++ def test_summary_for_empty_capabilities_mentions_none(self):+ entry = PluginCatalogEntry(+ name="plain",+ repo="https://github.com/example/plain",+ sha=VALID_SHA,+ description="Plain.",+ maintainer="Example",+ )+ summary = entry_capability_summary(entry)+ assert summary # non-empty human text+++# ── shipped catalog seed ───────────────────────────────────────────────────+++class TestShippedCatalog:+ def test_shipped_catalog_entries_are_valid(self, monkeypatch):+ """Every yaml shipped in <repo>/plugin-catalog must load cleanly."""+ monkeypatch.delenv("HERMES_PLUGIN_CATALOG_DIR", raising=False)+ shipped = get_catalog_dir()+ yaml_files = [+ p for p in shipped.glob("*.yaml") if p.name != "removed.yaml"+ ]+ entries = load_catalog()+ assert len(entries) == len(yaml_files)+ # removed.yaml must exist and parse+ assert (shipped / "removed.yaml").exists()+ load_removed_list()+++# ── _version_satisfies ─────────────────────────────────────────────────────+++class TestVersionSatisfies:+ @pytest.fixture(autouse=True)+ def _import(self):+ from hermes_cli.plugins import _version_satisfies++ self.satisfies = _version_satisfies++ def test_ge(self):+ assert self.satisfies(">=0.19", "0.19.0") is True+ assert self.satisfies(">=0.19", "0.20.1") is True+ assert self.satisfies(">=0.19", "0.18.2") is False++ def test_gt_lt_le(self):+ assert self.satisfies(">0.19", "0.19.1") is True+ assert self.satisfies(">0.19", "0.19.0") is False+ assert self.satisfies("<1.0", "0.19.0") is True+ assert self.satisfies("<=0.19.0", "0.19.0") is True++ def test_eq_ne(self):+ assert self.satisfies("==0.19.0", "0.19.0") is True+ assert self.satisfies("==0.19.0", "0.19.1") is False+ assert self.satisfies("!=0.19.0", "0.19.1") is True+ assert self.satisfies("!=0.19.0", "0.19.0") is False++ def test_comma_separated_all_must_hold(self):+ assert self.satisfies(">=0.10, <1.0", "0.19.0") is True+ assert self.satisfies(">=0.10, <0.15", "0.19.0") is False++ def test_bare_version_treated_as_ge(self):+ assert self.satisfies("0.10", "0.19.0") is True+ assert self.satisfies("999", "0.19.0") is False++ def test_empty_spec_is_satisfied(self):+ assert self.satisfies("", "0.19.0") is True++ def test_non_numeric_segments_fall_back_permissive(self):+ assert self.satisfies(">=abc.def", "0.19.0") is True+ assert self.satisfies(">=0.19", "unknown") is True+++# ── requires_hermes manifest gate ──────────────────────────────────────────+++def _make_plugin(base: Path, name: str, *, manifest_extra: dict | None = None,+ register_body: str = "pass", enable: bool = True) -> Path:+ """Create a plugin dir under <HERMES_HOME>/plugins and opt it in."""+ plugin_dir = base / name+ plugin_dir.mkdir(parents=True, exist_ok=True)+ manifest = {"name": name, "version": "0.1.0", "description": name}+ if manifest_extra:+ manifest.update(manifest_extra)+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump(manifest))+ (plugin_dir / "__init__.py").write_text(+ f"def register(ctx):\n {register_body}\n"+ )+ if enable:+ hermes_home = Path(os.environ["HERMES_HOME"])+ cfg_path = hermes_home / "config.yaml"+ cfg: dict = {}+ if cfg_path.exists():+ cfg = yaml.safe_load(cfg_path.read_text()) or {}+ cfg.setdefault("plugins", {}).setdefault("enabled", []).append(name)+ cfg_path.write_text(yaml.safe_dump(cfg))+ return plugin_dir+++class TestRequiresHermesGate:+ def test_unsatisfied_requires_hermes_skips_load(self, monkeypatch):+ from hermes_cli.plugins import PluginManager++ hermes_home = Path(os.environ["HERMES_HOME"])+ plugins_dir = hermes_home / "plugins"+ _make_plugin(+ plugins_dir, "future_plugin",+ manifest_extra={"requires_hermes": ">=999.0"},+ )+ mgr = PluginManager()+ mgr.discover_and_load()+ loaded = mgr._plugins["future_plugin"]+ assert loaded.enabled is False+ assert loaded.error is not None+ assert "requires hermes" in loaded.error+ assert ">=999.0" in loaded.error+ assert loaded.module is None # register() never ran++ def test_satisfied_requires_hermes_loads_normally(self, monkeypatch):+ from hermes_cli.plugins import PluginManager++ hermes_home = Path(os.environ["HERMES_HOME"])+ plugins_dir = hermes_home / "plugins"+ _make_plugin(+ plugins_dir, "old_ok_plugin",+ manifest_extra={"requires_hermes": ">=0.1"},+ )+ mgr = PluginManager()+ mgr.discover_and_load()+ loaded = mgr._plugins["old_ok_plugin"]+ assert loaded.enabled is True+ assert loaded.error is None++ def test_requires_hermes_parsed_onto_manifest(self):+ from hermes_cli.plugins import PluginManager++ hermes_home = Path(os.environ["HERMES_HOME"])+ plugins_dir = hermes_home / "plugins"+ _make_plugin(+ plugins_dir, "spec_plugin",+ manifest_extra={"requires_hermes": ">=0.19"},+ enable=False,+ )+ mgr = PluginManager()+ mgr.discover_and_load()+ assert mgr._plugins["spec_plugin"].manifest.requires_hermes == ">=0.19"++- # ── config: spec parsing + ctx.plugin_config ───────────────────────────────--- class TestPluginConfig:- def test_config_spec_parsed_onto_manifest(self):- from hermes_cli.plugins import PluginManager-- hermes_home = Path(os.environ["HERMES_HOME"])- plugins_dir = hermes_home / "plugins"- spec = [- {"key": "api_url", "prompt": "API URL", "type": "str",- "default": "https://api.example.com", "secret": False},- {"key": "token", "prompt": "Token", "type": "str", "secret": True},- ]- _make_plugin(- plugins_dir, "cfg_plugin",- manifest_extra={"config": spec},- enable=False,- )- mgr = PluginManager()- mgr.discover_and_load()- manifest = mgr._plugins["cfg_plugin"].manifest- assert isinstance(manifest.config_spec, list)- assert manifest.config_spec[0]["key"] == "api_url"- assert manifest.config_spec[1]["secret"] is True-- def test_plugin_config_merges_defaults_under_config_entries(self):- from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager-- hermes_home = Path(os.environ["HERMES_HOME"])- cfg_path = hermes_home / "config.yaml"- cfg_path.write_text(yaml.safe_dump({- "plugins": {"entries": {"merge_plugin": {"api_url": "https://override"}}}- }))-- manifest = PluginManifest(- name="merge_plugin",- key="merge_plugin",- config_spec=[- {"key": "api_url", "default": "https://default"},- {"key": "retries", "type": "int", "default": 3},- ],- )- ctx = PluginContext(manifest, PluginManager())- cfg = ctx.plugin_config- assert cfg["api_url"] == "https://override" # config.yaml wins- assert cfg["retries"] == 3 # default fills the gap-- def test_plugin_config_empty_without_spec_or_entries(self):- from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager-- manifest = PluginManifest(name="bare_plugin", key="bare_plugin")- ctx = PluginContext(manifest, PluginManager())- assert ctx.plugin_config == {}--+# ── _install_plugin_core: ref checkout + removed blocklist ────────────────+++def _make_git_repo(tmp_path: Path) -> tuple[Path, str, str]:+ """Create a local git repo with two commits; return (path, sha1, sha2)."""+ repo = tmp_path / "src-repo"+ repo.mkdir()++ def git(*args):+ subprocess.run(+ ["git", *args], cwd=repo, check=True, capture_output=True, text=True,+ env={**os.environ,+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"},+ )++ git("init", "-b", "main")+ (repo / "plugin.yaml").write_text(+ yaml.safe_dump({"name": "refplugin", "version": "1"})+ )+ (repo / "__init__.py").write_text("def register(ctx):\n pass\n")+ (repo / "marker.txt").write_text("first\n")+ git("add", "-A")+ git("commit", "-m", "first")+ sha1 = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True,+ capture_output=True, text=True,+ ).stdout.strip()+ (repo / "marker.txt").write_text("second\n")+ git("add", "-A")+ git("commit", "-m", "second")+ sha2 = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True,+ capture_output=True, text=True,+ ).stdout.strip()+ return repo, sha1, sha2+++class TestInstallPluginCore:+ def test_ref_checkout_installs_pinned_commit(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import _install_plugin_core++ repo, sha1, _sha2 = _make_git_repo(tmp_path)+ target, manifest, name = _install_plugin_core(+ f"file://{repo}", force=False, ref=sha1+ )+ assert name == "refplugin"+ assert (target / "marker.txt").read_text() == "first\n"++ def test_default_install_gets_head(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import _install_plugin_core++ repo, _sha1, _sha2 = _make_git_repo(tmp_path)+ target, _manifest, _name = _install_plugin_core(+ f"file://{repo}", force=False+ )+ assert (target / "marker.txt").read_text() == "second\n"++ def test_bad_ref_raises(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import PluginOperationError, _install_plugin_core++ repo, _sha1, _sha2 = _make_git_repo(tmp_path)+ with pytest.raises(PluginOperationError):+ _install_plugin_core(+ f"file://{repo}", force=False,+ ref="0000000000000000000000000000000000000000",+ )++ def test_removed_repo_blocked(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import PluginOperationError, _install_plugin_core++ repo, _sha1, _sha2 = _make_git_repo(tmp_path)+ _write_removed(+ catalog_dir,+ [{+ "name": "refplugin",+ "repo": f"file://{repo}",+ "reason": "exfiltrated env vars",+ "date": "2026-07-02",+ }],+ )+ with pytest.raises(PluginOperationError, match="exfiltrated env vars"):+ _install_plugin_core(f"file://{repo}", force=False)++ def test_removed_identifier_blocked_by_name(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import PluginOperationError, _install_plugin_core++ _write_removed(+ catalog_dir,+ [{"name": "evil-plugin", "reason": "malware", "date": "2026-01-01"}],+ )+ with pytest.raises(PluginOperationError, match="malware"):+ _install_plugin_core("evil-plugin", force=False)++ def test_skip_removed_check_bypasses_block(self, tmp_path, catalog_dir):+ from hermes_cli.plugins_cmd import _install_plugin_core++ repo, _sha1, _sha2 = _make_git_repo(tmp_path)+ _write_removed(+ catalog_dir,+ [{+ "name": "refplugin",+ "repo": f"file://{repo}",+ "reason": "bad",+ "date": "2026-07-02",+ }],+ )+ target, _manifest, name = _install_plugin_core(+ f"file://{repo}", force=False, skip_removed_check=True+ )+ assert name == "refplugin"+ assert target.exists()diff --cc web/src/pages/PluginsPage.tsxindex 92be0668304,bde492f20c4..652f3d16812--- a/web/src/pages/PluginsPage.tsx+++ b/web/src/pages/PluginsPage.tsx@@@ -1,12 -1,9 +1,12 @@@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { ExternalLink, RefreshCw, Trash2, Eye, EyeOff } from "lucide-react";import type { Translations } from "@/i18n/types";- import { Link } from "react-router-dom";+ import { Link } from "react-router";import { api } from "@/lib/api";import type {+ CatalogEntry,+ CatalogRemovedEntry,+ CatalogResponse,HubAgentPluginRow,MemoryProviderConfig,MemoryProviderField,