Skip to content

The agent that grows with you

fix(plugins): catalog provenance is installer-owned; kill list covers update/enable/load; re-pin keeps user files

teknium177f80d31eeb9
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index 0000471ed4b..645efa76775 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -230,8 +230,26 @@ def search_catalog(query: str) -> List[PluginCatalogEntry]:
# ── Removed / blocklist ──────────────────────────────────────────────────────
+_SCP_URL_RE = re.compile(r"^(?:[^@/\s]+@)?([^:/\s]+):(?!//)(.+)$") # git@host:owner/repo
+
+
def _normalize_repo(url: str) -> str:
- return url.strip().rstrip("/").removesuffix(".git").lower()
+ """Canonical ``host/path`` for a repo URL: scheme, user, ``www.``, ``.git`` and trailing slashes are
+ spelling, not identity — the kill list must match ``[email protected]:Evil/Bad.git`` when it names
+ ``https://github.com/evil/bad``."""
+ from urllib.parse import urlsplit
+ text = url.strip()
+ scp = _SCP_URL_RE.match(text)
+ if scp:
+ host, path = scp.group(1), scp.group(2)
+ elif "://" in text:
+ parts = urlsplit(text)
+ host, path = parts.hostname or "", parts.path
+ else:
+ host, path = "", text
+ host = host.lower().removeprefix("www.")
+ path = path.strip("/").removesuffix(".git").rstrip("/").lower()
+ return f"{host}/{path}" if host else path
def find_removed(name_or_repo: str, catalog_dir: Optional[Path] = None) -> Optional[RemovedEntry]:
@@ -255,6 +273,13 @@ def resolved_removed_entries() -> List[RemovedEntry]:
return load_removed_list() + live_removed_list()
+def cached_removed_entries() -> List[RemovedEntry]:
+ """In-tree list UNION the last fetched live copy, with NO network round-trip — for the load-time and
+ ``enable`` checks that run in every process and must never block on a dead catalog host."""
+ cached = _stale_live_cache(_live_cache_path()) or {}
+ return load_removed_list() + _removed_from_list(cached.get("removed"))
+
+
def match_removed(
candidate: str, entries: List[RemovedEntry]
) -> Optional[RemovedEntry]:
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index e97052674fc..b7c65fe521d 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -727,12 +727,17 @@ def _install_plugin_core(
scan_decision_cb=None,
reviewed_pin: Optional[str] = None,
python_deps: bool = True,
+ catalog: Optional[dict] = None,
+ allow_removed: bool = False,
) -> tuple[Path, dict, str]:
"""Clone a Git plugin and atomically record its source and exact revision.
*reviewed_pin* is the curated-catalog sha for this install; the scan trusts the tree
only when the checked-out revision is exactly that sha. *python_deps* False skips the
- dependency conflict gate (``--no-deps``: the user installs them by hand)."""
+ dependency conflict gate (``--no-deps``: the user installs them by hand). *catalog*
+ (``{"name", "repo", "tier", "pin"}``) is recorded on the install-metadata record with the
+ checked-out sha — provenance lives OUTSIDE the plugin tree, so a repo cannot forge it.
+ *allow_removed* records that the user knowingly bypassed the kill list."""
requested_revision = _normalize_exact_revision(ref) if ref is not None else None
try:
git_url, subdir = _resolve_git_url(identifier)
@@ -779,10 +784,13 @@ def _install_plugin_core(
f"Plugin '{plugin_name}' is pinned. Reinstall it with an explicit "
"--ref <40-character commit SHA> to change its source or revision.")
- new_metadata = {
- **old_metadata,
- plugin_name: {"pinned": requested_revision is not None, "revision": installed_revision, "source": source},
- }
+ record: dict[str, object] = {
+ "pinned": requested_revision is not None, "revision": installed_revision, "source": source}
+ if catalog:
+ record["catalog"] = {**catalog, "sha": installed_revision}
+ if allow_removed:
+ record["allow_removed"] = True
+ new_metadata = {**old_metadata, plugin_name: record}
_swap_in_plugin(tmp_target, target, Path(tmp) / "previous-plugin", old_metadata, new_metadata)
if not _looks_like_plugin_dir(target):
@@ -846,12 +854,12 @@ def cmd_install(
try:
if entry is not None:
target, installed_manifest, installed_name = catalog.install_catalog_entry(
- entry, force=force, ref=ref, allow_removed=True, scan_decision_cb=_interactive_scan_decision,
+ entry, force=force, ref=ref, allow_removed=allow_removed, scan_decision_cb=_interactive_scan_decision,
python_deps=not no_deps)
else:
target, installed_manifest, installed_name = _install_plugin_core(
identifier, force=force, ref=ref, scan_decision_cb=_interactive_scan_decision,
- python_deps=not no_deps)
+ python_deps=not no_deps, allow_removed=allow_removed)
except PluginOperationError as e:
_fail(console, f"[red]{'Blocked' if isinstance(e, PluginScanBlocked) else 'Error'}:[/red] {e}")
if not _looks_like_plugin_dir(target):
@@ -891,6 +899,9 @@ def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None)
raise PluginOperationError(pinned_msg(install_record))
if not (target / ".git").exists():
raise PluginOperationError(not_git_msg())
+ # A URL install whose name/repo later landed on the kill list must not keep pulling new code.
+ from hermes_cli import plugins_cmd_catalog as catalog
+ catalog.refuse_if_installed_removed(target.name, target)
if before_pull is not None:
before_pull()
ok, output = _git_pull_plugin_dir(target)
@@ -1127,6 +1138,13 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:
_fail(console, _unknown_plugin_message(name))
key, source = resolved
_refuse_legacy_relay(key)
+ if source != "bundled":
+ # Activating recalled code is the same act as installing it (`plugins/AGENTS.md`: kill list).
+ from hermes_cli import plugins_cmd_catalog as catalog
+ try:
+ catalog.refuse_if_installed_removed(key, _user_installed_plugin_dir(key.rsplit("/", 1)[-1]))
+ except PluginOperationError as exc:
+ _fail(console, f"[red]Error:[/red] {exc}")
enabled = _get_enabled_set()
disabled = _get_disabled_set()
@@ -1857,7 +1875,7 @@ def dashboard_install_plugin(
try:
if entry is not None:
target, installed_manifest, installed_name = catalog.install_catalog_entry(
- entry, force=force, allow_removed=True)
+ entry, force=force, allow_removed=False)
else:
target, installed_manifest, installed_name = _install_plugin_core(
identifier, force=force, ref=(ref or "").strip() or None)
@@ -1980,10 +1998,11 @@ def dashboard_update_user_plugin(name: str) -> dict[str, Any]:
sidecar = catalog.read_catalog_sidecar(target)
try:
if sidecar:
- sha, changed = catalog.repin_catalog_plugin(target, sidecar)
- warnings: list[str] = []
- deps = _install_python_dependencies_quietly(target, warnings) if changed else []
- return {"ok": True, "name": name, "sha": sha, "unchanged": not changed,
+ result = catalog.repin_catalog_plugin(target, sidecar)
+ warnings = list(result.warnings)
+ new_target = target.parent / result.installed_name
+ deps = _install_python_dependencies_quietly(new_target, warnings) if result.changed else []
+ return {"ok": True, "name": result.installed_name, "sha": result.sha, "unchanged": not result.changed,
"python_dependencies": deps, "warnings": warnings}
msg = _pull_plugin_update(
target,
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 44324150d25..7c2f088bd01 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -10,14 +10,16 @@ from __future__ import annotations
import datetime
import json
import logging
+import shutil
import sys
+import tempfile
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, NamedTuple, Optional
from hermes_cli.plugin_catalog import (
- PluginCatalogEntry, RemovedEntry, entry_capability_summary, filter_entries, find_removed,
- get_live_catalog_entry, load_catalog_live, load_removed_list, match_removed, resolved_removed_entries,
- _NAME_RE,
+ PluginCatalogEntry, RemovedEntry, cached_removed_entries, entry_capability_summary, filter_entries,
+ find_removed, get_live_catalog_entry, load_catalog_live, match_removed, resolved_removed_entries,
+ _NAME_RE, _normalize_repo,
)
logger = logging.getLogger(__name__)
@@ -60,11 +62,12 @@ def resolve_catalog_name(identifier: str, console) -> PluginCatalogEntry:
return entry
-def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry) -> None:
- """``.hermes-catalog.json`` inside the install dir — how ``update``/``list``/dashboards know the plugin
- came from the catalog and at which pin."""
+def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry, sha: Optional[str] = None) -> None:
+ """Human/Desktop-readable ``.hermes-catalog.json`` inside the install dir. It is a CONVENIENCE COPY:
+ the authoritative provenance is the ``catalog`` block on the ``.install-metadata.json`` record (see
+ :func:`read_catalog_sidecar`), because anything inside the tree is under the repo's control."""
sidecar = {
- "catalog_name": entry.name, "repo": entry.repo, "sha": entry.sha, "tier": entry.tier,
+ "catalog_name": entry.name, "repo": entry.repo, "sha": sha or entry.sha, "tier": entry.tier,
"installed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
.replace("+00:00", "Z"),
}
@@ -74,16 +77,62 @@ def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry) -> None:
logger.warning("Failed to write catalog sidecar in %s: %s", target, exc)
-def read_catalog_sidecar(plugin_dir) -> Optional[dict]:
- """Parsed sidecar, or ``None`` (absent/corrupt = a non-catalog install)."""
- path = Path(plugin_dir) / CATALOG_SIDECAR if plugin_dir else None
- if path is None or not path.is_file():
+def _install_record(plugin_dir: Path) -> Optional[dict]:
+ """The installer-owned ``.install-metadata.json`` record for a dir under the plugins dir, else ``None``."""
+ from hermes_cli.plugins_cmd import PluginOperationError, _plugins_dir, _read_install_metadata
+ if plugin_dir.parent != _plugins_dir():
+ return None
+ try:
+ record = _read_install_metadata().get(plugin_dir.name)
+ except PluginOperationError:
return None
+ return record if isinstance(record, dict) else None
+
+
+def _adopt_legacy_sidecar(plugin_dir: Path, record: dict) -> Optional[dict]:
+ """Installs made before provenance moved out of the tree carry only the in-tree file. Trust it once —
+ only when the installer record agrees (pinned at that sha, cloned from that catalog entry's repo) —
+ and copy it onto the record so later reads never consult the tree again."""
+ from hermes_cli.plugins_cmd import _read_install_metadata, _write_install_metadata
+ path = plugin_dir / CATALOG_SIDECAR
try:
- data = json.loads(path.read_text(encoding="utf-8"))
+ data = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None
except Exception:
return None
- return data if isinstance(data, dict) and data.get("catalog_name") else None
+ if not isinstance(data, dict) or not data.get("catalog_name"):
+ return None
+ sha = str(data.get("sha") or "").lower()
+ entry = get_live_catalog_entry(str(data["catalog_name"]))
+ if entry is None or record.get("pinned") is not True or record.get("revision") != sha:
+ return None
+ source = str(record.get("source") or "").split("#", 1)[0]
+ if _normalize_repo(source) != _normalize_repo(entry.repo):
+ return None
+ block = {"name": entry.name, "repo": entry.repo, "tier": str(data.get("tier") or entry.tier), "pin": sha, "sha": sha}
+ metadata = _read_install_metadata()
+ metadata[plugin_dir.name] = {**record, "catalog": block}
+ _write_install_metadata(metadata)
+ return block
+
+
+def read_catalog_sidecar(plugin_dir) -> Optional[dict]:
+ """Catalog provenance of an installed plugin (``catalog_name``/``repo``/``sha``/``tier``), or ``None``
+ for a non-catalog install. Read from the installer-owned metadata record, never from the tree: a
+ URL-installed repo that ships its own ``.hermes-catalog.json`` must not render as a reviewed
+ catalog install nor mark the real entry installed."""
+ if not plugin_dir:
+ return None
+ plugin_dir = Path(plugin_dir)
+ record = _install_record(plugin_dir)
+ if record is None:
+ return None
+ block = record.get("catalog")
+ if not isinstance(block, dict):
+ block = _adopt_legacy_sidecar(plugin_dir, record)
+ if not block or not block.get("name"):
+ return None
+ return {"catalog_name": block["name"], "repo": block.get("repo", ""), "sha": block.get("sha", ""),
+ "tier": block.get("tier") or "community", "pin": block.get("pin", "")}
def catalog_annotation(dir_path) -> Optional[str]:
@@ -113,22 +162,101 @@ def removed_annotation(name: str, dir_path, removed_entries: List[RemovedEntry])
def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optional[str] = None,
allow_removed: bool = False, scan_decision_cb=None, python_deps: bool = True) -> tuple:
- """``_install_plugin_core`` at the catalog pin (an explicit *ref* wins) + provenance sidecar.
- Returns the core's ``(target, manifest, installed_name)``."""
- from hermes_cli.plugins_cmd import _install_plugin_core
+ """``_install_plugin_core`` at the catalog pin (an explicit *ref* wins) + provenance recorded on the
+ install-metadata record at the sha ACTUALLY checked out (a ``--ref`` install is not at the reviewed
+ pin, so ``update_available`` must say so). Returns the core's ``(target, manifest, installed_name)``."""
+ from hermes_cli.plugins_cmd import _install_plugin_core, pinned_revision
if not allow_removed:
raise_if_removed(entry.name, entry.repo)
target, manifest, installed_name = _install_plugin_core(
entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,
- reviewed_pin=entry.sha, python_deps=python_deps)
- write_catalog_sidecar(target, entry)
+ reviewed_pin=entry.sha, python_deps=python_deps, allow_removed=allow_removed,
+ catalog={"name": entry.name, "repo": entry.repo, "tier": entry.tier, "pin": entry.sha})
+ write_catalog_sidecar(target, entry, sha=pinned_revision(target.name))
return target, manifest, installed_name
-def repin_catalog_plugin(target: Path, sidecar: dict) -> tuple[str, bool]:
- """Re-pin a catalog install to the current catalog SHA (never ``git pull``). Returns
- ``(new_sha, changed)``; raises ``PluginOperationError`` when the entry left the catalog."""
- from hermes_cli.plugins_cmd import PluginOperationError, _get_enabled_set, _save_enabled_set
+def installed_plugin_removal(name: str, plugin_dir) -> Optional[RemovedEntry]:
+ """Kill-list verdict for an INSTALLED plugin (manifest name, dir name, catalog name or recorded
+ source), or ``None``. A record carrying ``allow_removed`` (the user bypassed the list at install) is
+ honoured; the check is offline (in-tree list + cached live copy) so load time never blocks on the
+ catalog host."""
+ plugin_dir = Path(plugin_dir) if plugin_dir else None
+ record = (_install_record(plugin_dir) if plugin_dir else None) or {}
+ if record.get("allow_removed") is True:
+ return None
+ block = record.get("catalog") if isinstance(record.get("catalog"), dict) else {}
+ source = str(record.get("source") or "").split("#", 1)[0]
+ candidates = [name, source, block.get("name"), block.get("repo"), plugin_dir.name if plugin_dir else None]
+ entries = cached_removed_entries()
+ for candidate in candidates:
+ removed = match_removed(str(candidate), entries) if candidate else None
+ if removed is not None:
+ return removed
+ return None
+
+
+def refuse_if_installed_removed(name: str, plugin_dir) -> None:
+ """``PluginOperationError`` form of :func:`installed_plugin_removal` for ``update``/``enable``, which
+ otherwise keep pulling and activating code the catalog recalled."""
+ from hermes_cli.plugins_cmd import PluginOperationError
+ removed = installed_plugin_removal(name, plugin_dir)
+ if removed is not None:
+ raise PluginOperationError(
+ f"Plugin '{name}' was removed from the Hermes plugin catalog: "
+ f"{removed.reason or 'no reason recorded'}. Remove it with `hermes plugins remove {name}`, "
+ "or reinstall with `hermes plugins install <source> --force --allow-removed` if you trust it.")
+
+
+_PRESERVE_SKIP = ("__pycache__",)
+
+
+def _local_changes(target: Path) -> tuple[list[str], list[str]]:
+ """``(untracked_or_ignored, modified_tracked)`` relative paths in a git checkout; empty for a
+ non-git tree (subdir installs carry no ``.git``, so nothing can be told apart from the clone)."""
+ from hermes_cli.plugins_cmd import _resolve_git_executable, _run_plugin_git
+ git_exe = _resolve_git_executable()
+ if not git_exe or not (target / ".git").exists():
+ return [], []
+ status = _run_plugin_git(git_exe, target, "status", "--porcelain", "--ignored", "-z", "--untracked-files=all",
+ "--ignored=matching", timeout=30)
+ if status.returncode != 0:
+ return [], []
+ local, modified = [], []
+ for item in status.stdout.split("\0"):
+ if len(item) < 4:
+ continue
+ code, rel = item[:2], item[3:]
+ if any(part in _PRESERVE_SKIP or part.endswith(".pyc") for part in Path(rel).parts):
+ continue
+ (local if code in ("??", "!!") else modified).append(rel)
+ return local, modified
+
+
+def _stash_local_files(target: Path, rels: list[str], stash: Path) -> None:
+ for rel in rels:
+ src = target / rel
+ if src.is_file():
+ dst = stash / rel
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src, dst)
+
+
+class RepinResult(NamedTuple):
+ sha: str
+ changed: bool
+ installed_name: str
+ warnings: list[str]
+
+
+def repin_catalog_plugin(target: Path, sidecar: dict) -> RepinResult:
+ """Re-pin a catalog install to the current catalog SHA (never ``git pull``). The force reinstall
+ replaces the whole tree, so the user's untracked/ignored files (installer-created ``config.yaml``,
+ data) are carried into the new tree and edits to TRACKED files are saved under
+ ``<HERMES_HOME>/plugins-backup/<name>-<sha8>/`` with a warning. A manifest rename between pins moves the
+ enabled flag and removes the stale dir. Raises ``PluginOperationError`` when the entry left the catalog."""
+ from hermes_cli.plugins_cmd import (
+ PluginOperationError, _get_enabled_set, _plugins_dir, _remove_plugin_core, _save_enabled_set)
catalog_name = str(sidecar["catalog_name"])
entry = get_live_catalog_entry(catalog_name)
if entry is None:
@@ -136,26 +264,47 @@ def repin_catalog_plugin(target: Path, sidecar: dict) -> tuple[str, bool]:
f"Plugin '{catalog_name}' is no longer in the catalog — it may have been removed. "
"See `hermes plugins info` and the removed blocklist.")
if str(sidecar.get("sha") or "").strip().lower() == entry.sha:
- return entry.sha, False
+ return RepinResult(entry.sha, False, target.name, [])
was_enabled = _get_enabled_set() # the force reinstall must not flip activation state
- install_catalog_entry(entry, force=True)
+ local, modified = _local_changes(target)
+ old_sha8 = str(sidecar.get("sha") or "old")[:8]
+ with tempfile.TemporaryDirectory(prefix=".repin-", dir=_plugins_dir()) as tmp:
+ stash = Path(tmp) / "local"
+ _stash_local_files(target, local, stash)
+ # Outside the plugins dir: the discovery scanners recurse into every subdirectory there.
+ backup = _plugins_dir().parent / "plugins-backup" / f"{target.name}-{old_sha8}"
+ _stash_local_files(target, modified, backup)
+ new_target, _manifest, installed_name = install_catalog_entry(entry, force=True)
+ if stash.exists():
+ shutil.copytree(stash, new_target, dirs_exist_ok=True)
+ warnings: list[str] = []
+ if modified:
+ warnings.append(f"Local edits to {len(modified)} tracked file(s) were not carried over; copies are under "
+ f"{backup} (the previous version's files, re-apply by hand).")
+ if new_target != target and target.exists():
+ _remove_plugin_core(target)
+ if target.name in was_enabled:
+ was_enabled = (was_enabled - {target.name}) | {installed_name}
+ warnings.append(f"Plugin renamed itself from '{target.name}' to '{installed_name}'; the old directory was removed.")
_save_enabled_set(was_enabled)
- return entry.sha, True
+ return RepinResult(entry.sha, True, installed_name, warnings)
def cmd_update_catalog(name: str, target: Path, sidecar: dict, console) -> None:
from hermes_cli.plugins_cmd import PluginOperationError, _fail
console.print(f"[dim]Checking catalog pin for {name}...[/dim]")
try:
- sha, changed = repin_catalog_plugin(target, sidecar)
+ result = repin_catalog_plugin(target, sidecar)
except PluginOperationError as exc:
_fail(console, f"[red]Error:[/red] {exc}")
raise SystemExit(1)
- verb = "updated to" if changed else "is already at catalog pin"
- console.print(f"[green]✓[/green] Plugin [bold]{name}[/bold] {verb} {sha[:8]}.")
- if changed:
+ verb = "updated to" if result.changed else "is already at catalog pin"
+ console.print(f"[green]✓[/green] Plugin [bold]{result.installed_name}[/bold] {verb} {result.sha[:8]}.")
+ for warning in result.warnings:
+ console.print(f"[yellow]⚠ {warning}[/yellow]")
+ if result.changed:
from hermes_cli.plugins_cmd import _install_python_dependencies
- _install_python_dependencies(target, console)
+ _install_python_dependencies(target.parent / result.installed_name, console)
# ── search / browse / info / validate ────────────────────────────────────────
@@ -291,7 +440,7 @@ def installed_catalog_state(installed: Dict[str, Dict[str, Any]]) -> Dict[str, A
})
return {
"entries": entries,
- "removed": [{"name": r.name, "repo": r.repo, "reason": r.reason, "date": r.date} for r in load_removed_list()],
+ "removed": [{"name": r.name, "repo": r.repo, "reason": r.reason, "date": r.date} for r in resolved_removed_entries()],
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
}
diff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.py
index 06a544943ca..dd38a5edb8f 100644
--- a/hermes_cli/plugins_discovery.py
+++ b/hermes_cli/plugins_discovery.py
@@ -222,4 +222,13 @@ def gate_manifest(
f"not enabled in config (run `hermes plugins enable {lookup_key}` to activate)", logging.DEBUG,
"Skipping '%s' (not in plugins.enabled)",
)
+ if manifest.source != "bundled":
+ # The catalog kill list is enforced at install; a plugin recalled AFTER it was installed must not keep
+ # loading. Offline check (in-tree list + cached live copy), honours an explicit install-time bypass.
+ from hermes_cli.plugins_cmd_catalog import installed_plugin_removal
+ removed = installed_plugin_removal(manifest.name, manifest.path)
+ if removed is not None:
+ error = f"removed from the Hermes plugin catalog: {removed.reason or 'no reason recorded'}"
+ return _placeholder(error, logging.WARNING, "Refusing to load plugin '%s' — %s; run `hermes plugins remove`",
+ error)
return ManifestGate("load")
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md
index c446de6e2d9..71b70ac7fdc 100644
--- a/plugins/AGENTS.md
+++ b/plugins/AGENTS.md
@@ -35,7 +35,13 @@ command. A hook with no concrete consumer is speculative infrastructure and is r
The ONLY discovery system for out-of-tree plugins. One YAML per entry, 40-hex SHA pin mandatory,
human-merged via PR (`plugin-catalog/README.md` = admission policy; `plugin-catalog-ci.yml` clones
each changed entry at its pin and runs `hermes plugins validate`). `removed.yaml` is the kill list —
-every install path (CLI, dashboard, TUI) refuses matches; only the CLI has a loud `--allow-removed`.
+every install path (CLI, dashboard, TUI) refuses matches (repo URLs compared by canonical
+`host/owner/repo`, so `git@`/`ssh://`/`www.` spellings match); only the CLI has a loud
+`--allow-removed`, which is recorded on the install record and is the only thing that exempts an
+installed plugin from the same check at `update`, `enable` and load (`gate_manifest`). Catalog
+provenance lives on the installer-owned `.install-metadata.json` record (`catalog` block, sha =
+checked-out commit), NEVER in the tree: the in-tree `.hermes-catalog.json` is a convenience copy the
+Desktop reads for "Install here"; Python never trusts it (a repo can ship a forged one).
Code: `hermes_cli/plugin_catalog.py` (loader, live refresh from
`/docs/api/plugin-catalog.json` published by the docs build, in-tree fallback),
`hermes_cli/plugins_cmd_catalog.py` (resolution, `.hermes-catalog.json` provenance sidecar,
diff --git a/tests/hermes_cli/test_plugin_catalog.py b/tests/hermes_cli/test_plugin_catalog.py
index 6a8f4587aa3..7856a428354 100644
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@ -82,6 +82,11 @@ def test_find_removed_matches_name_or_normalized_repo(tmp_path):
assert pc.find_removed("evil", tmp_path).reason == "malware"
assert pc.find_removed("https://github.com/x/EVIL/", tmp_path) is not None
assert pc.find_removed("https://github.com/x/fine", tmp_path) is None
+ # Scheme/host/user spellings are not identity: every git way of naming the repo is blocked.
+ for spelling in ("[email protected]:x/evil.git", "ssh://[email protected]/x/evil", "http://github.com/x/evil",
+ "https://www.github.com/x/evil/", "git://github.com/x/evil.git"):
+ assert pc.find_removed(spelling, tmp_path) is not None, spelling
+ assert pc.find_removed("[email protected]:x/evil.git", tmp_path) is None # different host stays distinct
def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_plugins_cmd_catalog.py b/tests/hermes_cli/test_plugins_cmd_catalog.py
index c7c99c02363..1c3436566cd 100644
--- a/tests/hermes_cli/test_plugins_cmd_catalog.py
+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py
@@ -111,3 +111,83 @@ def test_owner_repo_hash_subdir_shorthand_resolves_like_the_catalog_spelling():
assert _resolve_git_url("plastic-labs/honcho#hermes-plugin-honcho") == (
"https://github.com/plastic-labs/honcho.git", "hermes-plugin-honcho")
assert _resolve_git_url("owner/repo") == ("https://github.com/owner/repo.git", None)
+
+
+def _install_url(repo: Path, name: str, files: dict) -> Path:
+ """A URL (non-catalog) install of a fresh repo carrying *files*."""
+ repo.mkdir()
+ (repo / "plugin.yaml").write_text(f"name: {name}\nversion: 1.0.0\ndescription: d\n")
+ (repo / "__init__.py").write_text("def register(ctx):\n pass\n")
+ for rel, text in files.items():
+ (repo / rel).write_text(text)
+ sp.run(["git", "init", "-q"], cwd=repo, check=True, env=_GIT_ENV)
+ _commit(repo, "v1")
+ return pc._install_plugin_core(repo.as_uri(), force=False)[0]
+
+
+def test_in_tree_sidecar_cannot_forge_catalog_provenance(world, tmp_path):
+ """Provenance is the installer's metadata record, never a file the repo ships: a URL install carrying
+ its own .hermes-catalog.json is not a catalog install and does not mark the real entry installed."""
+ forged = json.dumps({"catalog_name": "cat-plugin", "tier": "official", "sha": "0" * 40, "repo": "x"})
+ target = _install_url(tmp_path / "evil", "evil-plugin", {cat.CATALOG_SIDECAR: forged})
+ assert (target / cat.CATALOG_SIDECAR).exists() # the file is there, and inert
+ assert cat.read_catalog_sidecar(target) is None
+ assert cat.catalog_annotation(target) is None
+ assert cat.catalog_row_fields(target, cat.catalog_pins()) == {}
+ state = cat.installed_catalog_state({"evil-plugin": {"dir": str(target), "runtime_status": None}})
+ assert state["entries"][0]["installed"] is False
+ # Control: a real catalog install is still recognised through the metadata record.
+ real, _m, _n = cat.install_catalog_entry(pc_cat.get_live_catalog_entry("cat-plugin"), force=False)
+ assert cat.catalog_annotation(real) == f"catalog:community@{world['sha1'][:8]}"
+
+
+def test_ref_install_records_installed_sha_so_update_is_offered(world):
+ """`install NAME --ref X` checks out X, not the reviewed pin; provenance must say X so list/TUI flag the
+ drift and `update` re-pins instead of answering 'already at catalog pin'."""
+ entry = pc_cat.get_live_catalog_entry("cat-plugin")
+ target, _m, _n = cat.install_catalog_entry(entry, force=False, ref=world["sha2"])
+ assert _head(target) == world["sha2"]
+ assert cat.read_catalog_sidecar(target)["sha"] == world["sha2"]
+ assert cat.catalog_row_fields(target, cat.catalog_pins())["update_available"] is True
+ result = pc.dashboard_update_user_plugin("cat-plugin")
+ assert result["unchanged"] is False and _head(target) == world["sha1"]
+
+
+def test_repin_keeps_local_files_backs_up_edits_and_follows_manifest_rename(world, monkeypatch):
+ entry = pc_cat.get_live_catalog_entry("cat-plugin")
+ target, _m, _n = cat.install_catalog_entry(entry, force=False)
+ (target / "config.yaml").write_text("api_key: real\n") # installer/user data
+ (target / "__init__.py").write_text("def register(ctx):\n pass # mine\n") # tracked edit
+ pc._save_enabled_set({"cat-plugin"})
+ # New pin renames the manifest.
+ repo = world["repo"]
+ (repo / "plugin.yaml").write_text("name: cat-plugin-v2\nversion: 2.0.0\ndescription: d\n")
+ world["state"]["pin"] = _commit(repo, "rename")
+ result = pc.dashboard_update_user_plugin("cat-plugin")
+ new_target = world["plugins_dir"] / "cat-plugin-v2"
+ assert result["ok"] and result["name"] == "cat-plugin-v2" and _head(new_target) == world["state"]["pin"]
+ assert (new_target / "config.yaml").read_text() == "api_key: real\n"
+ assert not target.exists() and "cat-plugin" not in pc._read_install_metadata()
+ assert pc._get_enabled_set() == {"cat-plugin-v2"}
+ backups = list((world["plugins_dir"].parent / "plugins-backup").glob("cat-plugin-*/__init__.py"))
+ assert backups and "# mine" in backups[0].read_text()
+ assert any("plugins-backup" in w for w in result["warnings"]) and any("renamed" in w for w in result["warnings"])
+
+
+def test_kill_list_covers_update_enable_and_load_of_an_installed_plugin(world, tmp_path, monkeypatch):
+ """A URL install whose name lands on the kill list AFTER install must stop pulling, cannot be enabled
+ and is refused at load; an install made with --allow-removed keeps working."""
+ from hermes_cli.plugins_discovery import gate_manifest
+ from hermes_cli.plugins_manifest import PluginManifest
+ target = _install_url(tmp_path / "later-killed", "killed", {})
+ world["state"]["removed"].append(pc_cat.RemovedEntry(name="killed", reason="backdoor"))
+ monkeypatch.setattr(pc_cat, "_live_cache_path", lambda: tmp_path / "no-cache.json")
+ assert "backdoor" in pc.dashboard_update_user_plugin("killed")["error"]
+ with pytest.raises(SystemExit):
+ pc.cmd_enable("killed")
+ assert "killed" not in pc._get_enabled_set()
+ manifest = PluginManifest(name="killed", source="user", path=str(target), key="killed")
+ assert gate_manifest(manifest, set(), {"killed"}).action != "load"
+ # Explicit bypass at install time is remembered.
+ pc.cmd_install((tmp_path / "later-killed").as_uri(), force=True, enable=False, allow_removed=True)
+ assert gate_manifest(manifest, set(), {"killed"}).action == "load"
diff --git a/tests/hermes_cli/test_web_plugins_catalog.py b/tests/hermes_cli/test_web_plugins_catalog.py
index 26c80aa440c..b0bd0e85271 100644
--- a/tests/hermes_cli/test_web_plugins_catalog.py
+++ b/tests/hermes_cli/test_web_plugins_catalog.py
@@ -1,5 +1,5 @@
"""Dashboard plugin-catalog surface: GET /api/dashboard/plugins/catalog merges installed state (via the
-``.hermes-catalog.json`` sidecar) and the install endpoint has NO kill-list bypass."""
+install-metadata ``catalog`` record) and the install endpoint has NO kill-list bypass."""
from __future__ import annotations
@@ -42,12 +42,18 @@ def client(monkeypatch, tmp_path, _isolate_hermes_home):
def _install(name: str, sidecar: dict | None):
+ """A user-dir plugin; *sidecar* records catalog provenance the way the installer does — on the
+ installer-owned ``.install-metadata.json`` record (an in-tree ``.hermes-catalog.json`` is inert)."""
from hermes_constants import get_hermes_home
+ from hermes_cli.plugins_cmd import _read_install_metadata, _write_install_metadata
d = get_hermes_home() / "plugins" / name
d.mkdir(parents=True)
(d / "plugin.yaml").write_text(yaml.safe_dump({"name": name, "version": "1.0", "description": "x"}))
if sidecar:
- (d / ".hermes-catalog.json").write_text(json.dumps(sidecar))
+ block = {"name": sidecar["catalog_name"], "sha": sidecar["sha"], "tier": sidecar.get("tier", "community")}
+ _write_install_metadata({**_read_install_metadata(), name: {
+ "pinned": True, "revision": sidecar["sha"], "source": "https://github.com/example/alpha-plugin.git",
+ "catalog": block}})
def test_catalog_endpoint_merges_installed_state_from_sidecar(client):
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index ed246afcec1..ae7bfc4e569 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1498,10 +1498,11 @@ def _plugins_update(rid, params):
if not sidecar:
return _err(rid, 4020, f"'{name}' is not a catalog install — update it via the CLI")
try:
- sha, changed = cat.repin_catalog_plugin(target, sidecar)
+ result = cat.repin_catalog_plugin(target, sidecar)
except pc.PluginOperationError as e:
return _err(rid, 4021, str(e))
- return _ok(rid, {"ok": True, "unchanged": not changed, "sha": sha})
+ return _ok(rid, {"ok": True, "unchanged": not result.changed, "sha": result.sha, "name": result.installed_name,
+ "warnings": list(result.warnings)})
def _plugins_remove(rid, params):
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index e371552a4dd..48fe123aae0 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1622,7 +1622,7 @@ Unified plugin management — general plugins, memory providers, and context eng
| Subcommand | Description |
|------------|-------------|
| *(none)* | Composite interactive UI — general plugin toggles + provider plugin configuration. |
-| `install <identifier> [--force] [--ref COMMIT_SHA] [--allow-removed]` | Install a plugin from the Hermes plugin catalog (bare entry name), a Git URL, or `owner/repo` shorthand. Catalog names resolve to the entry's repo at its pinned 40-hex commit SHA, show the declared capability summary, and record catalog provenance in a `.hermes-catalog.json` sidecar. Raw URLs are flagged as custom (unreviewed) sources; `--ref` (full 40-character commit SHA) pins them. `--allow-removed` (DANGEROUS) bypasses the removed-plugin blocklist. |
+| `install <identifier> [--force] [--ref COMMIT_SHA] [--allow-removed]` | Install a plugin from the Hermes plugin catalog (bare entry name), a Git URL, or `owner/repo` shorthand. Catalog names resolve to the entry's repo at its pinned 40-hex commit SHA, show the declared capability summary, and record catalog provenance on the installer's `.install-metadata.json` record (a `.hermes-catalog.json` copy is written inside the plugin dir for convenience, but is never trusted). Raw URLs are flagged as custom (unreviewed) sources; `--ref` (full 40-character commit SHA) pins them, and on a catalog entry records the checked-out SHA rather than the reviewed pin. `--allow-removed` (DANGEROUS) bypasses the removed-plugin blocklist at install AND exempts that install from the update/enable/load-time kill-list checks. |
| `search [term] [--json]` | Search the Hermes plugin catalog (matches entry names, descriptions, and declared tools; omit `term` to list everything). The catalog is curated in-repo (`plugin-catalog/`), refreshed from the live repo with a 6-hour cache, and falls back to the in-tree copy offline. Cataloged ≠ audited — admission reviews the entry, not the code. |
| `update <name>` | Pull latest changes for an unpinned installed plugin. Pinned plugins must be reinstalled with `--force --ref <new-commit>` to move. |
| `remove <name>` (aliases: `rm`, `uninstall`) | Remove an installed plugin. |
diff --git a/website/docs/user-guide/features/plugin-catalog.md b/website/docs/user-guide/features/plugin-catalog.md
index 66d0d0830e4..ee127c22876 100644
--- a/website/docs/user-guide/features/plugin-catalog.md
+++ b/website/docs/user-guide/features/plugin-catalog.md
@@ -89,7 +89,12 @@ The catalog is designed so you know exactly what you're installing:
etc.) it needs, so you can judge its blast radius before installing.
- **Removed list.** Plugins pulled from the catalog (for example after a
security incident) go on `plugin-catalog/removed.yaml` with a reason and
- date. The installer refuses to install anything on the removed list.
+ date. Matching is by name or repository identity — `git@`, `ssh://`,
+ `http://` and `www.` spellings of the same repo all match. The installer
+ refuses to install anything on the removed list, and a plugin that lands on
+ the list *after* you installed it stops updating, cannot be enabled and is
+ refused at load time (`hermes plugins remove <name>`, or reinstall with
+ `--allow-removed` to keep it knowingly).
- **Installed ≠ enabled.** Installing a catalog plugin puts it on disk; like
any plugin it must still be enabled before it loads. See
[Plugins → Enabling and disabling](plugins.md).
@@ -141,9 +146,21 @@ hermes plugins enable snyk
`hermes plugins update <name>` never runs `git pull` for catalog installs —
it compares your installed pin against the current catalog pin and, when the
catalog moved (via a reviewed PR), force-reinstalls at the new SHA. Your
-enabled/disabled state is preserved. `hermes plugins list` shows catalog
+enabled/disabled state is preserved, and so are files the plugin's repo does
+not track (the `config.yaml` created from its `.example`, data files, `.env`).
+Edits you made to *tracked* files are not carried onto the new code; copies are
+saved under `~/.hermes/plugins-backup/<name>-<sha>/` and the update warns you.
+If the new pin renames the plugin's manifest, the old directory is removed and
+your enabled flag follows the new name. `hermes plugins list` shows catalog
installs as `catalog:<tier>@<sha>` so you can see provenance at a glance.
+Provenance is recorded by the installer in `~/.hermes/plugins/.install-metadata.json`,
+outside the plugin's own tree — a repository cannot ship a file that makes it
+look like a reviewed catalog install. (The `.hermes-catalog.json` inside the
+plugin directory is a convenience copy only.) Installing a catalog entry with
+`--ref <sha>` records the SHA you actually checked out, so `list`, the Desktop
+Plugins tab and `update` all report it as off the reviewed pin.
+
### Names not in the catalog
A bare name that isn't a catalog entry is an error: there is no second,