The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): provenance 2x2 reconciliation + adopt + trust-update-url
ethernet8120429a914d
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 99c847ce397..68821142547 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -919,6 +919,17 @@ def _install_plugin_core("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.+ try:+ manifest = _read_manifest(Path(tmp_target))+ update_url = (manifest or {}).get("update_url")+ if isinstance(update_url, str) and update_url.strip():+ new_metadata[plugin_name]["update_url"] = update_url.strip()+ except Exception:+ passbackup = Path(tmp) / "previous-plugin"replaced_existing = target.exists()if replaced_existing:@@ -2036,6 +2047,108 @@ def _filter_plugin_entries(entries: list, args: Any, enabled: set, disabled: setreturn filtered+def cmd_adopt(name: str) -> None:+ """Adopt a self-cloned plugin dir into the provenance sidecar.++ Reads the dir's git origin URL, validates it, writes the sidecar row+ — from then on a normal git install (check-updates + update). The+ ONLY mutation path for self-cloned dirs (settled: explicit verbs).+ """+ from rich.console import Console++ console = Console()+ plugins_dir = _plugins_dir()+ target = _require_installed_plugin(name, plugins_dir, console)++ from hermes_cli.plugins_provenance import ProvenanceClass, plugins_provenance++ prov = next((p for p in plugins_provenance(plugins_dir) if p.name == target.name), None)+ if prov is None:+ console.print(f"[red]Error:[/red] Plugin '{name}' not classifiable.")+ sys.exit(1)+ if prov.klass is not ProvenanceClass.SELF_CLONED:+ console.print(+ f"[red]Error:[/red] Plugin '{name}' is {prov.klass.value}, not "+ "self-cloned — there is nothing to adopt."+ )+ sys.exit(1)+ if not prov.origin_url:+ console.print(+ f"[red]Error:[/red] Plugin '{name}' has no readable git origin "+ "remote. Add one (git remote add origin <url>) and retry."+ )+ sys.exit(1)++ try:+ _resolve_git_url(prov.origin_url)+ except ValueError as e:+ console.print(f"[red]Error:[/red] The dir's origin url is not installable: {e}")+ sys.exit(1)++ metadata = _read_install_metadata()+ if target.name in metadata:+ console.print(f"[red]Error:[/red] Plugin '{name}' already has a provenance row.")+ sys.exit(1)++ git_exe = _resolve_git_executable()+ revision = _git_head_revision(target, git_exe) if git_exe else ""+ metadata[target.name] = {+ "pinned": False,+ "revision": revision,+ "source": _canonical_source(prov.origin_url, None),+ }+ _write_install_metadata(metadata)+ console.print(+ f"[green]✓[/green] Adopted [bold]{name}[/bold] "+ f"(source: {prov.origin_url}, revision: {revision[:12] or 'unknown'}). "+ "It is now a tracked git install."+ )+++def cmd_trust_update_url(name: str) -> None:+ """The ONLY path that moves a saved update_url tag.++ A needs-fixing mismatch (manifest update_url vs the saved tag) is+ resolved here: confirms the manifest's url into the sidecar row,+ prints old → new. Refuses when there is nothing to trust.+ """+ from rich.console import Console++ console = Console()+ plugins_dir = _plugins_dir()+ target = _require_installed_plugin(name, plugins_dir, console)++ from hermes_cli.plugins_provenance import plugins_provenance, read_sidecar_rows++ rows = read_sidecar_rows(plugins_dir)+ row = rows.get(target.name)+ if not isinstance(row, dict):+ console.print(+ f"[red]Error:[/red] Plugin '{name}' has no provenance row — "+ "nothing to trust. Reinstall it instead."+ )+ sys.exit(1)++ saved = row.get("update_url") or None+ manifest = _read_manifest(target)+ claimed = (manifest or {}).get("update_url") or None+ if claimed == saved:+ console.print(+ f"[yellow]Nothing to trust:[/yellow] '{name}' has no "+ "update_url mismatch."+ )+ return++ row["update_url"] = claimed+ rows[target.name] = row+ _write_install_metadata(rows)+ console.print(+ f"[green]✓[/green] Trusted [bold]{name}[/bold] update_url:\n"+ f" old: {saved or '(none)'}\n"+ f" new: {claimed or '(none)'}"+ )++def cmd_list(args: Any | None = None) -> None:"""List all plugins (bundled + user) with enabled/disabled state."""from rich.console import Console@@ -2083,6 +2196,13 @@ def cmd_list(args: Any | None = None) -> None:table.add_column("Description")table.add_column("Source", style="dim")+ # provenance class per user-installed dir (bundled entries show '-')+ from hermes_cli.plugins_provenance import plugins_provenance++ prov_classes = {+ p.name: p.klass.value for p in plugins_provenance(_plugins_dir())+ }+for name, version, description, source, _dir, key in entries:status_name = _plugin_status(name, enabled, disabled, key=key)if status_name == "disabled":@@ -2092,6 +2212,13 @@ def cmd_list(args: Any | None = None) -> None:else:status = "[yellow]not enabled[/yellow]"table.add_row(name, status, str(version), description, source)+ # class line rides the Source column for user plugins+ if source in {"user", "git"}:+ klass = prov_classes.get(name)+ if klass and klass != "git":+ table.add_row(+ "", "", "", f"[dim]provenance: {klass}[/dim]", ""+ )console.print()console.print(table)@@ -3230,6 +3357,10 @@ def plugins_command(args) -> None:)elif action == "update":cmd_update(args.name)+ elif action == "adopt":+ cmd_adopt(args.name)+ elif action == "trust-update-url":+ cmd_trust_update_url(args.name)elif action in {"remove", "rm", "uninstall"}:cmd_remove(args.name)elif action == "enable":diff --git a/hermes_cli/plugins_provenance.py b/hermes_cli/plugins_provenance.pynew file mode 100644index 00000000000..385114082c0--- /dev/null+++ b/hermes_cli/plugins_provenance.py@@ -0,0 +1,137 @@+"""Plugin provenance: the 2x2 reconciliation of install metadata.++Row-presence says "hermes installed this" (the .install-metadata.json+sidecar); ``.git``-presence cross-checks it. The reconciliation IS the+disambiguation — ``source`` alone does not distinguish a git install+from a manual copy (settled 2026-09-03, plugin-auto-update plan):++ row+git = git install — updatable via the recorded source+ neither = manual drop — not auto-updatable, listed as such+ git only = self-cloned — adoptable; origin URL carried ready+ row only = provenance drift — flagged with a reinstall remedy++Pure functions over (plugins_dir, sidecar rows) — no globals, no+network, fully testable. The sidecar remains the single authority for+what *hermes* installed; this module only reads it.+"""++from __future__ import annotations++import json+import subprocess+from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import Optional+++class ProvenanceClass(Enum):+ GIT = "git"+ MANUAL = "manual"+ SELF_CLONED = "self-cloned"+ DRIFT = "drift"+++@dataclass+class Provenance:+ name: str+ klass: ProvenanceClass+ path: Path+ row: Optional[dict] = None # the sidecar row, when present+ origin_url: Optional[str] = None # self-cloned: the .git remote+ saved_update_url: Optional[str] = None # the row's saved feed tag+++def read_sidecar_rows(plugins_dir: Path) -> dict:+ """The install-metadata rows for this plugins dir; {} when absent+ or unreadable (manual-only installs never wrote one)."""+ sidecar = plugins_dir / ".install-metadata.json"+ if not sidecar.is_file():+ return {}+ try:+ data = json.loads(sidecar.read_text(encoding="utf-8-sig"))+ except (OSError, json.JSONDecodeError):+ return {}+ return data if isinstance(data, dict) else {}+++def _git_origin_url(plugin_dir: Path) -> Optional[str]:+ """origin's URL from the installed .git — remote get-url on a real+ repo, config-file parse as the fallback (works for partial/copy+ installs where git refuses)."""+ # fast path: real git repo+ try:+ proc = subprocess.run(+ ["git", "-C", str(plugin_dir), "remote", "get-url", "origin"],+ capture_output=True,+ text=True,+ timeout=10,+ )+ if proc.returncode == 0:+ url = (proc.stdout or "").strip()+ if url:+ return url+ except (OSError, subprocess.TimeoutExpired):+ pass+ # fallback: parse .git/config directly (a .git dir with a config+ # file is all the adopt path needs)+ config = plugin_dir / ".git" / "config"+ if not config.is_file():+ return None+ try:+ text = config.read_text(encoding="utf-8-sig")+ except OSError:+ return None+ in_origin = False+ for line in text.splitlines():+ stripped = line.strip()+ if stripped == '[remote "origin"]':+ in_origin = True+ continue+ if stripped.startswith("["):+ in_origin = False+ continue+ if in_origin and stripped.startswith("url"):+ _, _, value = stripped.partition("=")+ url = value.strip()+ return url or None+ return None+++def plugins_provenance(plugins_dir: Path) -> list[Provenance]:+ """Classify every plugin dir under plugins_dir per the 2x2."""+ rows = read_sidecar_rows(plugins_dir)+ out: list[Provenance] = []+ if not plugins_dir.is_dir():+ return out+ try:+ entries = sorted(plugins_dir.iterdir(), key=lambda p: p.name)+ except OSError:+ return out+ for plugin_dir in entries:+ if not plugin_dir.is_dir() or plugin_dir.name.startswith("."):+ continue+ has_git = (plugin_dir / ".git").exists()+ row = rows.get(plugin_dir.name)+ row = row if isinstance(row, dict) else None++ if row and has_git:+ klass = ProvenanceClass.GIT+ elif row and not has_git:+ klass = ProvenanceClass.DRIFT+ elif has_git and not row:+ klass = ProvenanceClass.SELF_CLONED+ else:+ klass = ProvenanceClass.MANUAL++ out.append(+ Provenance(+ name=plugin_dir.name,+ klass=klass,+ path=plugin_dir,+ row=row,+ origin_url=_git_origin_url(plugin_dir) if klass is ProvenanceClass.SELF_CLONED else None,+ saved_update_url=(row or {}).get("update_url") or None,+ )+ )+ return out\ No newline at end of filediff --git a/hermes_cli/subcommands/plugins.py b/hermes_cli/subcommands/plugins.pyindex 975770c2fd5..db1da018e83 100644--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@ -86,6 +86,29 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:)plugins_update.add_argument("name", help="Plugin name to update")+ plugins_adopt = plugins_subparsers.add_parser(+ "adopt",+ help="Adopt a self-cloned plugin dir into provenance tracking",+ description=(+ "For plugin dirs you cloned yourself (no install record): read "+ "the git origin URL, write the provenance row, and become a "+ "tracked git install (check-updates + update)."+ ),+ )+ plugins_adopt.add_argument("name", help="Self-cloned plugin directory name")++ plugins_trust = plugins_subparsers.add_parser(+ "trust-update-url",+ help="Confirm a changed plugin update_url into the saved tag",+ description=(+ "The ONLY path that moves a saved update_url tag. When a "+ "plugin's manifest changed its update_url (needs-fixing "+ "mismatch), running this trusts the new url after review. "+ "Never triggered automatically."+ ),+ )+ plugins_trust.add_argument("name", help="Plugin name")+plugins_remove = plugins_subparsers.add_parser("remove", aliases=["rm", "uninstall"], help="Remove an installed plugin")diff --git a/tests/hermes_cli/test_plugins_provenance.py b/tests/hermes_cli/test_plugins_provenance.pynew file mode 100644index 00000000000..ac50b4145b8--- /dev/null+++ b/tests/hermes_cli/test_plugins_provenance.py@@ -0,0 +1,100 @@+"""Tests: plugin provenance reconciliation — the 2x2.++Row-presence says "hermes installed this"; `.git`-presence cross-checks+it. The reconciliation IS the disambiguation (settled 2026-09-03,+plugin-auto-update plan Task 1):+ row+git = git install (updatable via the recorded source)+ neither = manual drop (not auto-updatable, listed as such)+ git only = self-cloned (adoptable: origin URL ready)+ row only = provenance drift (flagged with a reinstall remedy)+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from hermes_cli.plugins_provenance import (+ Provenance,+ ProvenanceClass,+ plugins_provenance,+)+++def _write_sidecar(home: Path, rows: dict) -> None:+ plugins = home / "plugins"+ plugins.mkdir(parents=True, exist_ok=True)+ (plugins / ".install-metadata.json").write_text(+ json.dumps(rows, indent=2), encoding="utf-8"+ )+++def _fake_git_dir(plugin_dir: Path, origin_url: str = "https://example/o/r") -> None:+ plugin_dir.mkdir(parents=True, exist_ok=True)+ git = plugin_dir / ".git"+ git.mkdir()+ # a real-enough git dir: remote config the adopt path reads+ (git / "config").write_text(+ f'[remote "origin"]\n\turl = {origin_url}\n', encoding="utf-8"+ )+++def _manual_dir(plugin_dir: Path) -> None:+ plugin_dir.mkdir(parents=True, exist_ok=True)+ (plugin_dir / "plugin.yaml").write_text("name: x\n", encoding="utf-8")+++def test_git_install_row_and_git(tmp_path):+ _write_sidecar(tmp_path, {"plug": {"pinned": False, "revision": "a" * 40, "source": "https://example/o/r"}})+ _fake_git_dir(tmp_path / "plugins" / "plug")+ prov = plugins_provenance(tmp_path / "plugins")+ assert len(prov) == 1+ assert prov[0].klass is ProvenanceClass.GIT+ assert prov[0].row is not None and prov[0].row["revision"] == "a" * 40+++def test_manual_drop_neither(tmp_path):+ _write_sidecar(tmp_path, {})+ _manual_dir(tmp_path / "plugins" / "handmade")+ prov = plugins_provenance(tmp_path / "plugins")+ assert prov[0].klass is ProvenanceClass.MANUAL+++def test_self_cloned_git_without_row(tmp_path):+ _write_sidecar(tmp_path, {})+ _fake_git_dir(tmp_path / "plugins" / "selfcloned", "https://example/m/r")+ prov = plugins_provenance(tmp_path / "plugins")+ assert prov[0].klass is ProvenanceClass.SELF_CLONED+ assert prov[0].origin_url == "https://example/m/r"+++def test_drift_row_without_git(tmp_path):+ _write_sidecar(tmp_path, {"ghost": {"pinned": False, "revision": "b" * 40, "source": "https://example/g/r"}})+ _manual_dir(tmp_path / "plugins" / "ghost")+ prov = plugins_provenance(tmp_path / "plugins")+ assert prov[0].klass is ProvenanceClass.DRIFT+ assert prov[0].row["source"] == "https://example/g/r"+++def test_missing_sidecar_is_all_manual_or_selfcloned(tmp_path):+ # no sidecar at all: everything classifies from the dir alone+ _fake_git_dir(tmp_path / "plugins" / "cloned")+ _manual_dir(tmp_path / "plugins" / "dropped")+ prov = plugins_provenance(tmp_path / "plugins")+ classes = {p.name: p.klass for p in prov}+ assert classes["cloned"] is ProvenanceClass.SELF_CLONED+ assert classes["dropped"] is ProvenanceClass.MANUAL+++def test_update_url_tag_round_trips(tmp_path):+ # a saved update_url tag rides the row; the manifest is claims+ _write_sidecar(+ tmp_path,+ {"plug": {"pinned": False, "revision": "c" * 40, "source": "https://example/o/r",+ "update_url": "https://example/feed.yml"}},+ )+ _fake_git_dir(tmp_path / "plugins" / "plug")+ prov = plugins_provenance(tmp_path / "plugins")+ assert prov[0].saved_update_url == "https://example/feed.yml"\ No newline at end of file