Skip to content

The agent that grows with you

fix(cron): keep a sticky last_failure stamp so a healed run stays visible

salch-crede70801e736a3
diff --git a/cron/jobs.py b/cron/jobs.py
index 56e83305819..b3321f21f57 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1919,6 +1919,8 @@ def create_job(
"last_delivery_error": None,
# Targets acked without message_id/raw_response (accepted but UNVERIFIED).
"last_delivery_unverified": None,
+ # Most recent failed run ({at, detail}); NOT cleared by a later success (#118354).
+ "last_failure": None,
"failure_streak": 0,
"deliver": deliver,
"origin": origin, # Tracks where job was created for "origin" delivery
@@ -2396,6 +2398,12 @@ def _record_run_outcome(
# Consecutive agent-failure streak; delivery failures do NOT count
# (scheduler._failure_streak_nudge).
job["failure_streak"] = int(job.get("failure_streak") or 0) + 1
+ # Sticky last-failure stamp (#118354): the next success resets last_status and
+ # failure_streak, which erases the only job-level trace that a run ever failed —
+ # a monitor sampling jobs.json then sees a permanently green job. last_failure
+ # survives success (latest failure wins); the recency window is the consumer's
+ # call. Delivery failures keep their own sticky last_delivery_error.
+ job["last_failure"] = {"at": now, "detail": error or (status or "run failed")}
job["last_delivery_error"] = delivery_error
# Clear both claims: the run is over, so the job is claimable again.
job["fire_claim"] = None
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index c73465fab94..f1403a40289 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -294,6 +294,17 @@ def _job_warnings(job: Dict[str, Any]) -> List[str]:
fire_err = job.get("last_fire_error")
if isinstance(fire_err, dict) and fire_err.get("detail"):
lines.append(color(f"⚠ {_missed_fire_issue(job, fire_err)}", Colors.RED))
+ # Sticky last-failure stamp (#118354): survives a later success, so a job that
+ # self-healed still shows that a run failed recently. While last_status itself
+ # reports the failure this is redundant-but-consistent; after recovery it is the
+ # only job-level trace left.
+ last_failure = job.get("last_failure")
+ if isinstance(last_failure, dict) and last_failure.get("detail"):
+ recovered = str(job.get("last_status") or "") in {"ok", "delivery_queued"}
+ lines.append(color(
+ f"⚠ Last failure at {last_failure.get('at', '?')}: "
+ f"{_short_reason(last_failure['detail'])}" + (" — recovered since" if recovered else ""),
+ Colors.YELLOW if recovered else Colors.RED))
return lines
diff --git a/tests/cron/test_last_failure_stamp.py b/tests/cron/test_last_failure_stamp.py
new file mode 100644
index 00000000000..2aff7ecd3e0
--- /dev/null
+++ b/tests/cron/test_last_failure_stamp.py
@@ -0,0 +1,77 @@
+"""Tests for the sticky ``last_failure`` stamp (#118354).
+
+A failed cron run is recorded correctly (``last_status="error"``,
+``failure_streak`` climbing), but the next successful run resets both in the
+same pass — so a monitor sampling ``jobs.json`` after the fact sees a
+permanently green job and a relapse is invisible. ``last_failure`` now keeps
+the most recent failure (``{at, detail}``) on the job record and a later
+success does NOT clear it; the recency window is the consumer's call.
+"""
+
+from datetime import datetime
+
+import pytest
+
+from cron.jobs import create_job, get_job, mark_job_run
+
+
+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 TestLastFailureStamp:
+ def test_failed_run_stamps_last_failure(self, tmp_cron_dir):
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ assert mark_job_run(job["id"], success=False, error="Script exited with code 1") is True
+
+ stamp = get_job(job["id"])["last_failure"]
+ assert isinstance(stamp, dict)
+ assert stamp["detail"] == "Script exited with code 1"
+ # Timestamp parses as ISO.
+ datetime.fromisoformat(stamp["at"])
+
+ def test_success_resets_status_but_keeps_stamp(self, tmp_cron_dir):
+ """The heart of #118354: the healing success must not erase the failure."""
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ assert mark_job_run(job["id"], success=False, error="Script exited with code 1") is True
+ failed = get_job(job["id"])
+ assert failed["last_status"] == "error"
+ assert failed["failure_streak"] == 1
+
+ assert mark_job_run(job["id"], success=True) is True
+ healed = get_job(job["id"])
+ assert healed["last_status"] == "ok"
+ assert healed["failure_streak"] == 0
+ assert healed["last_failure"]["detail"] == "Script exited with code 1"
+
+ def test_latest_failure_wins(self, tmp_cron_dir):
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ mark_job_run(job["id"], success=False, error="first failure")
+ mark_job_run(job["id"], success=True)
+ mark_job_run(job["id"], success=False, error="second failure")
+ assert get_job(job["id"])["last_failure"]["detail"] == "second failure"
+
+ def test_success_without_prior_failure_leaves_no_stamp(self, tmp_cron_dir):
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ assert mark_job_run(job["id"], success=True) is True
+ assert get_job(job["id"]).get("last_failure") is None
+
+ def test_failure_without_error_text_uses_status(self, tmp_cron_dir):
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ assert mark_job_run(job["id"], success=False, status="blocked_config") is True
+ assert get_job(job["id"])["last_failure"]["detail"] == "blocked_config"
+
+ def test_delivery_failure_keeps_its_own_channel(self, tmp_cron_dir):
+ """Agent succeeded but delivery failed: success-path (no stamp), the sticky
+ ``last_delivery_error`` already covers that case."""
+ job = create_job(prompt="Watch the fleet", schedule="every 1h")
+ assert mark_job_run(
+ job["id"], success=True, delivery_error="webhook unreachable") is True
+ record = get_job(job["id"])
+ assert record.get("last_failure") is None
+ assert record["last_delivery_error"] == "webhook unreachable"