The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): keep satellite diagnostics scoped to observed health
yoniebansa3dc9583a8c7
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 9a589dfe34b..cc3d293e365 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -440,48 +440,30 @@ def cron_status():gateway_alive_via_lock = is_gateway_runtime_lock_active()lock_pid = get_running_pid() if gateway_alive_via_lock else Nonepids = [lock_pid] if lock_pid else pids- # Satellite profile: no local gateway.pid, but the default multiplexer ticks its store- # (#107168). Without this, `cron status` in a bot profile always says "not running"- # even though the default gateway *is* the live ticker for it, and the message is- # both wrong and masks the real Desktop-only-ticker cliff.+ # Multiplexer identity does not establish the active profile's ticker health.if not pids and not gateway_alive_via_lock:with contextlib.suppress(Exception):from hermes_cli.gateway import named_profile_served_by_running_multiplexerserved_by_multiplexer = named_profile_served_by_running_multiplexer()- if served_by_multiplexer:- # Re-check liveness via default profile's lock for heartbeat display.- with contextlib.suppress(Exception):- from hermes_constants import get_default_hermes_root- from gateway.status import _pid_exists, _pid_from_record, _read_pid_record- rec = _read_pid_record(get_default_hermes_root() / "gateway.pid")- pid = _pid_from_record(rec) if rec else None- if pid and _pid_exists(pid):- pids = [pid]if pids or gateway_alive_via_lock or served_by_multiplexer:- if served_by_multiplexer and not (pids or gateway_alive_via_lock):- print(color("✓ Gateway is running via the default-profile multiplexer"- " — cron jobs will fire automatically", Colors.GREEN))- if pids:- print(f" PID: {', '.join(map(str, pids))} (default profile)")- else:- _print_ticker_health(pids)+ if served_by_multiplexer:+ print(" Scheduler host: default-profile multiplexer")+ _print_ticker_health(pids)else:print(color("✗ Gateway is not running — cron jobs will NOT fire", Colors.RED))- # For non-default profiles the default multiplexer is the 24/7 ticker; the- # Desktop scheduler only runs while the app is open (#107168). Name the fix- # so the message is not misread as a false positive on desktop installs.+ # Desktop scheduling requires an open app and an awake machine.try:from hermes_cli.profiles import get_active_profile_nameactive = get_active_profile_name() or "default"except Exception:active = "default"if active != "default":- print("\n This is a non-default profile. Two ways to make its jobs fire 24/7:\n"- " 1) Keep the Desktop app open (its scheduler ticks all profiles), or\n"- " 2) Enable the default gateway to tick all profiles:\n"+ print("\n This is a non-default profile. Automatic scheduling requires an awake machine and either:\n"+ " 1) The Desktop app open with this profile included in its scheduler, or\n"+ " 2) A running default gateway configured to tick this profile:\n"" hermes --profile default config set gateway.multiplex_profiles true\n"- " hermes gateway restart # from the default profile\n"- " Check: hermes cron status (from default) should show the ticker heartbeat.\n")+ " hermes --profile default gateway restart\n"+ " Check: hermes cron status from this profile should show its ticker heartbeat.\n")else:print("\n To enable automatic execution:\n"" hermes gateway install # Install as a user service\n"@@ -573,11 +555,7 @@ def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:if unverified := job.get("last_delivery_unverified"):issues.append("last delivery unverified (adapter acked without evidence): "+ _unverified_targets(unverified))- # Missed-fire visibility: a catch-up/late dispatch means the scheduler was down- # and the job ran hours after schedule (#107168). Without this, doctor says- # "found no issues" on a job that just silently skipped an occurrence then- # fast-forwarded next_run_at — the overdue check passes because next_run_at- # is now in the future, so the missed occurrence is invisible.+ # Dispatch records measure lateness, not whether the scheduler process was running.if isinstance(job.get("last_dispatch"), dict):kind = job["last_dispatch"].get("kind")if kind == "catch_up":@@ -585,7 +563,7 @@ def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:scheduled = job["last_dispatch"].get("scheduled_at", "?")issues.append(f"last fire was a catch-up after a missed schedule (scheduled {scheduled}, "- f"{_format_lateness(lateness)} late) — scheduler was not running at the scheduled time")+ f"{_format_lateness(lateness)} late)")elif kind == "late":lateness = job["last_dispatch"].get("lateness_seconds", 0)scheduled = job["last_dispatch"].get("scheduled_at", "?")@@ -593,9 +571,7 @@ def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:f"last fire was late (scheduled {scheduled}, {_format_lateness(lateness)} late) — "f"scheduler was delayed")if fire_err := job.get("last_fire_error"):- # last_fire_error is set when a scheduled fire was missed/skipped entirely- # (e.g. ticker down, fire-claim wedged). Surface it in doctor so the missed- # occurrence is not silently swallowed when next_run_at jumped.+ # The handoff error survives next_run_at advancing beyond the failed dispatch.detail = fire_err.get("detail") if isinstance(fire_err, dict) else str(fire_err)at = fire_err.get("at", "?") if isinstance(fire_err, dict) else "?"issues.append(f"missed scheduled fire at {at}: {detail}")diff --git a/tests/hermes_cli/test_cron_satellite_diagnostics.py b/tests/hermes_cli/test_cron_satellite_diagnostics.pynew file mode 100644index 00000000000..3c34c268f1e--- /dev/null+++ b/tests/hermes_cli/test_cron_satellite_diagnostics.py@@ -0,0 +1,89 @@+from datetime import datetime, timedelta, timezone+import json+import os+import time++import pytest+++def profile(tmp_path, monkeypatch):+ from cron import jobs++ root = tmp_path / "home"+ home = root / "profiles" / "probe"+ home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_PROFILE", "probe")+ monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)+ monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)+ monkeypatch.setattr(jobs, "CRON_DIR", home / "cron")+ monkeypatch.setattr(jobs, "JOBS_FILE", home / "cron/jobs.json")+ monkeypatch.setattr(jobs, "OUTPUT_DIR", home / "cron/output")+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])+ monkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda: False)+ root.joinpath("gateway.pid").write_text(json.dumps({"pid": os.getpid()}))+ root.joinpath("config.yaml").write_text("gateway:\n multiplex_profiles: true\n")+ return root++[email protected]("mode", ["missing", "fresh", "stale", "disabled", "excluded", "local", "external"])+def test_status_preserves_profile_health_contract(profile, capsys, monkeypatch, mode):+ from cron import jobs+ from hermes_cli import cron++ if mode in {"fresh", "stale", "local"}:+ jobs.record_ticker_heartbeat(success=True)+ if mode == "stale":+ (jobs.CRON_DIR / "ticker_heartbeat").write_text(str(time.time() - 3600))+ if mode == "disabled":+ profile.joinpath("config.yaml").write_text("gateway:\n multiplex_profiles: false\n")+ if mode == "excluded":+ profile.joinpath("config.yaml").write_text("gateway:\n multiplex_profiles: true\n multiplex_profile_allowlist: [other]\n")+ if mode == "local":+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [os.getpid()])+ if mode == "external":+ monkeypatch.setattr(cron, "_active_cron_provider_name", lambda: "managed-test")++ cron.cron_status()+ output = capsys.readouterr().out+ assert ("Scheduler host: default-profile multiplexer" in output) == (mode in {"missing", "fresh", "stale"})+ assert ("will fire automatically" in output) == (mode in {"fresh", "local"})+ if mode == "missing":+ assert "has not reported a heartbeat" in output+ if mode == "stale":+ assert "STALLED" in output+ if mode in {"disabled", "excluded"}:+ assert "24/7" not in output+ assert "awake" in output+ assert "hermes --profile default gateway restart" in output+ if mode == "external":+ assert "managed scheduler" in output+ assert "STALLED" not in output++[email protected]("dispatch", ["catch_up", "late", "forward_error"])+def test_doctor_reports_persisted_dispatch_health(profile, capsys, dispatch):+ from cron import jobs+ from hermes_cli.cron import cron_doctor++ job = jobs.create_job(prompt="probe", schedule="every 1h")+ if dispatch == "forward_error":+ jobs.note_fire_forward_failure(job["id"], "loopback unavailable")+ else:+ records = jobs.load_jobs()+ delay = timedelta(hours=5) if dispatch == "catch_up" else timedelta(minutes=5)+ records[0]["next_run_at"] = (datetime.now(timezone.utc) - delay).isoformat()+ jobs.save_jobs(records)+ assert len(jobs.get_due_jobs()) == 1+ persisted = jobs.get_job(job["id"])+ assert persisted is not None+ assert persisted["last_dispatch"]["kind"] == dispatch+ assert cron_doctor() == 1+ output = capsys.readouterr().out+ expected = {"catch_up": "catch-up", "late": "last fire was late", "forward_error": "loopback unavailable"}+ assert expected[dispatch] in output+ assert "scheduler was not running" not in output+ if dispatch == "forward_error":+ jobs.mark_job_run(job["id"], success=True)+ assert cron_doctor() == 0