The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): flag overdue next_run_at and stale ticker in cron status
liuhao1024a20a71a3e3f1
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 4de42aa0ddb..fc15702fc59 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -4,6 +4,7 @@ import contextlibimport jsonimport reimport sys+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, Iterable, List, Optional@@ -96,6 +97,21 @@ def _dispatch_kind_label(kind) -> Optional[str]:return {"catch_up": "catch-up after missed fire", "late": "late"}.get(kind)+def _next_run_overdue_seconds(next_run_at: str) -> Optional[float]:+ """Seconds the timestamp has already been in the past; None if malformed.++ next_run_at is written as timezone-aware ISO strings; a naive value only ever comes+ from a hand-edited jobs.json and is read as UTC.+ """+ try:+ dt = datetime.fromisoformat(str(next_run_at).replace("Z", "+00:00"))+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return (datetime.now(timezone.utc) - dt).total_seconds()++def _dispatch_display(dispatch: dict) -> Optional[str]:"""One-line scheduled-vs-actual dispatch summary; None when the stamp is malformed.@@ -442,6 +458,15 @@ def cron_status():else:print(color("✗ Gateway is not running — cron jobs will NOT fire", Colors.RED))active = get_active_profile_name()+ # When scheduling last worked before the host went away: without this, a+ # 7h-overdue job still reads as a normal upcoming "Next run" (#114309).+ with contextlib.suppress(Exception):+ from cron.jobs import TICKER_INTERVAL_SECONDS, get_ticker_heartbeat_age+ hb_age = get_ticker_heartbeat_age()+ if hb_age is not None and hb_age > TICKER_INTERVAL_SECONDS * 3 + 20:+ print(color(" Scheduler last ticked "+ f"{_format_lateness(hb_age)} ago — jobs that came due "+ "since then have not fired.", Colors.YELLOW))print("\n To enable automatic execution for this profile:\n"" hermes gateway install # Install as a user service\n"" sudo hermes gateway install --system # Linux servers: boot-time system service\n"@@ -479,7 +504,16 @@ def _print_active_jobs_summary(jobs) -> None:next_runs.append((parsed.astimezone(timezone.utc), raw))print(f" {len(jobs)} active job(s)")if next_runs:- print(f" Next run: {min(next_runs, key=lambda run: run[0])[1]}")+ earliest = min(next_runs, key=lambda run: run[0])[1]+ overdue_by = _next_run_overdue_seconds(earliest)+ if overdue_by is not None and overdue_by > 0:+ # #114309: a dead scheduler leaves next_run_at stranded in the past; presenting it+ # as an upcoming "Next run" hides the outage.+ print(color(f" ⚠ Next run {earliest} is OVERDUE — passed "+ f"{_format_lateness(overdue_by)} ago but the job has not fired "+ "(is the scheduler running?)", Colors.YELLOW))+ else:+ print(f" Next run: {earliest}")# Post-downtime late fires show at status level, not just per-job in `cron list`.late = [j for j in jobs if isinstance(j.get("last_dispatch"), dict)and j["last_dispatch"].get("kind") in ("late", "catch_up")]diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.pyindex 96d4e63dd92..86806893409 100644--- a/tests/hermes_cli/test_cron.py+++ b/tests/hermes_cli/test_cron.py@@ -1,7 +1,9 @@"""Tests for hermes_cli.cron command handling."""import argparse+import timefrom argparse import Namespace+from datetime import datetime, timedelta, timezonefrom types import SimpleNamespaceimport pytest@@ -590,6 +592,50 @@ class TestSlashCronListLastStatus:assert "(ok)" in out+class TestStatusSurfacesDeadScheduler:+ """#114309 — with the ticker dead and a job's next_run_at stranded in the past, `cron+ status` must not present the stale timestamp as an upcoming "Next run": flag it as+ OVERDUE and say when the scheduler last ticked."""++ def _dead_gateway(self, monkeypatch):+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])+ monkeypatch.setattr(+ "hermes_cli.gateway.named_profile_served_by_running_multiplexer", lambda: None+ )+ monkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda: False)++ def test_overdue_next_run_and_stale_heartbeat_are_loud(+ self, tmp_cron_dir, capsys, monkeypatch+ ):+ job = create_job(prompt="Hourly", schedule="every 60m")+ self._dead_gateway(monkeypatch)+ overdue = datetime.now(timezone.utc) - timedelta(hours=7)+ jobs = load_jobs()+ jobs[[j["id"] for j in jobs].index(job["id"])]["next_run_at"] = overdue.isoformat()+ save_jobs(jobs)+ (tmp_cron_dir / "cron" / "ticker_heartbeat").write_text(str(time.time() - 25 * 3600))++ cron_command(Namespace(cron_command="status"))++ out = capsys.readouterr().out+ assert "Gateway is not running" in out+ assert "Scheduler last ticked" in out+ assert "OVERDUE" in out+ # The stale timestamp must no longer read as an upcoming run.+ assert "Next run:" not in out++ def test_future_next_run_stays_plain(self, tmp_cron_dir, capsys, monkeypatch):+ create_job(prompt="Hourly", schedule="every 60m")+ self._dead_gateway(monkeypatch)++ cron_command(Namespace(cron_command="status"))++ out = capsys.readouterr().out+ assert "Next run:" in out+ assert "OVERDUE" not in out+ assert "Scheduler last ticked" not in out++class TestSlashCronRunSkipped:"""``/cron run`` on a job whose claim is refused (paused here; a live claim held by anotherrun is the same shape) must print the refusal, never ``Triggered … next scheduler tick``."""