Skip to content

The agent that grows with you

refactor(hermes_cli): cron.py — split cron_list into _job_rows/_job_warnings/_last_run_display

Teknium7ff29f4837f1
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 293b58c8796..60d7ddf3dfb 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -168,98 +168,87 @@ def cron_list(show_all: bool = False):
_print_banner("Scheduled Jobs")
for job in jobs:
- job_id = job.get("id", "?")
# Scheduler-honoured flag — never show [paused] when enabled=true.
- state = effective_job_state(job)
- badge = _STATE_BADGES.get(state) or (
+ badge = _STATE_BADGES.get(effective_job_state(job)) or (
("[active]", Colors.GREEN) if job.get("enabled", True) else ("[disabled]", Colors.RED)
)
-
- # `repeat` / `deliver` may be present-but-null in the record (a one-shot persisted
- # with "repeat": null), so coalesce rather than rely on the dict-default, which only
- # applies to a missing key — a null deliver would crash `", ".join(None)`.
- repeat_info = job.get("repeat") or {}
- repeat_times = repeat_info.get("times")
- repeat_str = f"{repeat_info.get('completed', 0)}/{repeat_times}" if repeat_times else "∞"
- deliver = job.get("deliver") or ["local"]
- if isinstance(deliver, str):
- deliver = [deliver]
-
- rows = [
- ("Name", job.get("name", "(unnamed)")),
- ("Schedule", job.get("schedule_display", job.get("schedule", {}).get("value", "?"))),
- ("Repeat", repeat_str),
- ("Next run", job.get("next_run_at", "?")),
- ("Deliver", ", ".join(deliver)),
- ]
- skills = job.get("skills") or ([job["skill"]] if job.get("skill") else [])
- if skills:
- rows.append(("Skills", ", ".join(skills)))
- if job.get("script"):
- rows.append(("Script", job["script"]))
- monitor_source = job.get("monitor_script") or job.get("monitor_url")
- if monitor_source:
- rows.append(("Monitor", f"{monitor_source} (agent runs only on output change)"))
- mon_state = job.get("monitor_state") or {}
- if mon_state.get("last_changed_at"):
- rows.append(("Changed", mon_state["last_changed_at"]))
- if job.get("no_agent"):
- mode = color("no-agent", Colors.DIM) + " (script stdout delivered directly)"
- rows.append(("Mode", mode))
- if job.get("workdir"):
- rows.append(("Workdir", job["workdir"]))
-
- last_status = job.get("last_status")
- if last_status:
- if last_status == "ok":
- status_display = color("ok", Colors.GREEN)
- elif last_status == "delivery_failed":
- # Agent succeeded but the result never reached the user — not green; the
- # detail lives in last_delivery_error (last_error is None for these runs).
- detail = job.get("last_delivery_error") or "?"
- status_display = color(f"delivery_failed: {detail}", Colors.YELLOW)
- else:
- status_display = color(f"{last_status}: {job.get('last_error', '?')}", Colors.RED)
- streak = int(job.get("failure_streak") or 0)
- if streak >= 2:
- status_display += color(f" ({streak} failures in a row)", Colors.RED)
- rows.append(("Last run", f"{job.get('last_run_at', '?')} {status_display}"))
-
- dispatch_line = _dispatch_display(job.get("last_dispatch"))
- if dispatch_line:
- rows.append(("Dispatch", dispatch_line))
- latest_execution = job.get("latest_execution")
- if latest_execution:
- rows.append((
- "Execution",
- f"{latest_execution.get('status', '?')} {latest_execution.get('id', '?')}",
- ))
-
- print(f" {color(job_id, Colors.YELLOW)} {color(*badge)}")
- for label, value in rows:
+ print(f" {color(job.get('id', '?'), Colors.YELLOW)} {color(*badge)}")
+ for label, value in _job_rows(job):
print(f" {label + ':':<11}{value}")
-
- delivery_err = job.get("last_delivery_error")
- if delivery_err:
- print(f" {color('⚠ Delivery failed:', Colors.YELLOW)} {delivery_err}")
-
- # A live adapter acked the last send but returned no message_id / raw_response
- # (Slack/Matrix/Mattermost shape): accepted as delivered, but say so here.
- unverified = job.get("last_delivery_unverified")
- if unverified:
- print(f" {color('⚠ Delivery UNVERIFIED:', Colors.YELLOW)} adapter acked "
- f"{_unverified_targets(unverified)} without message_id/raw_response")
-
- 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']}")
-
+ for line in _job_warnings(job):
+ print(f" {line}")
print()
_warn_if_gateway_not_running()
+def _last_run_display(job: Dict[str, Any]) -> str:
+ last_status = job["last_status"]
+ if last_status == "ok":
+ return color("ok", Colors.GREEN)
+ if last_status == "delivery_failed":
+ # Agent succeeded but the result never reached the user — not green; the detail
+ # lives in last_delivery_error (last_error is None for these runs).
+ return color(f"delivery_failed: {job.get('last_delivery_error') or '?'}", Colors.YELLOW)
+ display = color(f"{last_status}: {job.get('last_error', '?')}", Colors.RED)
+ streak = int(job.get("failure_streak") or 0)
+ if streak >= 2:
+ display += color(f" ({streak} failures in a row)", Colors.RED)
+ return display
+
+
+def _job_rows(job: Dict[str, Any]) -> List[tuple[str, str]]:
+ """``(label, value)`` detail rows for one job in ``cron list``."""
+ # `repeat` / `deliver` may be present-but-null in the record (a one-shot persisted with
+ # "repeat": null), so coalesce rather than rely on the dict-default, which only applies
+ # to a missing key — a null deliver would crash `", ".join(None)`.
+ repeat_info = job.get("repeat") or {}
+ repeat_times = repeat_info.get("times")
+ deliver = job.get("deliver") or ["local"]
+ skills = job.get("skills") or ([job["skill"]] if job.get("skill") else [])
+ monitor_source = job.get("monitor_script") or job.get("monitor_url")
+ mon_state = job.get("monitor_state") or {}
+ latest_execution = job.get("latest_execution") or {}
+ optional = [
+ ("Skills", ", ".join(skills) if skills else ""),
+ ("Script", job.get("script")),
+ ("Monitor", f"{monitor_source} (agent runs only on output change)" if monitor_source else ""),
+ ("Changed", mon_state.get("last_changed_at") if monitor_source else ""),
+ ("Mode", color("no-agent", Colors.DIM) + " (script stdout delivered directly)"
+ if job.get("no_agent") else ""),
+ ("Workdir", job.get("workdir")),
+ ("Last run", f"{job.get('last_run_at', '?')} {_last_run_display(job)}"
+ if job.get("last_status") else ""),
+ ("Dispatch", _dispatch_display(job.get("last_dispatch"))),
+ ("Execution", f"{latest_execution.get('status', '?')} {latest_execution.get('id', '?')}"
+ if latest_execution else ""),
+ ]
+ return [
+ ("Name", job.get("name", "(unnamed)")),
+ ("Schedule", job.get("schedule_display", job.get("schedule", {}).get("value", "?"))),
+ ("Repeat", f"{repeat_info.get('completed', 0)}/{repeat_times}" if repeat_times else "∞"),
+ ("Next run", job.get("next_run_at", "?")),
+ ("Deliver", deliver if isinstance(deliver, str) else ", ".join(deliver)),
+ ] + [(label, value) for label, value in optional if value]
+
+
+def _job_warnings(job: Dict[str, Any]) -> List[str]:
+ """Delivery / fire warning lines for one job in ``cron list``."""
+ lines = []
+ if job.get("last_delivery_error"):
+ lines.append(f"{color('⚠ Delivery failed:', Colors.YELLOW)} {job['last_delivery_error']}")
+ # A live adapter acked the last send but returned no message_id / raw_response
+ # (Slack/Matrix/Mattermost shape): accepted as delivered, but say so here.
+ if unverified := job.get("last_delivery_unverified"):
+ lines.append(f"{color('⚠ Delivery UNVERIFIED:', Colors.YELLOW)} adapter acked "
+ f"{_unverified_targets(unverified)} without message_id/raw_response")
+ fire_err = job.get("last_fire_error")
+ if isinstance(fire_err, dict) and fire_err.get("detail"):
+ lines.append(f"{color('⚠ Missed scheduled fire:', Colors.RED)} "
+ f"{fire_err.get('at', '?')} {fire_err['detail']}")
+ return lines
+
+
def cron_tick():
"""Run due jobs once and exit."""
from cron.scheduler import CronTickYielded, tick