Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernetd0d4e9143449
diff --cc hermes_cli/plugins_cmd.py
index b4eade1722c,b7c65fe521d..8dec5b90086
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@@ -775,8 -733,11 +776,11 @@@ def _install_plugin_core
"""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). *catalog*
+ only when the checked-out revision is exactly that sha. *python_deps* False refuses
- active replacements; it never bypasses PM dependency admission."""
++ active replacements; it never bypasses PM dependency admission. *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)
@@@ -828,29 -784,14 +832,34 @@@
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}
++ "pinned": requested_revision is not None,
++ "revision": installed_revision,
++ "source": source,
+ }
+ # Saved update_url tag (settled: claims vs provenance): the
+ # manifest's update_url is COPIED into the row at install. Check
+ # time compares manifest vs tag; a mismatch is needs-fixing and
+ # only `hermes plugins trust-update-url` moves the tag.
+ if manifest.get("update_url"):
+ from hermes_cli.plugins_updates import https_update_url
+ try:
- new_metadata[plugin_name]["update_url"] = https_update_url(manifest["update_url"])
++ record["update_url"] = https_update_url(manifest["update_url"])
+ except ValueError as exc:
+ raise PluginOperationError(f"Plugin '{plugin_name}' {exc}") from exc
- if catalog_entry is not None:
- new_metadata[plugin_name]["catalog_name"] = catalog_entry.name
- new_metadata[plugin_name]["catalog_tier"] = catalog_entry.tier
+ if catalog:
+ record["catalog"] = {**catalog, "sha": installed_revision}
++ from hermes_cli.plugins_cmd_catalog import write_catalog_sidecar_record
++ write_catalog_sidecar_record(tmp_target, catalog, 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)
+ from hermes_cli.plugins_transaction import publish_plugin
+
+ try:
+ publish_plugin(tmp_target, target, old_metadata, new_metadata, require_consent=True)
+ except Exception as exc:
+ raise PluginOperationError(f"Plugin '{plugin_name}' was not published: {exc}") from exc
if not _looks_like_plugin_dir(target):
logger.warning("%s has no plugin.yaml / __init__.py; may not be a valid plugin", plugin_name)
@@@ -1000,14 -899,24 +1009,17 @@@ def _pull_plugin_update(target: Path, p
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)
- if not ok:
- raise PluginOperationError(output)
- # Store the new HEAD in the plugin's install-metadata record (if it has one).
- git_exe = _resolve_git_executable() if install_record else None
- if git_exe:
- install_record["revision"] = _git_head_revision(target, git_exe)
- metadata[target.name] = install_record
- _write_install_metadata(metadata)
- return output
-
-
-def cmd_update(name: str) -> None:
+ from hermes_cli.plugins_transaction import update_plugin
+
+ return update_plugin(target, interactive=interactive)
+
+
+def cmd_update(name: str, *, interactive: bool = True) -> None:
"""Update an installed plugin by pulling latest from its git remote."""
from rich.markup import escape
from hermes_cli import plugins_cmd_catalog as catalog
@@@ -2295,13 -1995,14 +2314,14 @@@ def dashboard_update_user_plugin(name:
target = _user_installed_plugin_dir(name)
if target is None:
return {"ok": False, "error": f"Plugin '{name}' was not found under {_plugins_dir()}."}
- sidecar = catalog.read_catalog_sidecar(target)
+ sidecar = catalog.catalog_install_record(target)
try:
if sidecar:
- sha, changed = catalog.repin_catalog_plugin(target, sidecar)
- warnings: list[str] = []
- deps = _python_dependency_summary(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 []
++ deps = _python_dependency_summary(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 --cc hermes_cli/plugins_cmd_catalog.py
index dfd3e72f988,7c2f088bd01..35fe6ffa6bb
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@@ -22,6 -24,9 +24,8 @@@ from hermes_cli.plugin_catalog import
logger = logging.getLogger(__name__)
+ CATALOG_SIDECAR = ".hermes-catalog.json"
+
-
# ── Resolution / provenance ──────────────────────────────────────────────────
def looks_like_catalog_name(identifier: str) -> bool:
@@@ -57,23 -62,82 +61,121 @@@ def resolve_catalog_name(identifier: st
return entry
- def catalog_install_record(plugin_dir) -> Optional[dict]:
- """Project catalog fields from the one authoritative install record."""
- from hermes_cli.plugins_provenance import read_sidecar_rows
-def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry, sha: Optional[str] = None) -> None:
++def write_catalog_sidecar_record(target: Path, catalog: dict, sha: str) -> 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": sha or entry.sha, "tier": entry.tier,
++ "catalog_name": catalog["name"], "repo": catalog["repo"], "sha": sha,
++ "tier": catalog.get("tier") or "community",
+ "installed_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
+ .replace("+00:00", "Z"),
+ }
+ 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)
+
- if plugin_dir is None:
++def write_catalog_sidecar(target: Path, entry: PluginCatalogEntry, sha: Optional[str] = None) -> None:
++ write_catalog_sidecar_record(
++ target,
++ {"name": entry.name, "repo": entry.repo, "tier": entry.tier},
++ sha or entry.sha,
++ )
++
++
+ 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
- path = Path(plugin_dir)
- row = read_sidecar_rows(path.parent).get(path.name, {})
- if not row.get("catalog_name"):
+ try:
+ record = _read_install_metadata().get(plugin_dir.name)
+ except PluginOperationError:
return None
- return {"catalog_name": row["catalog_name"], "sha": row["revision"],
- "repo": str(row["source"]).split("#", 1)[0], "tier": row.get("catalog_tier", "community")}
+ return record if isinstance(record, dict) else None
+
+
++def _write_catalog_block(plugin_dir: Path, record: dict, block: dict) -> dict:
++ """Migrate one trusted installer record to the nested catalog contract."""
++ from hermes_cli.plugins_cmd import _read_install_metadata, _write_install_metadata
++ migrated = dict(record)
++ migrated["catalog"] = block
++ migrated.pop("catalog_name", None)
++ migrated.pop("catalog_tier", None)
++ metadata = _read_install_metadata()
++ metadata[plugin_dir.name] = migrated
++ _write_install_metadata(metadata)
++ return block
++
++
+ 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")) if path.is_file() else None
++ data = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else None
+ except Exception:
+ return 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
++ return _write_catalog_block(plugin_dir, record, 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)
++ # PM-era installs already kept catalog identity in this installer-owned
++ # record, but used top-level fields. Migrate those without consulting
++ # the plugin tree, then retain the older sidecar migration for releases
++ # that predate the shared record.
++ legacy_name = record.get("catalog_name")
++ if legacy_name:
++ sha = str(record.get("revision") or "").lower()
++ block = {
++ "name": str(legacy_name),
++ "repo": str(record.get("source") or "").split("#", 1)[0],
++ "tier": str(record.get("catalog_tier") or "community"),
++ "pin": sha,
++ "sha": sha,
++ }
++ block = _write_catalog_block(plugin_dir, record, block)
++ else:
++ 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_install_record(plugin_dir) -> Optional[dict]:
++ """Catalog fields from the authoritative installer-owned record."""
++ return read_catalog_sidecar(plugin_dir)
+
+
def catalog_annotation(dir_path) -> Optional[str]:
"""``catalog:<tier>@<sha8>`` for a catalog install (``list`` Source column), else ``None``."""
- sidecar = read_catalog_sidecar(dir_path)
+ sidecar = catalog_install_record(dir_path)
if not sidecar:
return None
return f"catalog:{sidecar.get('tier') or 'community'}@{str(sidecar.get('sha') or '')[:8]}"
@@@ -98,48 -162,149 +200,166 @@@ def removed_annotation(name: str, dir_p
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 the catalog pin with provenance in the shared install record.
- Returns the core's ``(target, manifest, installed_name)``."""
+ """``_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
+ from hermes_cli.plugins_cmd import _install_plugin_core
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,
- catalog_entry=entry if ref is None or ref == entry.sha else None,
- reviewed_pin=entry.sha,
- python_deps=python_deps)
+ 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, *, interactive: bool = False) -> tuple[str, bool]:
- """Re-pin a catalog install to the current catalog SHA (never ``git pull``). Returns
- ``(new_sha, changed)``; raises ``PluginOperationError`` when the entry left the catalog."""
+ 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__",)
++_PRESERVE_SKIP = ("__pycache__", CATALOG_SIDECAR)
+
+
+ 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:
++def repin_catalog_plugin(target: Path, sidecar: dict, *, interactive: bool = False) -> 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)
++ from hermes_cli.plugins_cmd import PluginOperationError, _plugins_dir
catalog_name = str(sidecar["catalog_name"])
entry = get_live_catalog_entry(catalog_name)
if entry is None:
raise PluginOperationError(
f"Plugin '{catalog_name}' is no longer in the catalog — it may have been removed. "
"See `hermes plugins info` and the removed blocklist.")
- raise_if_removed(catalog_name, entry.repo)
++ refuse_if_installed_removed(catalog_name, target)
if str(sidecar.get("sha") or "").strip().lower() == entry.sha:
- return entry.sha, False
- from hermes_cli.plugins_transaction import update_plugin
-
- update_plugin(target, catalog_entry=entry, interactive=interactive)
- return entry.sha, True
+ return RepinResult(entry.sha, False, target.name, [])
- was_enabled = _get_enabled_set() # the force reinstall must not flip activation state
+ 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)
++ from hermes_cli.plugins_transaction import update_plugin
++ update_plugin(target, catalog_entry=entry, interactive=interactive, preserved_files=stash)
++ from hermes_cli.plugins_cmd import _read_install_metadata
++ matches = []
++ for name, row in _read_install_metadata().items():
++ if not isinstance(row, dict):
++ continue
++ block = row.get("catalog")
++ if isinstance(block, dict) and block.get("name") == entry.name and row.get("revision") == entry.sha:
++ matches.append(name)
++ if len(matches) != 1:
++ raise PluginOperationError(
++ f"Catalog update published but its install record is ambiguous: {matches or 'missing' }.")
++ installed_name = matches[0]
++ new_target = target.parent / installed_name
+ 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():
++ from hermes_cli.plugins_cmd import (
++ _admit_and_save_plugin_sets, _get_disabled_set, _get_enabled_set, _remove_plugin_core)
++ enabled, disabled = _get_enabled_set(), _get_disabled_set()
++ selection_changed = False
++ for selected in (enabled, disabled):
++ if target.name in selected:
++ selected.remove(target.name)
++ selected.add(installed_name)
++ selection_changed = True
++ if selection_changed:
++ _admit_and_save_plugin_sets(
++ enabled, disabled, action=f"Rename plugin '{target.name}' to '{installed_name}'")
+ _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 RepinResult(entry.sha, True, installed_name, warnings)
-def cmd_update_catalog(name: str, target: Path, sidecar: dict, console) -> None:
+def cmd_update_catalog(name: str, target: Path, sidecar: dict, console, *, interactive: bool = True) -> None:
from hermes_cli.plugins_cmd import PluginOperationError, _fail
console.print(f"[dim]Checking catalog pin for {name}...[/dim]")
try:
- sha, changed = repin_catalog_plugin(target, sidecar, interactive=interactive)
- result = repin_catalog_plugin(target, sidecar)
++ result = repin_catalog_plugin(target, sidecar, interactive=interactive)
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]}.")
+ 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.parent / result.installed_name, console)
++
# ── search / browse / info / validate ────────────────────────────────────────
diff --cc hermes_cli/plugins_transaction.py
index 852577a16ca,00000000000..9dfdef3ae04
mode 100644,000000..100644
--- a/hermes_cli/plugins_transaction.py
+++ b/hermes_cli/plugins_transaction.py
@@@ -1,164 -1,0 +1,193 @@@
+"""Publish plugin code and its dependency selection through one recoverable handoff."""
+from __future__ import annotations
+
+from pathlib import Path
+import shutil
+
+
+def recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:
+ """Recover a shipped caller's row through the stdlib boot-journal owner."""
+ from hermes_cli.runtime_state import _recover_plugin_publication
+
+ _recover_plugin_publication(project, row, journal)
+
+
+def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict,
+ *, target_digest: str | None = None, require_consent: bool = False) -> None:
+ from pm.client import sync_venv
+ from pm.store import tree_digest
+
+ if require_consent:
+ from hermes_cli import plugins_cmd
+ from pm.workspace import enabled_plugin_dirs
+
+ if target.resolve() in enabled_plugin_dirs(installing=target):
+ consented, reason = plugins_cmd._install_plugin_python_deps(
+ plugins_cmd._read_manifest_for_install(staged), staged, plugins_cmd._console())
+ if not consented:
+ raise plugins_cmd.PluginOperationError(
+ f"Reinstall declined: {reason}. The installed plugin and active environment are unchanged.")
+
+ sync_venv(explicit=True, staged_plugin={
+ "staged": str(staged.resolve()), "target": str(target.absolute()),
+ "old_metadata": old_metadata, "new_metadata": new_metadata,
+ "target_digest": target_digest if target_digest is not None else (tree_digest(target) if target.exists() else None),
+ })
+
+
+def _refresh_declared_dependencies(target: Path, staged: Path, manifest: dict, *, interactive: bool) -> None:
+ """Dependency changes carried by an update clear the same gates as an install.
+
+ New Python requirements install packages into the shared environment: install and
+ reinstall prompt for that, so an update prompts too, and an unattended one (dashboard,
+ ``plugins.auto_apply`` from the gateway) is REFUSED rather than consented on the user's
+ behalf. Publication replaces the whole tree, so a Node sidecar the user accepted earlier is
+ rebuilt in the staged copy when its package.json/lock moved (custom pulls copy a stale
+ node_modules; catalog re-pins clone without one).
+ """
+ from hermes_cli import plugins_cmd as pc
+ from hermes_cli.runtime_state import _bytes
+ from pm.plugin_declarations import read_python_declaration
+ from pm.workspace import enabled_plugin_dirs, install_node_sidecar
+
+ if (target / "node_modules").is_dir() and (staged / "package.json").is_file() and (
+ not (staged / "node_modules").is_dir()
+ or any(_bytes(target / name) != _bytes(staged / name) for name in ("package.json", "package-lock.json"))):
+ reason = install_node_sidecar(staged, explicit=True)
+ if reason:
+ raise pc.PluginOperationError(
+ f"Node dependencies could not be refreshed: {reason}. "
+ "The installed plugin and active environment are unchanged.")
+ if target.resolve() not in enabled_plugin_dirs(installing=target):
+ return # a disabled plugin's deps are admitted (and consented) by `hermes plugins enable`
+ before, after = read_python_declaration(target), read_python_declaration(staged)
+ added = tuple(spec for spec in after.install_requirements if spec not in before.install_requirements)
+ if not added and not (after.is_member and not before.is_member):
+ return
+ if not interactive:
+ raise pc.PluginOperationError(
+ f"The update declares new Python dependencies ({', '.join(added) or 'in its pyproject.toml'}); "
+ f"run `hermes plugins update {target.name}` in a terminal to review them.")
+ consented, reason = pc._consent_python_deps(manifest.get("name", target.name), added, pc._console())
+ if not consented:
+ raise pc.PluginOperationError(
+ f"Update declined: {reason}. The installed plugin and active environment are unchanged.")
+
+
- def update_plugin(target: Path, *, catalog_entry=None, interactive: bool = False) -> str:
++def update_plugin(
++ target: Path,
++ *,
++ catalog_entry=None,
++ interactive: bool = False,
++ preserved_files: Path | None = None,
++) -> str:
+ """Prepare a catalog re-pin or custom Git pull without changing the live tree.
+
+ *interactive*: a terminal user is present to consent to newly declared dependencies;
+ the dashboard and the gateway's auto-apply pass False and get a refusal instead."""
+ import tempfile
+
+ from hermes_cli import plugins_cmd as pc
- from hermes_cli.plugins_cmd_catalog import raise_if_removed
++ from hermes_cli.plugins_cmd_catalog import refuse_if_installed_removed
+ from pm.store import tree_digest
+
+ target = target.resolve()
+ metadata = pc._read_install_metadata()
+ record = dict(metadata.get(target.name, {}))
+ if catalog_entry is None and record.get("pinned"):
+ raise pc.PluginOperationError(f"Plugin '{target.name}' is pinned; reinstall with an explicit --ref to change it.")
+ source = catalog_entry.install_identifier if catalog_entry else str(record.get("source") or "")
+ if not source or (catalog_entry is None and not (target / ".git").is_dir()):
+ raise pc.PluginOperationError(f"Plugin '{target.name}' has no owned Git checkout; reinstall from its source.")
+ feed_revision = None
+ if catalog_entry is None:
+ from hermes_cli.plugins_provenance import Provenance, ProvenanceClass
+ from hermes_cli.plugins_updates import check_local_provenance, default_fetch, parse_feed_yml
+
+ checked = check_local_provenance(Provenance(target.name, ProvenanceClass.GIT, target, record))
+ if checked.needs_fixing:
+ raise pc.PluginOperationError(checked.needs_fixing)
+ if record.get("update_url"):
+ feed = parse_feed_yml(default_fetch(record["update_url"]))
+ proposed = (feed.get("artifacts") or {}).get("git", "")
+ if pc._EXACT_COMMIT_RE.fullmatch(proposed):
+ feed_revision = proposed.lower()
+ elif proposed not in (source, source.split("#", 1)[0]):
+ raise pc.PluginOperationError("Update feed must select a commit or the recorded Git source.")
+ if feed.get("min_hermes"):
+ pc._check_manifest_version({"requires_hermes": feed["min_hermes"]}, target.name)
- raise_if_removed(target.name, source.split("#", 1)[0])
++ refuse_if_installed_removed(target.name, target)
+ before = tree_digest(target)
+ with tempfile.TemporaryDirectory(prefix=".update-", dir=target.parent) as directory:
+ staged = Path(directory) / "plugin"
+ try:
+ if catalog_entry:
+ git_url, subdir = pc._resolve_git_url(source)
+ revision = pc._clone_plugin_repo(staged, git_url, catalog_entry.sha)
+ staged = pc._resolve_subdir_within(staged, subdir) if subdir else staged
- # Catalog re-pins cannot discard edits to a currently installed tree.
- if (target / ".git").is_dir():
- git = pc._resolve_git_executable()
- changed = pc._git_or_raise(git, target, "status", "--porcelain", "--untracked-files=normal",
- failure_prefix="Could not inspect plugin edits: ")
- if changed.stdout.strip():
- raise pc.PluginOperationError("Catalog plugin has local changes; save them before updating.")
+ output = f"Updated to catalog pin {revision}"
- record.update(catalog_name=catalog_entry.name, catalog_tier=catalog_entry.tier,
- pinned=True, source=pc._canonical_source(git_url, subdir))
++ catalog_record = {
++ "name": catalog_entry.name,
++ "repo": catalog_entry.repo,
++ "tier": catalog_entry.tier,
++ "pin": catalog_entry.sha,
++ "sha": revision,
++ }
++ record.update(
++ catalog=catalog_record,
++ pinned=True,
++ source=pc._canonical_source(git_url, subdir),
++ )
++ record.pop("catalog_name", None)
++ record.pop("catalog_tier", None)
++ from hermes_cli.plugins_cmd_catalog import write_catalog_sidecar_record
++ write_catalog_sidecar_record(staged, catalog_record, revision)
+ else:
+ # Copy Git metadata and local changes. Autostash only ever touches the copy.
+ shutil.copytree(target, staged, symlinks=True, ignore=shutil.ignore_patterns("__pycache__"))
+ if feed_revision:
+ git = pc._resolve_git_executable()
+ status = pc._git_or_raise(git, target, "status", "--porcelain", failure_prefix="Could not inspect plugin edits: ")
+ if status.stdout.strip():
+ raise pc.PluginOperationError("Pinned feed update has local changes; save them before updating.")
+ pc._checkout_exact_revision(staged, git, feed_revision)
+ output = f"Updated to feed commit {feed_revision}"
+ else:
+ ok, output = pc._git_pull_plugin_dir(staged)
+ if not ok:
+ raise pc.PluginOperationError(output)
+ revision = pc._git_head_revision(staged, pc._resolve_git_executable())
++ if preserved_files is not None and preserved_files.exists():
++ shutil.copytree(preserved_files, staged, dirs_exist_ok=True)
+ manifest = pc._read_manifest_for_install(staged)
- if manifest.get("name", target.name) != target.name:
++ installed_name = str(manifest.get("name") or target.name)
++ if catalog_entry is None and installed_name != target.name:
+ raise pc.PluginOperationError("The updated plugin changed its installed name; reinstall it explicitly.")
- pc._check_manifest_version(manifest, target.name)
++ try:
++ new_target = pc._sanitize_plugin_name(installed_name, target.parent)
++ except ValueError as exc:
++ raise pc.PluginOperationError(str(exc)) from exc
++ if new_target != target and new_target.exists():
++ raise pc.PluginOperationError(
++ f"The updated plugin renamed itself to '{installed_name}', but that plugin already exists.")
++ pc._check_manifest_version(manifest, installed_name)
+ pc._scan_plugin_tree(staged, source, force=False)
+ pc._copy_example_files(staged, pc._console())
+ _refresh_declared_dependencies(target, staged, manifest, interactive=interactive)
+ if tree_digest(target) != before:
+ raise pc.PluginOperationError("Plugin files changed while preparing the update; retry.")
+ record["revision"] = revision
- if tree_digest(staged) == before:
++ if new_target == target and tree_digest(staged) == before:
+ return output
- publish_plugin(staged, target, metadata, {**metadata, target.name: record}, target_digest=before)
++ publish_plugin(
++ staged,
++ new_target,
++ metadata,
++ {**metadata, installed_name: record},
++ target_digest=before if new_target == target else None,
++ )
+ return output
+ except pc.PluginOperationError:
+ raise
+ except Exception as exc:
+ raise pc.PluginOperationError(f"Plugin '{target.name}' update was not published: {exc}") from exc
diff --cc hermes_cli/plugins_updates.py
index 06f71dae30d,00000000000..450b403824d
mode 100644,000000..100644
--- a/hermes_cli/plugins_updates.py
+++ b/hermes_cli/plugins_updates.py
@@@ -1,438 -1,0 +1,444 @@@
+"""Plugin update checks — the standard, read-only 'is it outdated?' verb.
+
+Address resolution per plugin, in order, no derivation ever (settled
+2026-09-03, plugin-auto-update plan):
+ 1. saved sidecar tag + matching manifest update_url → fetch the feed yml
+ 2. manifest update_url differs from the saved tag (or appeared where
+ none was saved) → NEEDS-FIXING: fetch refused, tag untouched
+ 3. no update_url anywhere + git row → git ls-remote vs revision
+ 4. neither → manual/unupdatable
+Plus the pip world, stateless: entry-point discovery → installed version
+vs PyPI latest. NEVER mutates anything — no pulls, no row writes, no
+saved-tag changes.
+"""
+
+from __future__ import annotations
+
+import importlib.metadata
+import json
+import re
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from packaging.version import InvalidVersion, Version
+
+from hermes_cli.plugins_provenance import (
+ Provenance,
+ ProvenanceClass,
+ plugins_provenance,
+)
+
+_FETCH_TIMEOUT = 10.0
+_MAX_FEED_BYTES = 1 * 1024 * 1024
+_FULL_GIT_SHA_RE = re.compile(r"[0-9a-fA-F]{40}")
+
+
+def _version_is_newer(latest: str, current: str) -> Optional[bool]:
+ """Invalid versions are unknown, not evidence of an update."""
+ try:
+ return Version(latest) > Version(current)
+ except InvalidVersion:
+ return None
+
+
+@dataclass
+class CheckResult:
+ name: str
+ klass: str # provenance class value ('git', ...)
+ current: Optional[str] = None
+ latest: Optional[str] = None
+ update_available: Optional[bool] = None # None = unknown/uncheckable
+ needs_fixing: Optional[str] = None # mismatch reason when set
+ min_hermes: Optional[str] = None # feed's version floor, if any
+ reason: str = ""
+
+ def to_json(self) -> dict:
+ return {
+ "name": self.name,
+ "class": self.klass,
+ "current": self.current,
+ "latest": self.latest,
+ "update_available": self.update_available,
+ "needs_fixing": self.needs_fixing,
+ "min_hermes": self.min_hermes,
+ "reason": self.reason,
+ }
+
+
+def _read_manifest_field(plugin_dir: Path, key: str) -> Optional[str]:
+ """One field from the installed plugin.yaml (claims, not provenance)."""
+ import hermes_yaml as yaml
+
+ manifest = plugin_dir / "plugin.yaml"
+ if not manifest.is_file():
+ return None
+ try:
+ with manifest.open(encoding="utf-8-sig") as f:
+ data = yaml.safe_load(f) or {}
+ except Exception:
+ return None
+ if not isinstance(data, dict):
+ return None
+ value = data.get(key)
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+def check_local_provenance(prov: Provenance) -> CheckResult:
+ """Check installed provenance without fetching remote metadata."""
+ result = CheckResult(name=prov.name, klass=prov.klass.value)
+
+ if prov.klass is ProvenanceClass.MANUAL:
+ result.reason = "no provenance; not auto-updatable"
+ return result
+ if prov.klass is ProvenanceClass.DRIFT:
+ result.reason = (
+ f"provenance drift — sidecar records {prov.row.get('source')!r} "
+ "but the dir has no .git; reinstall from the recorded source"
+ )
+ return result
+ if prov.klass is ProvenanceClass.SELF_CLONED:
+ result.reason = "self-cloned; run `hermes plugins adopt` first"
+ return result
+
+ row = prov.row or {}
+ result.current = row.get("revision") or None
+ if row.get("pinned") is True:
+ result.update_available = False
+ result.reason = f"pinned @ {(result.current or '')[:12] or 'sha'}"
+ return result
+
+ # ── the saved-tag comparison (the security heart) ──────────────
+ saved = row.get("update_url") or None
+ claimed = _read_manifest_field(prov.path, "update_url")
+ if saved is None and claimed is not None:
+ # a pulled commit introduced a url where none was saved — same
+ # threat class as a swap; never adopt silently
+ result.needs_fixing = (
+ f"manifest declares update_url {claimed!r} but no url was saved "
+ "at install; run `hermes plugins trust-update-url` after review"
+ )
+ return result
+ if saved is not None and claimed != saved:
+ result.needs_fixing = (
+ f"update_url mismatch: saved {saved!r}, manifest declares "
+ f"{claimed!r}; run `hermes plugins trust-update-url` after review"
+ )
+ return result
+
+ return result
+
+
+def check_provenanced(
+ prov: Provenance,
+ *,
+ fetch: Callable[[str], str],
+ ls_remote: Callable[[str], str],
+) -> CheckResult:
+ """Check local provenance before contacting its approved update source."""
- if (prov.row or {}).get("catalog_name"):
++ row = prov.row or {}
++ catalog_value = row.get("catalog")
++ catalog: dict = catalog_value if isinstance(catalog_value, dict) else {}
++ catalog_name = catalog.get("name") or row.get("catalog_name")
++ if catalog_name:
+ from hermes_cli.plugin_catalog import find_removed, get_live_catalog_entry
+
- row = prov.row
+ result = CheckResult(name=prov.name, klass="catalog", current=row.get("revision"))
- removed = find_removed(row["catalog_name"]) or find_removed(str(row.get("source", "")).split("#", 1)[0])
++ removed = None if row.get("allow_removed") is True else (
++ find_removed(str(catalog_name))
++ or find_removed(str(catalog.get("repo") or row.get("source", "")).split("#", 1)[0])
++ )
+ if removed:
+ result.reason = f"removed from catalog: {removed.reason}"
+ return result
- entry = get_live_catalog_entry(row["catalog_name"])
++ entry = get_live_catalog_entry(str(catalog_name))
+ if entry is None:
+ result.reason = "catalog entry is unavailable; installed pin retained"
+ return result
+ result.latest = entry.sha
+ result.update_available = result.current != entry.sha
+ return result
+ result = check_local_provenance(prov)
+ if result.reason or result.needs_fixing:
+ return result
+ row = prov.row or {}
+ saved = row.get("update_url") or None
+
+ # ── 1. matching saved tag → fetch the feed ─────────────────────
+ if saved is not None:
+ try:
+ feed_text = fetch(saved)
+ except Exception as exc:
+ result.reason = f"feed fetch failed: {exc}"
+ return result
+ try:
+ feed = parse_feed_yml(feed_text)
+ except ValueError as exc:
+ result.reason = f"feed unparseable: {exc}"
+ return result
+ result.latest = feed.get("version")
+ result.min_hermes = feed.get("min_hermes")
+ # Like-for-like identity only (audit C17): a feed that ships a full
+ # git SHA compares SHA vs recorded revision; otherwise the feed's
+ # semantic version compares against the installed manifest's
+ # version. A SHA is never compared to a semantic version, and an
+ # uncomparable pair reads as unknown — not as an update.
+ feed_git = (feed.get("artifacts") or {}).get("git")
+ if feed_git and _FULL_GIT_SHA_RE.fullmatch(feed_git):
+ if not result.current or not _FULL_GIT_SHA_RE.fullmatch(
+ str(result.current)
+ ):
+ result.update_available = None
+ result.reason = (
+ "feed declares a git sha but the install records no "
+ "full revision sha to compare"
+ )
+ return result
+ # Case-equivalent hex only after format validation.
+ result.latest = feed_git.lower()
+ result.update_available = feed_git.lower() != result.current.lower()
+ return result
+ installed_version = _read_manifest_field(prov.path, "version")
+ if installed_version is None:
+ result.update_available = None
+ result.reason = (
+ f"feed declares version {result.latest!r} but the installed "
+ "plugin.yaml records no version to compare"
+ )
+ return result
+ # Like-for-like fields: the semantic branch compares version vs
+ # version, so `current` reports the installed version, not the
+ # recorded revision sha.
+ result.current = installed_version
+ result.update_available = _version_is_newer(result.latest, installed_version)
+ if result.update_available is None:
+ result.reason = (
+ f"cannot compare feed version {result.latest!r} with "
+ f"installed version {installed_version!r}"
+ )
+ return result
+
+ # ── 3. no update_url anywhere + git row → ls-remote ────────────
+ source = row.get("source") or ""
+ if not source:
+ result.reason = "no recorded source"
+ return result
+ try:
+ head = ls_remote(source)
+ except Exception as exc:
+ result.reason = f"ls-remote failed: {exc}"
+ return result
+ result.latest = head
+ result.update_available = bool(head) and head != result.current
+ return result
+
+
+def parse_feed_yml(text: str) -> dict:
+ """The electron-updater-derived feed shape: version, released,
+ min_hermes, artifacts{git,bundle,bundle_sha256}, notes_url."""
+ import hermes_yaml as yaml
+
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError as exc:
+ raise ValueError(f"invalid feed YAML: {exc}") from exc
+ if not isinstance(data, dict):
+ raise ValueError("feed must be a YAML mapping")
+ version = data.get("version")
+ if not isinstance(version, str) or not version.strip():
+ raise ValueError("feed missing 'version'")
+ out: dict[str, Any] = {"version": version.strip()}
+ for key in ("min_hermes", "notes_url"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ out[key] = value.strip()
+ artifacts = data.get("artifacts")
+ if isinstance(artifacts, dict):
+ git = artifacts.get("git")
+ if git is not None and not isinstance(git, str):
+ raise ValueError("feed artifacts.git must be a string")
+ out["artifacts"] = {
+ k: v for k, v in artifacts.items() if isinstance(v, str)
+ }
+ return out
+
+
+def _owning_distribution(ep) -> Optional[str]:
+ """The name of the distribution the entry point belongs to — metadata,
+ never a guess derived from the import module (audit C17)."""
+ dist = getattr(ep, "dist", None)
+ if dist is None:
+ return None
+ try:
+ return dist.metadata.get("Name") or None
+ except Exception:
+ return None
+
+
+def check_pip_plugins(
+ *,
+ installed_version: Callable[[str], str], # dist name -> version
+ pypi_latest: Callable[[str], Optional[str]], # dist name -> latest
+ entry_points: Optional[list] = None, # injectable for tests
+) -> list[CheckResult]:
+ """The pip world, stateless: entry-point dists vs PyPI. Nothing
+ recorded, nothing to drift."""
+ if entry_points is None:
+ entry_points = list(
+ importlib.metadata.entry_points().select(group="hermes_agent.plugins")
+ )
+ results: list[CheckResult] = []
+ for ep in entry_points:
+ dist_name = getattr(ep, "dist_name", None) or _owning_distribution(ep)
+ if not dist_name:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ reason=(
+ "entry point has no owning distribution metadata; "
+ "cannot determine what to check"
+ ),
+ )
+ )
+ continue
+ try:
+ current = installed_version(dist_name)
+ except importlib.metadata.PackageNotFoundError:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ reason=f"distribution {dist_name!r} not importable",
+ )
+ )
+ continue
+ latest = pypi_latest(dist_name)
+ # None (unknown / not on PyPI) must read as unknown — not False
+ if latest is None:
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ current=current,
+ latest=None,
+ update_available=None,
+ reason="unknown (not on PyPI)",
+ )
+ )
+ continue
+ update_available = _version_is_newer(latest, current)
+ results.append(
+ CheckResult(
+ name=ep.name,
+ klass="pip",
+ current=current,
+ latest=latest,
+ update_available=update_available,
+ reason=(
+ f"cannot compare PyPI version {latest!r} with installed {current!r}"
+ if update_available is None else ""
+ ),
+ )
+ )
+ return results
+
+
+def https_update_url(url: object) -> str:
+ """Normalize a manifest ``update_url``; raises ValueError unless it is ``https://``.
+
+ The feed picks which commit of the trusted origin gets installed and the gateway fetches
+ it unattended every check interval, so a plaintext ``http://`` (MITM → an old vulnerable
+ commit), ``file://`` or ``ftp://`` feed is refused at install, at trust-update-url AND at
+ the fetch itself (rows saved before this rule existed).
+ """
+ text = str(url or "").strip()
+ if not text.lower().startswith("https://"):
+ raise ValueError(f"update_url must be an https:// URL, got {text!r}")
+ return text
+
+
+def default_fetch(url: str) -> str:
+ """The real feed fetcher: url -> text (raises on failure).
+
+ ONE implementation shared by the manual ``hermes plugins
+ check-updates`` and the cadence tick — callers never re-derive it.
+ """
+ import urllib.request
+
+ with urllib.request.urlopen(https_update_url(url), timeout=_FETCH_TIMEOUT) as resp:
+ data = resp.read(_MAX_FEED_BYTES)
+ return data.decode("utf-8", errors="replace")
+
+
+def default_ls_remote(source: str) -> str:
+ """The real git probe: source -> HEAD sha (raises on failure).
+
+ Uses the same resolved git executable the CLI path resolves. Lazily
+ imports plugins_cmd (which lazily imports this module) — no import
+ cycle at module load.
+ """
+ from hermes_cli.plugins_cmd import _resolve_git_executable
+
+ proc = subprocess.run(
+ [_resolve_git_executable() or "git", "ls-remote", source, "HEAD"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if proc.returncode != 0:
+ raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])
+ # 'sha\trefs/heads/...' or empty
+ out = (proc.stdout or "").strip()
+ return out.split("\t")[0] if out else ""
+
+
+def run_checks(
+ plugins_dir: Path,
+ *,
+ fetch: Optional[Callable[[str], str]] = None,
+ ls_remote: Optional[Callable[[str], str]] = None,
+ include_pip: bool = True,
+ pip_installed_version: Callable[[str], str] = importlib.metadata.version,
+ pip_pypi_latest: Optional[Callable[[str], Optional[str]]] = None,
+ pip_entry_points: Optional[list] = None,
+) -> list[CheckResult]:
+ """All checks for one plugins dir. NEVER mutates anything.
+
+ ``fetch``/``ls_remote`` default to :func:`default_fetch` /
+ :func:`default_ls_remote` — the single shared network implementation
+ the manual command and the cadence tick both ride.
+ """
+ if fetch is None:
+ fetch = default_fetch
+ if ls_remote is None:
+ ls_remote = default_ls_remote
+ results = [
+ check_provenanced(p, fetch=fetch, ls_remote=ls_remote)
+ for p in plugins_provenance(plugins_dir)
+ ]
+ if include_pip:
+ if pip_pypi_latest is None:
+ pip_pypi_latest = _default_pypi_latest
+ results.extend(
+ check_pip_plugins(
+ installed_version=pip_installed_version,
+ pypi_latest=pip_pypi_latest,
+ entry_points=pip_entry_points,
+ )
+ )
+ return results
+
+
+def _default_pypi_latest(dist: str) -> Optional[str]:
+ """PyPI JSON API — the real fetcher (injectable in tests)."""
+ import urllib.request
+
+ url = f"https://pypi.org/pypi/{dist}/json"
+ try:
+ with urllib.request.urlopen(url, timeout=_FETCH_TIMEOUT) as resp:
+ data = json.loads(resp.read(_MAX_FEED_BYTES))
+ return (data.get("info") or {}).get("version")
+ except Exception:
+ return None
diff --cc tests/hermes_cli/test_plugin_catalog.py
index f9a24db26c5,7856a428354..5b136f5eebc
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@@ -87,21 -82,15 +87,26 @@@ def test_find_removed_matches_name_or_n
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):
[email protected]("stale", [False, True])
+def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkeypatch, stale):
"""Network failure → in-tree entries; a cached live doc contributes entries AND removals."""
+ import httpx
+
+ requests = []
+ get = httpx.get
+
+ def record_get(*args, **kwargs):
+ requests.append(args)
+ return get(*args, **kwargs)
+
+ monkeypatch.setattr(httpx, "get", record_get)
cache = tmp_path / "cache" / "plugin-catalog.json"
monkeypatch.setattr(pc, "_live_cache_path", lambda: cache)
monkeypatch.setattr(pc, "LIVE_CATALOG_URL", "http://127.0.0.1:9/nope") # unreachable
diff --cc tests/hermes_cli/test_plugin_update_transaction.py
index a5a5620f129,00000000000..749639321a9
mode 100644,000000..100644
--- a/tests/hermes_cli/test_plugin_update_transaction.py
+++ b/tests/hermes_cli/test_plugin_update_transaction.py
@@@ -1,254 -1,0 +1,254 @@@
+"""Catalog pins and custom Git updates publish only a validated dependency set."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+
+import pytest
+
+from tests.pm.test_plugin_survival_contract import admission_env # noqa: F401
+
+
+def _commit(repo, message):
+ env = {**os.environ, "GIT_AUTHOR_NAME": "fixture", "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "fixture", "GIT_COMMITTER_EMAIL": "[email protected]"}
+ subprocess.run(["git", "add", "--all"], cwd=repo, env=env, check=True, capture_output=True)
+ subprocess.run(["git", "commit", "-qm", message], cwd=repo, env=env, check=True, capture_output=True)
+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
+
+
+def _version(repo, version, *, broken=False, minimum="", libraries=("shared-library",)):
+ from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION
+
+ (repo / "plugin.yaml").write_text(
+ f"name: transactional\nversion: {version}\nmanifest_version: {SUPPORTED_MANIFEST_VERSION}\n"
+ f"requires_hermes: '{minimum}'\n", encoding="utf-8")
+ (repo / "__init__.py").write_text(f"VERSION = {version!r}\ndef register(ctx):\n pass\n", encoding="utf-8")
+ (repo / ".gitignore").write_text("node_modules/\n", encoding="utf-8")
+ deps = '["impossible-plugin-dep==1", "impossible-plugin-dep==2"]' if broken else '[]'
+ for name in libraries:
+ library = repo.parent / name
+ library.mkdir(exist_ok=True)
+ (library / "pyproject.toml").write_text(
+ f'[project]\nname="{name}"\nversion="1"\nrequires-python=">=3.14"\n'
+ '[tool.uv]\npackage=false\n', encoding="utf-8")
+ if not broken:
+ deps = json.dumps(list(libraries))
+ sources = "".join(f'{name}={{path="../{name}"}}\n' for name in libraries)
+ (repo / "pyproject.toml").write_text(
+ f'[project]\nname="transactional"\nversion="{version}"\nrequires-python=">=3.14"\n'
+ f'dependencies={deps}\n[tool.uv]\npackage=false\n'
+ f'[tool.uv.sources]\n{sources}', encoding="utf-8")
+ return _commit(repo, version)
+
+
+def installed(admission_env, monkeypatch, request):
+ from hermes_cli import plugin_catalog, plugins_cmd, plugins_cmd_catalog
+
+ root, home = admission_env
+ repo = root / "plugin-origin"
+ repo.mkdir()
+ subprocess.run(["git", "init", "-qb", "main"], cwd=repo, check=True, capture_output=True)
+ first = _version(repo, "1.0.0")
+ catalog = request.param == "catalog"
+ state = {"sha": first}
+
+ def entry():
+ return plugin_catalog.PluginCatalogEntry(
+ name="transactional", repo=repo.as_uri(), sha=state["sha"], description="fixture", maintainer="fixture")
+
+ monkeypatch.setattr(plugin_catalog, "fetch_live_catalog", lambda **kwargs: None)
+ monkeypatch.setattr(plugin_catalog, "load_catalog", lambda catalog_dir=None: [entry()])
+ monkeypatch.setattr(plugin_catalog, "load_removed_list", lambda catalog_dir=None: [])
+ monkeypatch.setattr(plugins_cmd, "_scan_on_install_enabled", lambda: False)
+ if catalog:
+ target, _, _ = plugins_cmd_catalog.install_catalog_entry(entry(), force=False)
+ else:
+ target, _, _ = plugins_cmd._install_plugin_core(repo.as_uri(), force=False)
+ import shutil
+
+ shutil.copytree(repo.parent / "shared-library", target.parent / "shared-library")
+ plugins_cmd._set_plugin_enabled("transactional", enable=True)
+ return root, home, repo, target, state
+
+
+def _head(repo) -> str:
+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
+def test_unattended_update_refuses_newly_declared_python_dependencies(installed):
+ """Install gates Python deps behind a prompt; an update that ADDS a dependency must not
+ slip them into the shared environment without one. With nobody to ask (dashboard, gateway
+ ``plugins.auto_apply``) the update is refused and nothing — code, env, metadata — moves."""
+ import shutil
+ from hermes_cli import plugins_cmd
+ from pm.environments import selected_venv
+
+ root, home, repo, target, state = installed
+ old_head, old_venv = _head(target), selected_venv(root / "core")
+ state["sha"] = _version(repo, "2.0.0", libraries=("shared-library", "second-library"))
+ shutil.copytree(repo.parent / "second-library", target.parent / "second-library", dirs_exist_ok=True)
+
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+
+ assert result["ok"] is False, result
+ assert "second-library" in result["error"]
+ assert _head(target) == old_head
+ assert selected_venv(root / "core") == old_venv
+
+
[email protected]("installed", ["custom"], indirect=True)
[email protected]("answer, published", [("y", True), ("n", False)])
+def test_interactive_update_asks_before_installing_new_python_dependencies(
+ installed, monkeypatch, answer, published):
+ """A terminal user is asked the same question install asks; yes publishes code AND the
+ dependency together, no leaves both untouched."""
+ import shutil
+ from types import SimpleNamespace
+ from hermes_cli import plugins_cmd
+ from hermes_cli.plugins_transaction import update_plugin
+ from pm.environments import selected_venv
+
+ root, home, repo, target, state = installed
+ old_head, old_venv = _head(target), selected_venv(root / "core")
+ state["sha"] = _version(repo, "2.0.0", libraries=("shared-library", "second-library"))
+ shutil.copytree(repo.parent / "second-library", target.parent / "second-library", dirs_exist_ok=True)
+ monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: True))
+ monkeypatch.setattr("sys.stdout", SimpleNamespace(isatty=lambda: True, write=lambda *a: None, flush=lambda: None))
+ asked: list = []
+ monkeypatch.setattr("builtins.input", lambda prompt="": asked.append(prompt) or answer)
+
+ if published:
+ update_plugin(target, interactive=True)
+ else:
+ with pytest.raises(plugins_cmd.PluginOperationError, match="declined"):
+ update_plugin(target, interactive=True)
+
+ assert asked, "no dependency consent prompt was shown"
+ assert (_head(target) == state["sha"]) is published
+ assert (selected_venv(root / "core") != old_venv) is published
+ assert (_head(target) != old_head) is published
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
+def test_update_rebuilds_an_accepted_node_sidecar_when_its_manifest_moves(installed, monkeypatch):
+ """Publication swaps the whole tree, so a node_modules the user accepted at install would
+ come back stale (custom pull copies it) or missing (catalog re-clone). When package.json
+ changes, the sidecar is rebuilt in the staged copy and published with the code."""
+ from hermes_cli import plugins_cmd
+ from pm import workspace
+
+ root, home, repo, target, state = installed
+ (repo / "package.json").write_text('{"name": "transactional", "dependencies": {}}', encoding="utf-8")
+ _commit(repo, "add node sidecar")
+ # the user accepted the sidecar at install time
+ (target / "node_modules").mkdir()
+ (target / "node_modules" / "stale").write_text("v1", encoding="utf-8")
+ (repo / "package.json").write_text('{"name": "transactional", "dependencies": {"left-pad": "*"}}', encoding="utf-8")
+ state["sha"] = _commit(repo, "bump node deps")
+ rebuilt: list = []
+
+ def fake_npm(plugin_dir, *, explicit=False):
+ rebuilt.append(plugin_dir)
+ (plugin_dir / "node_modules").mkdir(exist_ok=True)
+ (plugin_dir / "node_modules" / "fresh").write_text("v2", encoding="utf-8")
+ return None
+
+ monkeypatch.setattr(workspace, "install_node_sidecar", fake_npm)
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+
+ assert result["ok"] is True, result
+ assert len(rebuilt) == 1 and rebuilt[0] != target, "npm must run in the staged copy, not the live tree"
+ assert (target / "node_modules" / "fresh").is_file()
+ assert _head(target) == state["sha"]
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
[email protected]("failure", ["dependencies", "version", "publication", "manifest"])
+def test_failed_update_keeps_code_metadata_config_and_environment(installed, monkeypatch, failure):
+ from hermes_cli import plugins_cmd
+ from pm.environments import selected_venv
+ from pm import paths
+ from pm.lock import Facts
+
+ root, home, repo, target, state = installed
+ selected = selected_venv(root / "core")
+ watched = [target / "plugin.yaml", target / "__init__.py", target / "pyproject.toml",
+ home / "config.yaml", home / "plugins/.install-metadata.json", paths.runtime_facts_path()]
+
+ before = {path: path.read_bytes() for path in watched}
+ old_head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip()
+ state["sha"] = _version(repo, "2.0.0", broken=failure == "dependencies",
+ minimum=">=999.0.0" if failure == "version" else "")
+ if failure == "manifest":
+ (repo / "plugin.yaml").write_text("name: [broken", encoding="utf-8")
+ state["sha"] = _commit(repo, "invalid manifest")
+ if failure == "publication":
+ def deny(*args, **kwargs):
+ raise OSError("fixture refuses environment publication")
+ monkeypatch.setattr(Facts, "record_state", deny)
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+ assert result["ok"] is False, result
+ assert result.get("error")
+ assert selected_venv(root / "core") == selected
+ assert {path: path.read_bytes() for path in watched} == before
+ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == old_head
+
+
[email protected]("installed", ["catalog", "custom"], indirect=True)
+def test_successful_update_publishes_matching_code_and_durable_workspace(installed):
+ import tomllib
+ from hermes_cli import plugins_cmd
+ from pm.environments import selected_venv
+ from pm import paths
+ from pm.lock import Facts
+ from pm.packages import Venv
+
+ root, home, repo, target, state = installed
+ before = selected_venv(root / "core")
+ config = (home / "config.yaml").read_bytes()
+ state["sha"] = _version(repo, "2.0.0")
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+ assert result["ok"] is True, result
+ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() == state["sha"]
+ assert 'VERSION = \'2.0.0\'' in (target / "__init__.py").read_text(encoding="utf-8")
+ assert (home / "config.yaml").read_bytes() == config
+ fact = Facts(paths.runtime_facts_path()).get("venv")
+ assert selected_venv(root / "core") != before
+ assert fact["stamp"] == Venv().expected_stamp(fact["extras"])
+ workspace = Path(fact["resolved_lock"]).parent
+ document = tomllib.loads((workspace / "pyproject.toml").read_text(encoding="utf-8"))
+ members = document["tool"]["uv"]["workspace"]["members"]
+ assert members
+ for member in members:
+ path = (workspace / member).resolve()
+ assert path.is_relative_to(workspace)
+ assert (path / "pyproject.toml").is_file()
+ record = json.loads((home / "plugins/.install-metadata.json").read_text(encoding="utf-8"))["transactional"]
+ assert record["revision"] == state["sha"]
+
+ # A packaged member's source changes even when its dependency metadata does not.
+ previous_stamp = fact["stamp"]
+ (repo / "__init__.py").write_text("VERSION = 'code-only'\ndef register(ctx):\n pass\n", encoding="utf-8")
+ state["sha"] = _commit(repo, "code-only update")
+ result = plugins_cmd.dashboard_update_user_plugin("transactional")
+ assert result["ok"], result
+ record = json.loads((home / "plugins/.install-metadata.json").read_text(encoding="utf-8"))["transactional"]
+ assert Facts(paths.runtime_facts_path()).get("venv")["stamp"] != previous_stamp
+
+ from hermes_cli.plugins_updates import run_checks
+
+ def no_network(*args):
+ raise AssertionError("catalog pin must not consult a custom update source")
+
- if record.get("catalog_name"):
++ if (record.get("catalog") or {}).get("name"):
+ state["sha"] = _version(repo, "3.0.0")
+ check = next(row for row in run_checks(home / "plugins", include_pip=False,
+ fetch=no_network, ls_remote=no_network)
+ if row.name == "transactional")
+ assert check.klass == "catalog" and check.update_available is True
+ assert check.current == record["revision"] and check.latest == state["sha"]
diff --cc tests/hermes_cli/test_plugins_cmd_catalog.py
index 9dbd109a056,1c3436566cd..b49e77913e8
--- a/tests/hermes_cli/test_plugins_cmd_catalog.py
+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py
@@@ -113,3 -111,83 +113,83 @@@ def test_owner_repo_hash_subdir_shortha
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"})
++ pc._write_config_value("plugins", "enabled", ["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 --cc tests/hermes_cli/test_web_plugins_catalog.py
index 79733b08586,b0bd0e85271..12d32fbfbd5
--- a/tests/hermes_cli/test_web_plugins_catalog.py
+++ b/tests/hermes_cli/test_web_plugins_catalog.py
@@@ -1,12 -1,12 +1,10 @@@
--"""Dashboard plugin-catalog surface: GET /api/dashboard/plugins/catalog merges installed state (via the
- shared install record) and the install endpoint has NO kill-list bypass."""
-install-metadata ``catalog`` record) and the install endpoint has NO kill-list bypass."""
++"""Dashboard plugin-catalog surface: GET /api/dashboard/plugins/catalog merges installed state via the
++installer-owned install-metadata ``catalog`` record; the install endpoint has no kill-list bypass."""
from __future__ import annotations
--import json
--
import pytest
-import yaml
+import hermes_yaml as yaml
from hermes_cli import plugin_catalog as pc_cat
diff --cc website/docs/reference/cli-commands.md
index bcbc63e6382,48fe123aae0..8993132cd05
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@@ -1626,9 -1622,9 +1626,9 @@@ Unified plugin management — general p
| 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 select the reviewed 40-hex commit SHA. Source, revision, and catalog membership share `plugins/.install-metadata.json`. An explicit different `--ref` selects a custom pin. `--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. |
++| `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 reviewed 40-hex commit SHA and show declared capabilities. Source, checked-out revision, and a nested catalog-provenance block are recorded in the installer's `plugins/.install-metadata.json`; the `.hermes-catalog.json` copy inside the plugin directory is only for convenience and is never trusted. Raw URLs are flagged as custom (unreviewed) sources. `--ref` selects a full-SHA custom pin and records the SHA actually checked out. `--allow-removed` (DANGEROUS) bypasses the removed-plugin blocklist at install and exempts that install from update, enable, and 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. |
+| `update <name>` | Re-pin catalog installs to the reviewed catalog SHA, or update a custom Git install from its recorded source/feed. PM validates active-plugin dependencies before code publication. Explicit custom pins move only with `install --force --ref <new-commit>`. |
| `remove <name>` (aliases: `rm`, `uninstall`) | Remove an installed plugin. |
| `enable <name>` | Enable a disabled plugin. |
| `disable <name>` | Disable a plugin without removing it. |
diff --cc website/docs/user-guide/features/plugin-catalog.md
index 99bcd53de8e,ee127c22876..80aa2df98d7
--- a/website/docs/user-guide/features/plugin-catalog.md
+++ b/website/docs/user-guide/features/plugin-catalog.md
@@@ -134,16 -145,21 +145,27 @@@ hermes plugins enable sny
`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), prepares the new SHA before publication. Your
- enabled/disabled state is preserved. `hermes plugins list` shows catalog
-catalog moved (via a reviewed PR), force-reinstalls at the new SHA. Your
++catalog moved (via a reviewed PR), prepares and dependency-validates the new SHA
++before publishing it. Your
+ 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.
+PM validates the dependencies of an active plugin before its new code replaces
+the installed version. A version, scan, dependency, or publication failure keeps
+the working code and dependency selection. Disabled plugins stay disabled.
- Catalog membership, installed revision, and source share the profile's
- `plugins/.install-metadata.json` record. Custom Git plugins retain their recorded
- Git/feed update policy but use the same PM validation and publication path.
+ 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.
++Custom Git plugins retain their recorded Git/feed update policy but use the same
++PM validation and publication path.
### Names not in the catalog