The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: surface missed cron fires as last_fire_error on the job record
Tekniumcb1b1da21901
diff --git a/cron/jobs.py b/cron/jobs.pyindex 1ef134fa800..68cfacb922e 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -2363,6 +2363,38 @@ def clear_drift_alerted(job_id: str) -> None:_set_alert_flag(job_id, "drift_alerted", False)+def note_fire_forward_failure(job_id: str, detail: str) -> bool:+ """Durably record that a scheduled fire could not be handed to the runner.++ Written by the dashboard fire webhook when the loopback forward to the+ gateway api_server fails (gateway unreachable / listener not bound) —+ the shape behind "job runs manually but never auto-fires". Without this+ stamp the miss is invisible outside gui.log: no execution row is created+ (the claim never happens) and ``last_status``/``last_error`` only cover+ runs that actually started.++ Stored as ``last_fire_error`` (``{"at": iso, "detail": str}``) on the job+ record so `cronjob list`, the CLI, and the dashboard all surface it.+ Cleared by the next successful run (``mark_job_run``). Repeated failures+ overwrite in place — latest miss wins; per-fire history lives in the+ scheduler's own logs.++ Returns True when a job record was found and stamped.+ """+ with _jobs_lock():+ jobs = load_jobs()+ for i, job in enumerate(jobs):+ if job["id"] == job_id:+ job["last_fire_error"] = {+ "at": _hermes_now().isoformat(),+ "detail": str(detail or "")[:500],+ }+ jobs[i] = job+ save_jobs(jobs)+ return True+ return False++def _mark_job_run_locked(job_id: str,success: bool,@@ -2412,6 +2444,10 @@ def _mark_job_run_locked(if success:job.pop("preflight_alerted", None)job.pop("drift_alerted", None)+ # The fire hand-off demonstrably works again — clear the+ # forward-failure stamp so it only ever describes the+ # CURRENT auto-fire health, not a healed past incident.+ job.pop("last_fire_error", None)# Consecutive agent-failure streak. Any successful run resets# it; delivery failures alone do NOT count (the agent did its# job). Read by the scheduler's failure-delivery path to nudgediff --git a/gateway/run.py b/gateway/run.pyindex 924858867ad..a7b8e79e57d 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -30292,6 +30292,32 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =)cron_thread.start()+ # Preflight tell for the hosted fire path: an external cron provider+ # (Chronos) delivers scheduled fires over HTTP to THIS process's+ # api_server adapter on loopback. If that adapter never came up (most+ # commonly API_SERVER_KEY missing from this process's environment —+ # e.g. a gateway relaunched outside its supervisor without the profile+ # env), every scheduled fire will fail with ConnectError at the+ # dashboard forwarder while manual runs keep working, which users+ # reliably misread as a job bug. Say it loudly ONCE at startup, when+ # it is fixable, instead of letting the first miss say it at 2am.+ if not isinstance(cron_provider, InProcessCronScheduler):+ try:+ _has_api_server = Platform.API_SERVER in (runner.adapters or {})+ except Exception:+ _has_api_server = True # never let the tell break startup+ if not _has_api_server:+ logger.warning(+ "Cron provider '%s' is active but the api_server adapter is "+ "NOT running in this gateway — scheduled fires arrive over "+ "loopback HTTP and will all fail (jobs only run when "+ "triggered manually). Most common cause: API_SERVER_KEY is "+ "missing from this gateway process's environment. Restart "+ "the gateway through its supervisor (`hermes gateway "+ "restart`) so the profile env loads.",+ getattr(cron_provider, "name", "external"),+ )+# Gateway-only periodic housekeeping (channel dir, cache cleanup, paste# sweep, curator) — runs independently of which cron provider is active.# Shares cron_stop as the shutdown signal.diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 3e4c06676a4..7d08ebfd1e0 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -198,6 +198,13 @@ def cron_list(show_all: bool = False):if delivery_err:print(f" {color('⚠ Delivery failed:', Colors.YELLOW)} {delivery_err}")+ fire_err = job.get("last_fire_error")+ if isinstance(fire_err, dict) and fire_err.get("detail"):+ print(+ f" {color('⚠ Missed scheduled fire:', Colors.RED)} "+ f"{fire_err.get('at', '?')} {fire_err['detail']}"+ )+print()_warn_if_gateway_not_running()diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.pyindex 8e846a132ee..c540c77e170 100644--- a/hermes_cli/web_routers/cron.py+++ b/hermes_cli/web_routers/cron.py@@ -192,6 +192,25 @@ async def cron_fire_webhook(request: Request):forwarded = await _forward_cron_fire_to_gateway(profile, job_id, auth)if forwarded is None:+ # Durably stamp the miss on the job record (last_fire_error) so the+ # user and their agent can see "scheduled fire could not reach the+ # runner" in `cronjob list` / the dashboard — without this, a dead+ # 8642 hop is invisible outside gui.log (no execution row is ever+ # created because the claim never happens). Best-effort: visibility+ # must never break the retry contract below.+ try:+ await _run_cron_dashboard_io(+ _call_cron_for_profile,+ profile,+ "note_fire_forward_failure",+ job_id,+ "scheduled fire could not be forwarded to the gateway "+ "api_server (127.0.0.1 loopback unreachable); the gateway "+ "process may be down or its api_server adapter not bound "+ "(missing API_SERVER_KEY)",+ )+ except Exception:+ _log.debug("could not stamp last_fire_error for %s", job_id, exc_info=True)# Gateway unreachable. Split by OPERATOR INTENT (OOF-266):## - Deliberately stopped gateway (durable desired_state == "stopped",diff --git a/tests/cron/test_fire_forward_failure_stamp.py b/tests/cron/test_fire_forward_failure_stamp.pynew file mode 100644index 00000000000..cb205f8fb69--- /dev/null+++ b/tests/cron/test_fire_forward_failure_stamp.py@@ -0,0 +1,89 @@+"""Tests for the last_fire_error stamp (missed scheduled fires made visible).++When the hosted fire path (NAS -> dashboard -> loopback forward to the+gateway api_server) cannot reach the gateway, no execution row is ever+created — the miss used to be invisible outside gui.log. The dashboard fire+webhook now stamps ``last_fire_error`` on the job record via+``note_fire_forward_failure`` so `cronjob list`, `hermes cron list`, and the+dashboard surface it, and ``mark_job_run`` clears the stamp on the next+successful run so it always describes CURRENT auto-fire health.+"""++import pytest++from cron.jobs import (+ create_job,+ get_job,+ mark_job_run,+ note_fire_forward_failure,+)+++def tmp_cron_dir(tmp_path, monkeypatch):+ """Redirect cron storage to a temp directory."""+ monkeypatch.setattr("cron.jobs.CRON_DIR", tmp_path / "cron")+ monkeypatch.setattr("cron.jobs.JOBS_FILE", tmp_path / "cron" / "jobs.json")+ monkeypatch.setattr("cron.jobs.OUTPUT_DIR", tmp_path / "cron" / "output")+ return tmp_path+++class TestNoteFireForwardFailure:+ def test_stamps_last_fire_error(self, tmp_cron_dir):+ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ assert note_fire_forward_failure(job["id"], "gateway unreachable") is True++ stamped = get_job(job["id"])+ err = stamped["last_fire_error"]+ assert isinstance(err, dict)+ assert err["detail"] == "gateway unreachable"+ # Timestamp parses as ISO.+ from datetime import datetime+ datetime.fromisoformat(err["at"])++ def test_unknown_job_returns_false(self, tmp_cron_dir):+ assert note_fire_forward_failure("nope", "gateway unreachable") is False++ def test_repeated_failures_overwrite_latest_wins(self, tmp_cron_dir):+ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ note_fire_forward_failure(job["id"], "first miss")+ note_fire_forward_failure(job["id"], "second miss")+ err = get_job(job["id"])["last_fire_error"]+ assert err["detail"] == "second miss"++ def test_detail_truncated_to_500(self, tmp_cron_dir):+ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ note_fire_forward_failure(job["id"], "x" * 2000)+ err = get_job(job["id"])["last_fire_error"]+ assert len(err["detail"]) == 500++ def test_successful_run_clears_stamp(self, tmp_cron_dir):+ """The stamp describes CURRENT auto-fire health — a run that made it+ through the fire path proves the hand-off works again."""+ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ note_fire_forward_failure(job["id"], "gateway unreachable")+ assert get_job(job["id"])["last_fire_error"] is not None++ assert mark_job_run(job["id"], success=True) is True+ assert get_job(job["id"]).get("last_fire_error") is None++ def test_failed_run_keeps_stamp(self, tmp_cron_dir):+ """An agent-level failure is not proof the fire hand-off healed —+ only success clears (mirrors preflight_alerted / drift_alerted)."""+ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ note_fire_forward_failure(job["id"], "gateway unreachable")++ assert mark_job_run(job["id"], success=False, error="boom") is True+ err = get_job(job["id"]).get("last_fire_error")+ assert isinstance(err, dict)+ assert err["detail"] == "gateway unreachable"+++class TestFormatJobSurfacesFireError:+ def test_cronjob_list_carries_last_fire_error(self, tmp_cron_dir):+ from tools.cronjob_tools import _format_job++ job = create_job(prompt="Daily invoice triage", schedule="every 1h")+ note_fire_forward_failure(job["id"], "gateway unreachable")+ formatted = _format_job(get_job(job["id"]))+ assert formatted["last_fire_error"]["detail"] == "gateway unreachable"diff --git a/tests/hermes_cli/test_cron_fire_dashboard.py b/tests/hermes_cli/test_cron_fire_dashboard.pyindex a8c08df9395..aa898bf78ef 100644--- a/tests/hermes_cli/test_cron_fire_dashboard.py+++ b/tests/hermes_cli/test_cron_fire_dashboard.py@@ -438,3 +438,106 @@ def test_intentionally_stopped_false_when_profile_resolution_fails(monkeypatch):monkeypatch.setattr(web_server, "_cron_profile_home", boom)assert web_server._gateway_intentionally_stopped("ghost") is False+++# ── last_fire_error stamp on forward failure (missed-fire visibility) ─────+++def test_forward_failure_stamps_last_fire_error(monkeypatch):+ """Gateway unreachable -> the job record gets a durable last_fire_error+ stamp (via note_fire_forward_failure) so the miss is visible in+ `cronjob list` / the dashboard instead of only in gui.log."""+ stamped = []++ async def fake_forward(profile, job_id, authorization):+ return None # unreachable++ def fake_call_cron(profile, func_name, *args, **kwargs):+ stamped.append((profile, func_name, args))+ return True++ monkeypatch.setattr(+ "plugins.cron_providers.chronos.verify.get_fire_verifier",+ lambda: (lambda **kw: {"purpose": "cron_fire"}),+ )+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)+ monkeypatch.setattr(web_server, "_gateway_intentionally_stopped", lambda p: False)+ monkeypatch.setattr(web_server, "_call_cron_for_profile", fake_call_cron)++ client, pa, ph = _client(auth_required=False)+ try:+ resp = client.post("/api/cron/fire",+ headers={"Authorization": "Bearer nas-jwt"},+ json={"job_id": "j8"})+ assert resp.status_code == 503 # retry contract unchanged+ assert len(stamped) == 1+ profile, func_name, args = stamped[0]+ assert profile == "default"+ assert func_name == "note_fire_forward_failure"+ assert args[0] == "j8"+ assert "api_server" in args[1] # detail names the dead hop+ finally:+ _restore(pa, ph)+ client.close()+++def test_forward_failure_stamp_error_never_breaks_retry_contract(monkeypatch):+ """Stamping is best-effort observability: if the jobs store write blows+ up, the webhook still returns the retryable 503 + Retry-After."""++ async def fake_forward(profile, job_id, authorization):+ return None++ def boom(profile, func_name, *args, **kwargs):+ raise RuntimeError("jobs.json locked")++ monkeypatch.setattr(+ "plugins.cron_providers.chronos.verify.get_fire_verifier",+ lambda: (lambda **kw: {"purpose": "cron_fire"}),+ )+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)+ monkeypatch.setattr(web_server, "_gateway_intentionally_stopped", lambda p: False)+ monkeypatch.setattr(web_server, "_call_cron_for_profile", boom)++ client, pa, ph = _client(auth_required=False)+ try:+ resp = client.post("/api/cron/fire",+ headers={"Authorization": "Bearer nas-jwt"},+ json={"job_id": "j9"})+ assert resp.status_code == 503+ assert resp.headers.get("Retry-After") == "60"+ finally:+ _restore(pa, ph)+ client.close()+++def test_reachable_gateway_does_not_stamp(monkeypatch):+ """A successful forward must not touch the job record."""+ stamped = []++ async def fake_forward(profile, job_id, authorization):+ return 202, {"status": "accepted", "job_id": job_id}++ monkeypatch.setattr(+ "plugins.cron_providers.chronos.verify.get_fire_verifier",+ lambda: (lambda **kw: {"purpose": "cron_fire"}),+ )+ monkeypatch.setattr(web_server, "_find_cron_job_profile", lambda jid: "default")+ monkeypatch.setattr(web_server, "_forward_cron_fire_to_gateway", fake_forward)+ monkeypatch.setattr(+ web_server, "_call_cron_for_profile",+ lambda *a, **k: stamped.append(a),+ )++ client, pa, ph = _client(auth_required=False)+ try:+ resp = client.post("/api/cron/fire",+ headers={"Authorization": "Bearer nas-jwt"},+ json={"job_id": "j10"})+ assert resp.status_code == 202+ assert stamped == []+ finally:+ _restore(pa, ph)+ client.close()diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex dced41547cb..502dc4a74e9 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -638,6 +638,7 @@ def _format_job(job: Dict[str, Any]) -> Dict[str, Any]:"last_run_at": job.get("last_run_at"),"last_status": job.get("last_status"),"last_delivery_error": job.get("last_delivery_error"),+ "last_fire_error": job.get("last_fire_error"),"enabled": job.get("enabled", True),# Derive from enabled so half-paused records never render as paused."state": effective_job_state(job),diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 55166952158..a3dc7f5e2ba 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -2275,6 +2275,7 @@ export interface CronJob {last_status?: string | null;last_error?: string | null;last_delivery_error?: string | null;+ last_fire_error?: { at?: string | null; detail?: string | null } | null;}export interface CronDeliveryTarget {diff --git a/web/src/pages/CronPage.tsx b/web/src/pages/CronPage.tsxindex fed2013270d..b501d5675f2 100644--- a/web/src/pages/CronPage.tsx+++ b/web/src/pages/CronPage.tsx@@ -1159,6 +1159,12 @@ export default function CronPage() {delivery: {job.last_delivery_error}</p>)}+ {job.last_fire_error?.detail && (+ <p className="text-xs text-destructive mt-1">+ missed scheduled fire ({formatTime(job.last_fire_error.at ?? null)}):{" "}+ {job.last_fire_error.detail}+ </p>+ )}{job.last_error && (<p className="text-xs text-destructive mt-1">{job.last_error}diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 529b051a8e3..168d7e57d33 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -666,6 +666,18 @@ Cron jobs inherit your configured fallback providers and credential pool rotatioThis means cron jobs that run at high frequency or during peak hours are more resilient — a single rate-limited key won't fail the entire run.+## Missed scheduled fires (`last_fire_error`)++On hosted (managed-cron) deployments, a scheduled fire travels from the platform scheduler through the dashboard to the gateway's internal API server. If that final hand-off fails — the gateway process is down, or its API-server listener never started — the run never begins, so there is no execution record and no `last_status` to inspect. The tell-tale shape: the job works every time you trigger it manually, but never auto-fires.++These misses are stamped on the job record as `last_fire_error` (timestamp + reason) and surfaced by:++- `cronjob` tool → `action: "list"` — the `last_fire_error` field+- `hermes cron list` — a red `⚠ Missed scheduled fire:` line under the job+- The dashboard job view++The stamp always reflects **current** auto-fire health: it is overwritten by newer misses and cleared automatically by the next successful run. If you see it, the job and its schedule are fine — the gateway side of the fire path needs attention (most commonly, restart the gateway through its supervisor so it loads the full profile environment: `hermes gateway restart`).+## Schedule formatsThe agent's final response is automatically delivered to the job's `deliver:` target — the agent no longer fires messages itself, so the user-facing content simply goes in the final response. To deliver to **additional or different** targets, list multiple `deliver:` targets on the cron job (comma-separated, e.g. `deliver: "telegram,discord"`) rather than having the agent send them.