Skip to content

The agent that grows with you

feat(plugins): update-check cadence — clock-gated, receipt-surfaced, apply-explicit

ethernet22e5a9d11a31
diff --git a/gateway/run.py b/gateway/run.py
index b5ca054079a..f74f8745a6a 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -33614,6 +33614,52 @@ def main():
pm.activate()
except Exception:
logger.debug("pm startup check failed", exc_info=True)
+
+ # Plugin update-check cadence (read-only, receipt-surfaced): one
+ # background thread at boot; the clock gate makes it a no-op until
+ # plugins.auto_update_check_hours (default 24h) elapses. Never
+ # blocks boot, never installs — apply stays explicit
+ # (plugins.auto_apply opt-in, git rows only, scan-gated).
+ def _kick_plugin_check_cadence() -> None:
+ try:
+ from hermes_cli.plugins_cadence import run_scheduled_check
+ from hermes_cli.plugins_cmd import _plugins_dir
+ from hermes_cli.plugins_updates import run_checks as _run_checks
+
+ run_scheduled_check(
+ run_checks_fn=lambda plugins_dir: _run_checks(
+ plugins_dir,
+ fetch=_cadence_fetch,
+ ls_remote=_cadence_ls_remote,
+ ),
+ plugins_dir=_plugins_dir(),
+ )
+ except Exception:
+ logger.debug("plugin update-check cadence failed", exc_info=True)
+
+ def _cadence_fetch(url: str) -> str:
+ import urllib.request
+
+ with urllib.request.urlopen(url, timeout=10.0) as resp:
+ return resp.read(1024 * 1024).decode("utf-8", errors="replace")
+
+ def _cadence_ls_remote(source: str) -> str:
+ import subprocess as _sp
+
+ proc = _sp.run(
+ ["git", "ls-remote", source, "HEAD"],
+ capture_output=True, text=True, timeout=30,
+ )
+ out = (proc.stdout or "").strip()
+ return out.split("\t")[0] if out else ""
+
+ import threading as _threading
+
+ _threading.Thread(
+ target=_kick_plugin_check_cadence,
+ daemon=True,
+ name="plugin-update-check",
+ ).start()
# start_gateway() performs the full graceful teardown (adapters
# disconnected, sessions saved + flushed, SQLite closed, cron/MCP stopped,
# PID file + runtime lock released) before it returns OR raises SystemExit
diff --git a/hermes_cli/plugins_cadence.py b/hermes_cli/plugins_cadence.py
new file mode 100644
index 00000000000..638cedf1322
--- /dev/null
+++ b/hermes_cli/plugins_cadence.py
@@ -0,0 +1,160 @@
+"""The plugin update-check cadence: read-only, receipt-surfaced.
+
+Runs at gateway start + the periodic tick when
+``plugins.auto_update_check_hours`` (default 24, 0 disables) says it's
+due, writes a plugin-check receipt (pm.receipt, kind 'plugin-check'),
+and logs ONE actionable line when updates exist. Applying updates
+stays explicit — ``plugins.auto_apply: true`` (default false) opts into
+unattended apply for git-row plugins ONLY, scan-gated like cmd_update.
+
+Pure, injectable clock/check/update seams for hermetic tests.
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Callable, Optional
+
+_MARKERS_DIR = "plugin-update-checks"
+_DEFAULT_INTERVAL_HOURS = 24
+
+
+def _markers_dir() -> Path:
+ # resolved per call (tests monkeypatch get_hermes_home)
+ from hermes_constants import get_hermes_home
+
+ d = get_hermes_home() / _MARKERS_DIR
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def check_interval_hours(config_get: Callable = None) -> float:
+ """plugins.auto_update_check_hours; 0 disables; default 24."""
+ if config_get is None:
+ config_get = _default_config_get
+ try:
+ value = config_get("plugins", "auto_update_check_hours")
+ except Exception:
+ return _DEFAULT_INTERVAL_HOURS
+ if value is None:
+ return _DEFAULT_INTERVAL_HOURS
+ try:
+ hours = float(value)
+ except (TypeError, ValueError):
+ return _DEFAULT_INTERVAL_HOURS
+ return max(0.0, hours)
+
+
+def auto_apply_enabled(config_get: Callable = None) -> bool:
+ if config_get is None:
+ config_get = _default_config_get
+ try:
+ return bool(config_get("plugins", "auto_apply"))
+ except Exception:
+ return False
+
+
+def _default_config_get(section: str, key: str):
+ try:
+ from hermes_cli.config import cfg_get, load_config_readonly
+
+ return cfg_get(load_config_readonly(), section, key, default=None)
+ except Exception:
+ return None
+
+
+def check_due(now: Optional[float] = None, interval_hours: Optional[float] = None,
+ config_get: Callable = None) -> bool:
+ """The clock gate: last-run marker vs the interval."""
+ if interval_hours is None:
+ interval_hours = check_interval_hours(config_get)
+ if interval_hours <= 0:
+ return False
+ now = time.time() if now is None else now
+ marker = _markers_dir() / "last-run"
+ try:
+ last = marker.stat().st_mtime
+ except OSError:
+ return True
+ return (now - last) >= interval_hours * 3600
+
+
+def run_scheduled_check(
+ *,
+ run_checks_fn: Callable[..., list],
+ plugins_dir: Path,
+ apply_updates_fn: Optional[Callable[[str], None]] = None,
+ log=None,
+ config_get: Callable = None,
+ now: Optional[float] = None,
+) -> Optional[list]:
+ """One cadence tick: gate → check → receipt → (opt-in) apply.
+
+ Returns the check results, or None when not due / disabled. NEVER
+ raises — a cadence failure is logged, never fatal.
+ """
+ import logging
+
+ if log is None:
+ log = logging.getLogger(__name__)
+ if not check_due(now=now, config_get=config_get):
+ return None
+
+ try:
+ results = run_checks_fn(plugins_dir)
+ except Exception:
+ log.warning("plugin update check failed", exc_info=True)
+ results = []
+
+ # the receipt — the surface every medium reads
+ try:
+ from pm import receipt
+
+ receipt.begin("plugin-check")
+ receipt.record_plugin_checks(results)
+ updates = [
+ r for r in results
+ if getattr(r, "update_available", None) is True
+ ]
+ receipt.finalize("ok" if not updates else "updates-available")
+ except Exception:
+ log.debug("plugin-check receipt write failed", exc_info=True)
+
+ # ONE actionable line (a log, not a system-prompt mutation — cache safe)
+ updates = [r for r in results if getattr(r, "update_available", None) is True]
+ needs_fixing = [r for r in results if getattr(r, "needs_fixing", None)]
+ if updates:
+ names = ", ".join(r.name for r in updates)
+ log.info(
+ "plugin updates available: %s — run `hermes plugins check-updates` "
+ "and `hermes plugins update <name>`",
+ names,
+ )
+ if needs_fixing:
+ names = ", ".join(r.name for r in needs_fixing)
+ log.warning(
+ "plugin update_url mismatches need attention: %s — run "
+ "`hermes plugins trust-update-url <name>` after review",
+ names,
+ )
+
+ # Opt-in unattended apply: git rows ONLY, scan-gated by the update
+ # path itself. Pinned/manual/drift/pip are never auto-applied
+ # (their update_available is False/None or their class excludes it).
+ if apply_updates_fn and updates and auto_apply_enabled(config_get):
+ for r in updates:
+ if getattr(r, "klass", "") == "git":
+ try:
+ apply_updates_fn(r.name)
+ except Exception:
+ log.warning("auto-apply of %s failed", r.name, exc_info=True)
+
+ # stamp the marker AFTER a completed run (even a failed one — a
+ # failing check retrying every tick would hammer the network)
+ try:
+ marker = _markers_dir() / "last-run"
+ marker.write_text(str(int(time.time())), encoding="utf-8")
+ except OSError:
+ pass
+ return results
\ No newline at end of file
diff --git a/pm/receipt.py b/pm/receipt.py
index 302c2edc1ce..b361bc48e23 100644
--- a/pm/receipt.py
+++ b/pm/receipt.py
@@ -84,6 +84,16 @@ def record_platform(platform_id: str) -> None:
_current["platform"] = platform_id
+def record_plugin_checks(results: list) -> None:
+ """Plugin update-check results (the cadence's receipt section).
+ Each item is a plugins_updates.CheckResult.to_json() dict."""
+ if _current is None:
+ return
+ _current["plugin_checks"] = [
+ r.to_json() if hasattr(r, "to_json") else r for r in results
+ ]
+
+
def snapshot() -> Optional[dict[str, Any]]:
"""The in-flight receipt data — for the updater to EMBED its sync
sections into its own receipt (one schema, one directory)."""
diff --git a/tests/hermes_cli/test_plugins_cadence.py b/tests/hermes_cli/test_plugins_cadence.py
new file mode 100644
index 00000000000..18bf363051f
--- /dev/null
+++ b/tests/hermes_cli/test_plugins_cadence.py
@@ -0,0 +1,176 @@
+"""Tests: the plugin update-check cadence — clock-gated, receipt-surfaced,
+apply-explicit. All seams injected; hermetic."""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+import hermes_cli.plugins_cadence as cad
+
+
+def homed(tmp_path, monkeypatch):
+ """Cadence state (markers) inside a temp hermes home."""
+ import hermes_constants
+
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
+ return tmp_path
+
+
+class _Result:
+ def __init__(self, name, klass="git", update_available=None, needs_fixing=None):
+ self.name = name
+ self.klass = klass
+ self.update_available = update_available
+ self.needs_fixing = needs_fixing
+
+ def to_json(self):
+ return {"name": self.name, "class": self.klass}
+
+
+def _no_results(plugins_dir, **k):
+ return []
+
+
+def test_clock_gate_due_when_never_run(homed):
+ assert cad.check_due(now=1000.0, interval_hours=24) is True
+
+
+def test_clock_gate_not_due_within_interval(homed, monkeypatch):
+ marker = homed / "plugin-update-checks"
+ marker.mkdir()
+ (marker / "last-run").write_text("x", encoding="utf-8")
+ # fresh mtime
+ recent = time.time() - 100
+ import os
+
+ os.utime(marker / "last-run", (recent, recent))
+ assert cad.check_due(now=time.time(), interval_hours=24) is False
+
+
+def test_zero_interval_disables(homed):
+ assert cad.check_due(now=time.time(), interval_hours=0) is False
+
+
+def test_interval_reads_config(homed):
+ assert cad.check_interval_hours(lambda s, k: None) == 24
+ assert cad.check_interval_hours(lambda s, k: 6) == 6.0
+ assert cad.check_interval_hours(lambda s, k: 0) == 0.0
+ assert cad.check_interval_hours(lambda s, k: "garbage") == 24
+
+
+def test_run_writes_receipt_and_marker(homed):
+ calls = {"checks": 0}
+ receipt_calls = []
+
+ import pm.receipt as receipt_mod
+
+ orig_begin, orig_finalize = receipt_mod.begin, receipt_mod.finalize
+ monkey = pytest.MonkeyPatch()
+ monkey.setattr(receipt_mod, "begin", lambda kind: receipt_calls.append(("begin", kind)))
+ monkey.setattr(
+ receipt_mod, "finalize",
+ lambda outcome, exit_code=0: receipt_calls.append(("finalize", outcome)),
+ )
+ try:
+ def fake_run_checks(plugins_dir):
+ calls["checks"] += 1
+ return [_Result("plug", update_available=True)]
+
+ results = cad.run_scheduled_check(
+ run_checks_fn=fake_run_checks,
+ plugins_dir=homed / "plugins",
+ now=time.time(),
+ )
+ assert calls["checks"] == 1
+ assert results[0].name == "plug"
+ assert ("begin", "plugin-check") in receipt_calls
+ assert ("finalize", "updates-available") in receipt_calls
+ # marker stamped → second run is a no-op
+ assert cad.run_scheduled_check(
+ run_checks_fn=fake_run_checks,
+ plugins_dir=homed / "plugins",
+ now=time.time(),
+ ) is None
+ assert calls["checks"] == 1
+ finally:
+ monkey.undo()
+
+
+def test_needs_fixing_logged_not_applied(homed):
+ applied = []
+
+ import pm.receipt as receipt_mod
+
+ monkey = pytest.MonkeyPatch()
+ monkey.setattr(receipt_mod, "begin", lambda kind: None)
+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)
+ try:
+ results = cad.run_scheduled_check(
+ run_checks_fn=lambda d: [_Result("plug", needs_fixing="mismatch")],
+ plugins_dir=homed / "plugins",
+ apply_updates_fn=applied.append,
+ now=time.time(),
+ )
+ assert applied == [] # needs-fixing is never auto-applied
+ finally:
+ monkey.undo()
+
+
+def test_auto_apply_only_git_rows_and_only_when_opted_in(homed):
+ applied = []
+
+ import pm.receipt as receipt_mod
+
+ monkey = pytest.MonkeyPatch()
+ monkey.setattr(receipt_mod, "begin", lambda kind: None)
+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)
+ try:
+ results = [_Result("gitplug", klass="git", update_available=True),
+ _Result("pipplug", klass="pip", update_available=True)]
+ # opted OUT: nothing applied
+ cad.run_scheduled_check(
+ run_checks_fn=lambda d: results,
+ plugins_dir=homed / "plugins",
+ apply_updates_fn=applied.append,
+ config_get=lambda s, k: (False if k == "auto_apply" else None),
+ now=time.time(),
+ )
+ assert applied == [] # auto_apply False → nothing
+
+ # opted IN: only the git row applies
+ cad._markers_dir().joinpath("last-run").unlink()
+ cad.run_scheduled_check(
+ run_checks_fn=lambda d: results,
+ plugins_dir=homed / "plugins",
+ apply_updates_fn=applied.append,
+ config_get=lambda s, k: (True if k == "auto_apply" else None),
+ now=time.time(),
+ )
+ assert applied == ["gitplug"]
+ finally:
+ monkey.undo()
+
+
+def test_check_failure_is_never_fatal_and_stamps_marker(homed):
+ import pm.receipt as receipt_mod
+
+ monkey = pytest.MonkeyPatch()
+ monkey.setattr(receipt_mod, "begin", lambda kind: None)
+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)
+ try:
+ def boom(d):
+ raise RuntimeError("network down")
+
+ results = cad.run_scheduled_check(
+ run_checks_fn=boom,
+ plugins_dir=homed / "plugins",
+ now=time.time(),
+ )
+ assert results == []
+ # marker stamped → a failing check doesn't hammer the network
+ assert (homed / "plugin-update-checks" / "last-run").is_file()
+ finally:
+ monkey.undo()