The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: live plugin-catalog cache never outranks a newer in-tree pin, expires after 24h, is written atomically
teknium1958188f3cae7
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.pyindex 645efa76775..6a0d15a4cf1 100644--- a/hermes_cli/plugin_catalog.py+++ b/hermes_cli/plugin_catalog.py@@ -32,6 +32,9 @@ CATALOG_TIERS = ("official", "community")CATALOG_CATEGORIES = ("desktop", "memory", "platform", "web", "tools", "voice", "automation", "models", "general")LIVE_CATALOG_URL = "https://hermes-agent.nousresearch.com/docs/api/plugin-catalog.json"LIVE_CATALOG_TTL_SECONDS = 6 * 60 * 60+# Past this age an offline cache no longer supplies PINS (the in-tree catalog does); its removals+# still count — a kill-list entry never expires.+LIVE_CATALOG_MAX_STALE_SECONDS = 24 * 60 * 60LIVE_CATALOG_FAILURE_TTL_SECONDS = 60.0_REQUEST_TIMEOUT = 5.0_MAX_LIVE_BYTES = 2 * 1024 * 1024@@ -310,9 +313,17 @@ _live_fetch_failed_until = 0.0def _stale_live_cache(cache: Path) -> Optional[Dict[str, Any]]:- """A previously fetched copy still beats the in-tree one when the network is down."""+ """A previously fetched copy still beats the in-tree one when the network is down — for+ :data:`LIVE_CATALOG_MAX_STALE_SECONDS`. Past that its pins may trail the checkout's own catalog+ (a 90-day-old cache outranked a freshly updated in-tree pin), so the entries are dropped and the+ caller falls back to in-tree; the removals are kept."""try:- return json.loads(cache.read_text(encoding="utf-8")) if cache.is_file() else None+ if not cache.is_file():+ return None+ data = json.loads(cache.read_text(encoding="utf-8"))+ if time.time() - cache.stat().st_mtime > LIVE_CATALOG_MAX_STALE_SECONDS:+ data = {**data, "entries": []}+ return dataexcept Exception:return None@@ -335,6 +346,7 @@ def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:try:import httpxfrom hermes_constants import mkdir_under_hermes_home+ from utils import atomic_write_textresp = httpx.get(LIVE_CATALOG_URL, timeout=_REQUEST_TIMEOUT, follow_redirects=True)resp.raise_for_status()@@ -344,7 +356,9 @@ def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:if not isinstance(data, dict) or not isinstance(data.get("entries"), list):raise ValueError("unexpected live catalog payload")mkdir_under_hermes_home(cache.parent)- cache.write_text(json.dumps(data), encoding="utf-8")+ # Atomic: a concurrent reader (gateway, TUI, a second CLI) must never see a half-written+ # document, which would read as a fetch failure and start its own 60 s failure window.+ atomic_write_text(cache, json.dumps(data), tmp_prefix=f"{cache.name}.tmp-")return dataexcept Exception as exc:logger.debug("Plugin catalog: live fetch failed: %s", exc)@@ -352,15 +366,76 @@ def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:return _stale_live_cache(cache)+_in_tree_catalog_time: Optional[float] = -1.0 # -1 = not resolved yet; None = no git checkout+++def in_tree_catalog_time() -> Optional[float]:+ """Commit time (epoch) of the last change to this checkout's ``plugin-catalog/``, or ``None`` when+ the install is not a git checkout (a release/pip install cannot be newer than the published doc).+ Resolved once per process."""+ global _in_tree_catalog_time+ if _in_tree_catalog_time != -1.0:+ return _in_tree_catalog_time+ root = get_catalog_dir().parent+ resolved: Optional[float] = None+ if (root / ".git").exists():+ try:+ import subprocess+ out = subprocess.run(["git", "-C", str(root), "log", "-1", "--format=%ct", "--", "plugin-catalog"],+ capture_output=True, text=True, timeout=10, stdin=subprocess.DEVNULL)+ resolved = float(out.stdout.strip()) if out.returncode == 0 and out.stdout.strip() else None+ except Exception as exc:+ logger.debug("Plugin catalog: could not date the in-tree catalog: %s", exc)+ _in_tree_catalog_time = resolved+ return resolved+++def _live_generated_time(data: Dict[str, Any]) -> Optional[float]:+ raw = data.get("generated_at")+ if not isinstance(raw, str) or not raw:+ return None+ try:+ from datetime import datetime, timezone+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))+ return (parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)).timestamp()+ except ValueError:+ return None+++def _prefer_in_tree_entry(tree: PluginCatalogEntry, live: PluginCatalogEntry, tree_is_newer: Optional[bool]) -> bool:+ """For one entry present in both sources with a different pin: the newer catalog wins. Newer is+ decided by the checkout's catalog commit time vs the doc's ``generated_at`` when both resolve;+ otherwise by the entries' ``version`` labels when both parse; otherwise the live doc wins (a release+ install's in-tree copy is frozen at release time)."""+ if tree.sha == live.sha:+ return False+ if tree_is_newer is not None:+ return tree_is_newer+ if tree.version and live.version:+ try:+ from packaging.version import Version+ return Version(tree.version) > Version(live.version)+ except Exception:+ return False+ return False++def load_catalog_live() -> List[PluginCatalogEntry]:- """Entries from the live (or cached) catalog, else the in-tree catalog."""+ """Entries from the live (or cached) catalog, else the in-tree catalog. When both name an entry at+ different pins the NEWER source supplies it — right after ``hermes update`` bumps an in-tree pin,+ a cache fetched before the bump must not re-install the old one (see :func:`_prefer_in_tree_entry`)."""data = fetch_live_catalog()- if data is not None:- entries = [e for i, raw in enumerate(data["entries"])- if (e := entry_from_mapping(raw, f"{LIVE_CATALOG_URL}#{i}")) is not None]- if entries:- return entries- return load_catalog()+ if data is None:+ return load_catalog()+ entries = [e for i, raw in enumerate(data["entries"])+ if (e := entry_from_mapping(raw, f"{LIVE_CATALOG_URL}#{i}")) is not None]+ if not entries:+ return load_catalog()+ in_tree = {e.name: e for e in load_catalog()}+ live_t, tree_t = _live_generated_time(data), in_tree_catalog_time()+ tree_is_newer = (tree_t > live_t) if (live_t is not None and tree_t is not None) else None+ return [in_tree[e.name] if e.name in in_tree and _prefer_in_tree_entry(in_tree[e.name], e, tree_is_newer) else e+ for e in entries]def live_removed_list() -> List[RemovedEntry]:diff --git a/tests/hermes_cli/test_plugin_catalog.py b/tests/hermes_cli/test_plugin_catalog.pyindex 7856a428354..df806958b80 100644--- a/tests/hermes_cli/test_plugin_catalog.py+++ b/tests/hermes_cli/test_plugin_catalog.py@@ -101,3 +101,69 @@ def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkey"removed": [{"name": "pulled-live", "reason": "cve"}]}))assert [e.name for e in pc.load_catalog_live()] == ["live-only"]assert pc.find_removed("pulled-live").reason == "cve"+++def _fresh_cache(tmp_path, monkeypatch, doc: dict):+ cache = tmp_path / "cache" / "plugin-catalog.json"+ cache.parent.mkdir(parents=True, exist_ok=True)+ cache.write_text(json.dumps(doc))+ monkeypatch.setattr(pc, "_live_cache_path", lambda: cache)+ monkeypatch.setattr(pc, "LIVE_CATALOG_URL", "http://127.0.0.1:9/nope") # never reached / unreachable+ return cache+++def test_newer_in_tree_pin_outranks_a_fresh_live_cache(tmp_path, monkeypatch):+ """Right after `hermes update` bumps an in-tree pin, a live cache fetched BEFORE the bump must not+ re-install the old sha: for the same entry the newer catalog wins (checkout catalog commit time vs+ the doc's generated_at). Live-only entries survive; an older checkout still defers to the doc."""+ old, new = SHA, "a" * 40+ _fresh_cache(tmp_path, monkeypatch, {"generated_at": "2026-09-22T10:00:00Z",+ "entries": [_entry("shared", sha=old), _entry("live-only")], "removed": []})+ monkeypatch.setattr(pc, "load_catalog", lambda catalog_dir=None: [pc.entry_from_mapping(_entry("shared", sha=new), "t")])+ bump_time = pc._live_generated_time({"generated_at": "2026-09-22T10:00:00Z"}) + 3600+ monkeypatch.setattr(pc, "in_tree_catalog_time", lambda: bump_time)+ by_name = {e.name: e for e in pc.load_catalog_live()}+ assert by_name["shared"].sha == new and "live-only" in by_name+ # Control: a checkout whose catalog predates the doc takes the live pin.+ monkeypatch.setattr(pc, "in_tree_catalog_time", lambda: bump_time - 7200)+ assert {e.name: e.sha for e in pc.load_catalog_live()}["shared"] == old+++def test_live_cache_past_max_stale_age_stops_supplying_pins_but_keeps_removals(tmp_path, monkeypatch):+ """Offline for days: a 25-hour-old cache no longer outranks the in-tree catalog (its pins may be+ older than the checkout's), while its kill-list entries still block."""+ import os+ import time+ cache = _fresh_cache(tmp_path, monkeypatch, {"entries": [_entry("live-only")],+ "removed": [{"name": "pulled-live", "reason": "cve"}]})+ stale = time.time() - pc.LIVE_CATALOG_MAX_STALE_SECONDS - 3600+ os.utime(cache, (stale, stale))+ pc._live_fetch_failed_until = 0.0+ assert [e.name for e in pc.load_catalog_live()] == [e.name for e in pc.load_catalog()]+ assert pc.find_removed("pulled-live").reason == "cve"+ assert pc.cached_removed_entries()[-1].name == "pulled-live"+++def test_live_cache_write_never_truncates_the_previous_copy(tmp_path, monkeypatch):+ """The cache is replaced atomically: a reader racing the writer (or a write that dies half-way)+ sees the whole previous document, never a truncated one."""+ cache = _fresh_cache(tmp_path, monkeypatch, {"entries": [_entry("previous")], "removed": []})+ previous = cache.read_text()++ class _Resp:+ content = json.dumps({"entries": [_entry("fresh")], "removed": []}).encode()+ def raise_for_status(self): pass+ def json(self): return json.loads(self.content)++ import httpx+ import utils+ monkeypatch.setattr(httpx, "get", lambda *a, **k: _Resp())+ pc._live_fetch_failed_until = 0.0++ def _dies(*_a, **_k):+ raise OSError("disk full")++ monkeypatch.setattr(utils, "atomic_replace", _dies)+ pc.fetch_live_catalog(force=True) # the failed write is swallowed like any other fetch failure+ assert cache.read_text() == previous+ assert not list(cache.parent.glob("*.tmp*")) # no leftover temp file eitherdiff --git a/website/docs/user-guide/features/plugin-catalog.md b/website/docs/user-guide/features/plugin-catalog.mdindex ee127c22876..7734c442692 100644--- a/website/docs/user-guide/features/plugin-catalog.md+++ b/website/docs/user-guide/features/plugin-catalog.md@@ -173,10 +173,15 @@ The docs build publishes the catalog as one JSON document(`https://hermes-agent.nousresearch.com/docs/api/plugin-catalog.json`).`search`/`install`/`update` fetch it at most every six hours and cache it under`~/.hermes/cache/`, so new entries and removals reach installed clients without-updating Hermes. Offline, the copy shipped with your checkout is used (a failed-fetch is remembered for a minute, so `plugins list` and the dashboard's Plugins-page pay at most one connection timeout, not one per installed plugin). Removals-from the in-tree list and the live list are always both enforced.+updating Hermes. Offline, the cached copy is used for up to 24 hours, then the+copy shipped with your checkout takes over (a failed fetch is remembered for a+minute, so `plugins list` and the dashboard's Plugins page pay at most one+connection timeout, not one per installed plugin). When the cached document and+your checkout disagree on an entry's pin, the newer of the two wins — a git+checkout whose catalog was committed after the document was published (a fresh+`hermes update`) installs its own pin, never the cached older one. Removals+from the in-tree list and the live list are always both enforced, whatever the+cache's age.### Custom git URLs are different