Skip to content

The agent that grows with you

refactor(kanban-cli): compact diagnostics rule engine — shared cli_hint/payload-id/run-order helpers, asdict, triage slot table

Tekniume085147f574f
diff --git a/hermes_cli/kanban_diagnostics.py b/hermes_cli/kanban_diagnostics.py
index 61d1e201ce6..f5aab6d8b9e 100644
--- a/hermes_cli/kanban_diagnostics.py
+++ b/hermes_cli/kanban_diagnostics.py
@@ -3,16 +3,14 @@
A ``Diagnostic`` carries a **kind** (canonical code the UI/tests match on), a
**severity**, title/detail text, and **actions** the dashboard renders as
buttons and the CLI as hints. Rules are stateless and read-only over
-(task, events, runs, optional graph); callers compute on demand.
-
-Design goals: operator-fixable signals only (not a one-off provider 502);
-every diagnostic has at least one recovery action; diagnostics auto-clear
-when the failure mode resolves (the audit event trail stays).
+(task, events, runs, optional graph); callers compute on demand. Only
+operator-fixable signals (not a one-off provider 502); every diagnostic has a
+recovery action and auto-clears when the failure mode resolves.
"""
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Iterable, Optional
import json
import time
@@ -44,12 +42,7 @@ class DiagnosticAction:
suggested: bool = False
def to_dict(self) -> dict:
- return {
- "kind": self.kind,
- "label": self.label,
- "payload": self.payload,
- "suggested": self.suggested,
- }
+ return asdict(self)
@dataclass
@@ -64,24 +57,11 @@ class Diagnostic:
first_seen_at: int = 0
last_seen_at: int = 0
count: int = 1
- # Optional: the run id this diagnostic is scoped to. None = task-wide.
- run_id: Optional[int] = None
- # Optional structured payload for the UI (phantom ids, failure count).
- data: dict = field(default_factory=dict)
+ run_id: Optional[int] = None # None = task-wide
+ data: dict = field(default_factory=dict) # structured payload for the UI
def to_dict(self) -> dict:
- return {
- "kind": self.kind,
- "severity": self.severity,
- "title": self.title,
- "detail": self.detail,
- "actions": [a.to_dict() for a in self.actions],
- "first_seen_at": self.first_seen_at,
- "last_seen_at": self.last_seen_at,
- "count": self.count,
- "run_id": self.run_id,
- "data": self.data,
- }
+ return asdict(self)
# ---------------------------------------------------------------------------
@@ -105,8 +85,6 @@ def _task_field(task, name, default=None):
def _parse_payload(ev) -> dict:
"""Tolerate event.payload being either a dict or a JSON string."""
p = _task_field(ev, "payload", None)
- if p is None:
- return {}
if isinstance(p, dict):
return p
if isinstance(p, str):
@@ -122,8 +100,7 @@ def _event_kind(ev) -> str:
def _event_ts(ev) -> int:
- t = _task_field(ev, "created_at", 0)
- return int(t or 0)
+ return int(_task_field(ev, "created_at", 0) or 0)
def _first_field(task, primary: str, legacy: str, default=None):
@@ -134,20 +111,16 @@ def _first_field(task, primary: str, legacy: str, default=None):
def _latest_event_ts(events: Iterable[Any], kinds: set[str]) -> int:
"""Max ``created_at`` over events whose kind is in ``kinds`` (0 if none)."""
- latest = 0
- for ev in events:
- if _event_kind(ev) in kinds:
- latest = max(latest, _event_ts(ev))
- return latest
+ return max([0, *(_event_ts(ev) for ev in events if _event_kind(ev) in kinds)])
+
+
+def _cli_hint(label: str, command: str, *, suggested: bool = False) -> DiagnosticAction:
+ return DiagnosticAction(kind="cli_hint", label=label, payload={"command": command}, suggested=suggested)
def _log_hint_action(task_id: str) -> DiagnosticAction:
- return DiagnosticAction(
- kind="cli_hint",
- label=f"Check logs: hermes kanban log {task_id}",
- payload={"command": f"hermes kanban log {task_id}"},
- suggested=True,
- )
+ cmd = f"hermes kanban log {task_id}"
+ return _cli_hint(f"Check logs: {cmd}", cmd, suggested=True)
def _error_snippet(last_err) -> str:
@@ -156,10 +129,7 @@ def _error_snippet(last_err) -> str:
return err_text[:500] + ("…" if len(err_text) > 500 else "") if err_text else ""
-def _active_hallucination_events(
- events: Iterable[Any],
- kind: str,
-) -> list[Any]:
+def _active_hallucination_events(events: Iterable[Any], kind: str) -> list[Any]:
"""Events of ``kind`` with no ``completed``/``edited`` event strictly after
them. Requires id-sorted (arrival-order) input, which the DB provides."""
active: list[Any] = []
@@ -172,23 +142,37 @@ def _active_hallucination_events(
return active
-# Baseline recovery primitives every diagnostic can fall back on.
+def _unique_payload_ids(hits: list[Any], key: str) -> list[str]:
+ """Ordered, de-duplicated ``payload[key]`` entries across ``hits``."""
+ out: list[str] = []
+ for ev in hits:
+ for pid in _parse_payload(ev).get(key, []) or []:
+ if pid not in out:
+ out.append(pid)
+ return out
+
+
def _generic_recovery_actions(task: Any, *, running: bool) -> list[DiagnosticAction]:
+ """Baseline recovery primitives every diagnostic can fall back on."""
out: list[DiagnosticAction] = []
if running:
- out.append(DiagnosticAction(
- kind="reclaim",
- label="Reclaim task",
- payload={},
- ))
+ out.append(DiagnosticAction(kind="reclaim", label="Reclaim task", payload={}))
out.append(DiagnosticAction(
- kind="reassign",
- label="Reassign to different profile",
- payload={"reclaim_first": running},
+ kind="reassign", label="Reassign to different profile", payload={"reclaim_first": running},
))
return out
+def _is_running(task) -> bool:
+ return _task_field(task, "status") == "running"
+
+
+def _runs_newest_first(runs) -> list[Any]:
+ # reversed(sorted()) not sorted(reverse=True): equal ids must keep the
+ # last-listed run first.
+ return list(reversed(sorted(runs, key=lambda r: _task_field(r, "id", 0))))
+
+
# ---------------------------------------------------------------------------
# Rule implementations
# ---------------------------------------------------------------------------
@@ -208,10 +192,7 @@ def _aux_slot_explicit(slot: Any) -> bool:
provider = str(slot.get("provider") or "").strip().lower()
if provider and provider != "auto":
return True
- for key in ("model", "base_url", "api_key"):
- if str(slot.get(key) or "").strip():
- return True
- return False
+ return any(str(slot.get(key) or "").strip() for key in ("model", "base_url", "api_key"))
def _main_model_visible(raw_config: Any) -> bool:
@@ -223,12 +204,7 @@ def _main_model_visible(raw_config: Any) -> bool:
model_cfg = raw_config.get("model")
if isinstance(model_cfg, dict):
provider = str(model_cfg.get("provider") or "").strip()
- model = str(
- model_cfg.get("default")
- or model_cfg.get("model")
- or model_cfg.get("name")
- or ""
- ).strip()
+ model = str(model_cfg.get("default") or model_cfg.get("model") or model_cfg.get("name") or "").strip()
return bool(provider and model)
return bool(str(model_cfg or "").strip())
@@ -239,37 +215,21 @@ def triage_aux_status(config: Optional[dict]) -> Optional[dict]:
when no config context is present (keeps low-level callers/tests silent)."""
if not isinstance(config, dict):
return None
-
explicit = config.get("triage_aux_status")
if isinstance(explicit, dict):
return explicit
aux = config.get("auxiliary")
kanban_cfg = config.get("kanban") if isinstance(config.get("kanban"), dict) else {}
-
# No auxiliary/kanban/model keys at all => a low-level caller passing {}.
- if (
- not isinstance(aux, dict)
- and not kanban_cfg
- and "model" not in config
- ):
+ if not isinstance(aux, dict) and not kanban_cfg and "model" not in config:
return None
-
- decomposer_explicit = False
- specifier_explicit = False
- if isinstance(aux, dict):
- decomposer_explicit = _aux_slot_explicit(aux.get("kanban_decomposer"))
- specifier_explicit = _aux_slot_explicit(aux.get("triage_specifier"))
-
- # ``auto_decompose`` defaults to True per kanban DEFAULT_CONFIG.
- auto_decompose = True
- if isinstance(kanban_cfg, dict) and "auto_decompose" in kanban_cfg:
- auto_decompose = bool(kanban_cfg.get("auto_decompose"))
-
+ aux = aux if isinstance(aux, dict) else {}
return {
- "auto_decompose": auto_decompose,
- "decomposer_explicit": decomposer_explicit,
- "specifier_explicit": specifier_explicit,
+ # ``auto_decompose`` defaults to True per kanban DEFAULT_CONFIG.
+ "auto_decompose": bool(kanban_cfg["auto_decompose"]) if "auto_decompose" in kanban_cfg else True,
+ "decomposer_explicit": _aux_slot_explicit(aux.get("kanban_decomposer")),
+ "specifier_explicit": _aux_slot_explicit(aux.get("triage_specifier")),
"main_model_visible": _main_model_visible(config),
}
@@ -288,20 +248,11 @@ def _rule_hallucinated_cards(task, events, runs, now, cfg) -> list[Diagnostic]:
hits = _active_hallucination_events(events, "completion_blocked_hallucination")
if not hits:
return []
- phantom_ids: list[str] = []
- first = _event_ts(hits[0])
- last = _event_ts(hits[-1])
- for ev in hits:
- payload = _parse_payload(ev)
- for pid in payload.get("phantom_cards", []) or []:
- if pid not in phantom_ids:
- phantom_ids.append(pid)
- running = _task_field(task, "status") == "running"
actions = [DiagnosticAction(
kind="comment",
label="Add a comment explaining what to do",
suggested=False,
- )] + _generic_recovery_actions(task, running=running)
+ )] + _generic_recovery_actions(task, running=_is_running(task))
return [Diagnostic(
kind="hallucinated_cards",
severity="error",
@@ -314,13 +265,29 @@ def _rule_hallucinated_cards(task, events, runs, now, cfg) -> list[Diagnostic]:
"return values from kanban_create."
),
actions=actions,
- first_seen_at=first,
- last_seen_at=last,
+ first_seen_at=_event_ts(hits[0]),
+ last_seen_at=_event_ts(hits[-1]),
count=len(hits),
- data={"phantom_ids": phantom_ids},
+ data={"phantom_ids": _unique_payload_ids(hits, "phantom_cards")},
)]
+# (primary_slot, fallback_slot, primary_desc, detail_path) keyed by auto_decompose.
+_TRIAGE_SLOTS = {
+ True: (
+ "auxiliary.kanban_decomposer", "auxiliary.triage_specifier", "decomposer",
+ "Auto-decompose is on, so the dispatcher needs "
+ "auxiliary.kanban_decomposer (with auxiliary.triage_specifier as "
+ "a fallback for non-fan-out tasks).",
+ ),
+ False: (
+ "auxiliary.triage_specifier", "auxiliary.kanban_decomposer", "specifier",
+ "Auto-decompose is off, so triage tasks need "
+ "`hermes kanban specify`, which uses auxiliary.triage_specifier.",
+ ),
+}
+
+
def _rule_triage_aux_unavailable(task, events, runs, now, cfg) -> list[Diagnostic]:
"""A triage task can't leave triage without a usable aux model. With
auto-decompose on the primary slot is ``auxiliary.kanban_decomposer``
@@ -330,7 +297,6 @@ def _rule_triage_aux_unavailable(task, events, runs, now, cfg) -> list[Diagnosti
context ({} keeps it silent)."""
if _task_field(task, "status") != "triage":
return []
-
status = triage_aux_status(cfg)
if status is None:
return []
@@ -339,62 +305,25 @@ def _rule_triage_aux_unavailable(task, events, runs, now, cfg) -> list[Diagnosti
decomposer_explicit = bool(status.get("decomposer_explicit"))
specifier_explicit = bool(status.get("specifier_explicit"))
main_visible = bool(status.get("main_model_visible"))
-
- # Determine the primary slot and whether it is usable.
- if auto_decompose:
- primary_slot = "auxiliary.kanban_decomposer"
- primary_explicit = decomposer_explicit
- fallback_slot = "auxiliary.triage_specifier"
- fallback_explicit = specifier_explicit
- primary_desc = "decomposer"
- detail_path = (
- "Auto-decompose is on, so the dispatcher needs "
- "auxiliary.kanban_decomposer (with auxiliary.triage_specifier as "
- "a fallback for non-fan-out tasks)."
- )
- else:
- primary_slot = "auxiliary.triage_specifier"
- primary_explicit = specifier_explicit
- fallback_slot = "auxiliary.kanban_decomposer"
- fallback_explicit = decomposer_explicit
- primary_desc = "specifier"
- detail_path = (
- "Auto-decompose is off, so triage tasks need "
- "`hermes kanban specify`, which uses auxiliary.triage_specifier."
- )
-
+ primary_slot, fallback_slot, primary_desc, detail_path = _TRIAGE_SLOTS[auto_decompose]
+ primary_explicit, fallback_explicit = (
+ (decomposer_explicit, specifier_explicit) if auto_decompose
+ else (specifier_explicit, decomposer_explicit)
+ )
if primary_explicit or main_visible:
return []
task_id = _task_field(task, "id") or "<task_id>"
- actions = [
- DiagnosticAction(
- kind="cli_hint",
- label=f"Configure {primary_slot}",
- payload={
- "command": (
- f"hermes config set {primary_slot}.provider auto"
- )
- },
- suggested=True,
- ),
- ]
+ actions = [_cli_hint(
+ f"Configure {primary_slot}", f"hermes config set {primary_slot}.provider auto", suggested=True,
+ )]
if not fallback_explicit and not main_visible:
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label=f"Or configure fallback {fallback_slot}",
- payload={
- "command": (
- f"hermes config set {fallback_slot}.provider auto"
- )
- },
+ actions.append(_cli_hint(
+ f"Or configure fallback {fallback_slot}", f"hermes config set {fallback_slot}.provider auto",
))
if not auto_decompose:
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label=f"Specify manually: hermes kanban specify {task_id}",
- payload={"command": f"hermes kanban specify {task_id}"},
- ))
+ cmd = f"hermes kanban specify {task_id}"
+ actions.append(_cli_hint(f"Specify manually: {cmd}", cmd))
return [Diagnostic(
kind="triage_aux_unavailable",
@@ -426,12 +355,6 @@ def _rule_prose_phantom_refs(task, events, runs, now, cfg) -> list[Diagnostic]:
hits = _active_hallucination_events(events, "suspected_hallucinated_references")
if not hits:
return []
- phantom_refs: list[str] = []
- for ev in hits:
- for pid in _parse_payload(ev).get("phantom_refs", []) or []:
- if pid not in phantom_refs:
- phantom_refs.append(pid)
- running = _task_field(task, "status") == "running"
return [Diagnostic(
kind="prose_phantom_refs",
severity="warning",
@@ -442,14 +365,22 @@ def _rule_prose_phantom_refs(task, events, runs, now, cfg) -> list[Diagnostic]:
"but downstream consumers parsing the summary may be pointed "
"at cards that never existed."
),
- actions=_generic_recovery_actions(task, running=running),
+ actions=_generic_recovery_actions(task, running=_is_running(task)),
first_seen_at=_event_ts(hits[0]),
last_seen_at=_event_ts(hits[-1]),
count=len(hits),
- data={"phantom_refs": phantom_refs},
+ data={"phantom_refs": _unique_payload_ids(hits, "phantom_refs")},
)]
+def _failure_threshold(cfg: dict) -> Any:
+ """``failure_threshold`` with the legacy ``spawn_failure_threshold`` alias."""
+ return cfg.get("failure_threshold", cfg.get("spawn_failure_threshold", 3))
+
+
+_OUTCOME_LABELS = {"spawn_failed": "spawn", "timed_out": "timeout", "crashed": "crash"}
+
+
def _rule_repeated_failures(task, events, runs, now, cfg) -> list[Diagnostic]:
"""``consecutive_failures`` >= cfg["failure_threshold"] (legacy key
``spawn_failure_threshold``), regardless of failure mode — the kernel keeps
@@ -461,10 +392,7 @@ def _rule_repeated_failures(task, events, runs, now, cfg) -> list[Diagnostic]:
if it fails too)."""
if _task_field(task, "status") in ("done", "archived", "running"):
return []
- threshold = _positive_int(cfg.get(
- "failure_threshold",
- cfg.get("spawn_failure_threshold", 3),
- ), 3)
+ threshold = _positive_int(_failure_threshold(cfg), 3)
failure_limit = _positive_int(cfg.get("failure_limit"), threshold)
failures = _first_field(task, "consecutive_failures", "spawn_failures", 0)
if failures is None or failures < threshold:
@@ -473,45 +401,29 @@ def _rule_repeated_failures(task, events, runs, now, cfg) -> list[Diagnostic]:
assignee = _task_field(task, "assignee")
# Most recent failure outcome makes the title/action specific.
- ordered_runs = sorted(runs, key=lambda r: _task_field(r, "id", 0))
- most_recent_outcome = None
- for r in reversed(ordered_runs):
- oc = _task_field(r, "outcome")
- if oc in {"spawn_failed", "timed_out", "crashed"}:
- most_recent_outcome = oc
- break
+ most_recent_outcome = next(
+ (oc for oc in (_task_field(r, "outcome") for r in _runs_newest_first(runs))
+ if oc in {"spawn_failed", "timed_out", "crashed"}),
+ None,
+ )
actions: list[DiagnosticAction] = []
if most_recent_outcome == "spawn_failed" and assignee and assignee != "default":
# Spawn is failing specifically — profile setup issue.
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label=f"Verify profile: hermes -p {assignee} doctor",
- payload={"command": f"hermes -p {assignee} doctor"},
- suggested=True,
- ))
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label=f"Fix profile auth: hermes -p {assignee} auth",
- payload={"command": f"hermes -p {assignee} auth"},
+ actions.append(_cli_hint(
+ f"Verify profile: hermes -p {assignee} doctor", f"hermes -p {assignee} doctor", suggested=True,
))
+ actions.append(_cli_hint(f"Fix profile auth: hermes -p {assignee} auth", f"hermes -p {assignee} auth"))
elif most_recent_outcome in {"timed_out", "crashed"}:
- # Worker got off the ground but died. Logs are the right place
- # to diagnose; reclaim/reassign are the recovery levers.
+ # Worker got off the ground but died: logs diagnose, reclaim/reassign recover.
task_id = _task_field(task, "id")
if task_id:
actions.append(_log_hint_action(task_id))
- actions.extend(_generic_recovery_actions(
- task, running=_task_field(task, "status") == "running",
- ))
+ actions.extend(_generic_recovery_actions(task, running=_is_running(task)))
severity = "critical" if failures >= threshold * 2 else "error"
err_snippet = _error_snippet(last_err)
- outcome_label = {
- "spawn_failed": "spawn",
- "timed_out": "timeout",
- "crashed": "crash",
- }.get(most_recent_outcome or "", "failure")
+ outcome_label = _OUTCOME_LABELS.get(most_recent_outcome or "", "failure")
if err_snippet:
title = f"Agent {outcome_label} x{failures}: {err_snippet.splitlines()[0][:160]}"
detail = (
@@ -559,42 +471,30 @@ def _rule_repeated_crashes(task, events, runs, now, cfg) -> list[Diagnostic]:
and wouldn't break the scan)."""
if _task_field(task, "status") in ("done", "archived", "running"):
return []
- failure_threshold = int(cfg.get(
- "failure_threshold",
- cfg.get("spawn_failure_threshold", 3),
- ))
- unified_counter = (
- _task_field(task, "consecutive_failures", 0) or 0
- )
# Unified rule will catch this — let it handle to avoid double fire.
- if unified_counter >= failure_threshold:
+ if (_task_field(task, "consecutive_failures", 0) or 0) >= int(_failure_threshold(cfg)):
return []
threshold = int(cfg.get("crash_threshold", 2))
- ordered = sorted(runs, key=lambda r: _task_field(r, "id", 0))
- # Count trailing consecutive 'crashed' outcomes.
+ # Count trailing consecutive 'crashed' outcomes; a success (or manual
+ # reclaim) breaks the streak, other outcomes neither count nor break it.
consecutive = 0
last_err = None
- for r in reversed(ordered):
+ for r in _runs_newest_first(runs):
outcome = _task_field(r, "outcome")
if outcome == "crashed":
consecutive += 1
if last_err is None:
last_err = _task_field(r, "error")
elif outcome in {"completed", "reclaimed"}:
- # A success (or manual reclaim) breaks the streak.
break
- else:
- # Other outcomes neither count as crashes nor break the streak.
- continue
if consecutive < threshold:
return []
task_id = _task_field(task, "id")
actions: list[DiagnosticAction] = []
if task_id:
actions.append(_log_hint_action(task_id))
- running = _task_field(task, "status") == "running"
- actions.extend(_generic_recovery_actions(task, running=running))
+ actions.extend(_generic_recovery_actions(task, running=_is_running(task)))
severity = "critical" if consecutive >= threshold * 2 else "error"
# Error up-front so operators see WHAT broke without opening the logs.
err_snippet = _error_snippet(last_err)
@@ -629,11 +529,7 @@ def _rule_review_dependency_deadlock(task, events, runs, now, cfg) -> list[Diagn
for it to be terminal. Graph-aware; deliberately mutates nothing."""
if _task_field(task, "status") != "blocked":
return []
-
- latest_block = None
- for event in events:
- if _event_kind(event) == "blocked":
- latest_block = event
+ latest_block = next((ev for ev in reversed(list(events)) if _event_kind(ev) == "blocked"), None)
if latest_block is None:
return []
reason = str(_parse_payload(latest_block).get("reason") or "").strip()
@@ -644,32 +540,22 @@ def _rule_review_dependency_deadlock(task, events, runs, now, cfg) -> list[Diagn
if not isinstance(graph, dict):
return []
waiting_children = [
- child
- for child in (graph.get("children") or [])
+ child for child in (graph.get("children") or [])
if isinstance(child, dict) and child.get("status") == "todo"
]
if not waiting_children:
return []
task_id = str(_task_field(task, "id") or "")
- child_ids = [
- str(child.get("id"))
- for child in waiting_children
- if child.get("id")
- ]
+ child_ids = [str(child.get("id")) for child in waiting_children if child.get("id")]
actions: list[DiagnosticAction] = []
if task_id:
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label="Complete the finished implementation phase",
- payload={"command": f"hermes kanban complete {task_id}"},
- suggested=True,
+ actions.append(_cli_hint(
+ "Complete the finished implementation phase", f"hermes kanban complete {task_id}", suggested=True,
))
if task_id and child_ids:
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label="Or unlink the incorrectly gated reviewer",
- payload={"command": f"hermes kanban unlink {task_id} {child_ids[0]}"},
+ actions.append(_cli_hint(
+ "Or unlink the incorrectly gated reviewer", f"hermes kanban unlink {task_id} {child_ids[0]}",
))
blocked_at = _event_ts(latest_block) or now
@@ -700,8 +586,7 @@ def _rule_stuck_in_blocked(task, events, runs, now, cfg) -> list[Diagnostic]:
"""Blocked for >= cfg["blocked_stale_hours"] (default 24) with no comment
or unblock since the last ``blocked`` event."""
hours = float(cfg.get("blocked_stale_hours", 24))
- status = _task_field(task, "status")
- if status != "blocked":
+ if _task_field(task, "status") != "blocked":
return []
last_blocked_ts = _latest_event_ts(events, {"blocked"})
if last_blocked_ts == 0:
@@ -710,16 +595,8 @@ def _rule_stuck_in_blocked(task, events, runs, now, cfg) -> list[Diagnostic]:
if age_hours < hours:
return []
# Any comment / unblock after the block breaks the "stale" signal.
- for ev in events:
- if _event_kind(ev) in {"commented", "unblocked"} and _event_ts(ev) > last_blocked_ts:
- return []
- actions: list[DiagnosticAction] = [
- DiagnosticAction(
- kind="comment",
- label="Add a comment / unblock the task",
- suggested=True,
- ),
- ]
+ if any(_event_kind(ev) in {"commented", "unblocked"} and _event_ts(ev) > last_blocked_ts for ev in events):
+ return []
return [Diagnostic(
kind="stuck_in_blocked",
severity="warning",
@@ -730,7 +607,7 @@ def _rule_stuck_in_blocked(task, events, runs, now, cfg) -> list[Diagnostic]:
f"are waiting for human input — check the block reason and "
f"either unblock with feedback or answer with a comment."
),
- actions=actions,
+ actions=[DiagnosticAction(kind="comment", label="Add a comment / unblock the task", suggested=True)],
first_seen_at=last_blocked_ts,
last_seen_at=last_blocked_ts,
count=1,
@@ -775,12 +652,8 @@ def _rule_block_unblock_cycling(task, events, runs, now, cfg) -> list[Diagnostic
task_id = _task_field(task, "id")
actions: list[DiagnosticAction] = []
if task_id:
- actions.append(DiagnosticAction(
- kind="cli_hint",
- label=f"Check block reasons: hermes kanban events {task_id}",
- payload={"command": f"hermes kanban events {task_id}"},
- suggested=True,
- ))
+ cmd = f"hermes kanban events {task_id}"
+ actions.append(_cli_hint(f"Check block reasons: {cmd}", cmd, suggested=True))
return [Diagnostic(
kind="block_unblock_cycling",
severity="warning",
@@ -796,10 +669,7 @@ def _rule_block_unblock_cycling(task, events, runs, now, cfg) -> list[Diagnostic
first_seen_at=int(initial_blocked_ts) if initial_blocked_ts else int(now),
last_seen_at=int(last_cycle_blocked_ts) if last_cycle_blocked_ts else int(now),
count=cycles,
- data={
- "cycles": cycles,
- "window_seconds": int(window_seconds),
- },
+ data={"cycles": cycles, "window_seconds": int(window_seconds)},
)]
@@ -809,11 +679,8 @@ def _rule_stranded_in_ready(task, events, runs, now, cfg) -> list[Diagnostic]:
catches typo'd assignees, deleted profiles, and down external worker
pools alike without a registry to curate. Unassigned tasks are excluded —
the dispatcher's ``skipped_unassigned`` already covers them."""
- threshold_seconds = float(
- cfg.get("stranded_threshold_seconds", 30 * 60)
- )
- status = _task_field(task, "status")
- if status != "ready":
+ threshold_seconds = float(cfg.get("stranded_threshold_seconds", 30 * 60))
+ if _task_field(task, "status") != "ready":
return []
# A live claim means it's being worked on even without progress yet.
if _task_field(task, "claim_lock"):
@@ -822,13 +689,10 @@ def _rule_stranded_in_ready(task, events, runs, now, cfg) -> list[Diagnostic]:
if not assignee.strip():
return []
- # Most recent event that put the task into ready.
- last_ready_ts = _latest_event_ts(
- events, {"created", "promoted", "reclaimed", "unblocked"},
- )
-
- # No qualifying event (old task / truncated events): fall back to
- # created_at — over-flagging an ancient task beats missing a stranded one.
+ # Most recent event that put the task into ready; with none (old task /
+ # truncated events) fall back to created_at — over-flagging an ancient
+ # task beats missing a stranded one.
+ last_ready_ts = _latest_event_ts(events, {"created", "promoted", "reclaimed", "unblocked"})
if last_ready_ts == 0:
last_ready_ts = int(_task_field(task, "created_at", default=0) or 0)
if last_ready_ts == 0:
@@ -838,12 +702,7 @@ def _rule_stranded_in_ready(task, events, runs, now, cfg) -> list[Diagnostic]:
if age_seconds < threshold_seconds:
return []
- # Format the age in the largest sensible unit.
- if age_seconds >= 3600:
- age_str = f"{age_seconds / 3600:.1f}h"
- else:
- age_str = f"{int(age_seconds / 60)}m"
-
+ age_str = f"{age_seconds / 3600:.1f}h" if age_seconds >= 3600 else f"{int(age_seconds / 60)}m"
# Escalate with age: <2x threshold warning, 2x-6x error, >6x critical.
if age_seconds >= threshold_seconds * 6:
severity = "critical"
@@ -858,13 +717,8 @@ def _rule_stranded_in_ready(task, events, runs, now, cfg) -> list[Diagnostic]:
label="Reassign to a different worker",
payload={"current_assignee": assignee},
),
- DiagnosticAction(
- kind="cli_hint",
- label="Check dispatcher status",
- payload={"command": "hermes kanban diagnostics"},
- ),
+ _cli_hint("Check dispatcher status", "hermes kanban diagnostics"),
]
-
return [Diagnostic(
kind="stranded_in_ready",
severity=severity,
@@ -917,20 +771,18 @@ DEFAULT_CONFIG = {
}
+def _has_explicit_threshold(cfg: dict) -> bool:
+ return "failure_threshold" in cfg or "spawn_failure_threshold" in cfg
+
+
def config_from_kanban_config(kanban_cfg: Optional[dict]) -> dict:
"""Diagnostics config from the ``kanban`` section. ``kanban.diagnostics.
failure_threshold`` is an explicit override; otherwise the threshold is
``kanban.failure_limit`` so diagnostics match the dispatcher's breaker."""
kanban_cfg = kanban_cfg or {}
diag_cfg = dict(kanban_cfg.get("diagnostics") or {})
- diag_cfg.setdefault(
- "failure_limit",
- kanban_cfg.get("failure_limit", DEFAULT_CONFIG["failure_threshold"]),
- )
- if (
- "failure_threshold" not in diag_cfg
- and "spawn_failure_threshold" not in diag_cfg
- ):
+ diag_cfg.setdefault("failure_limit", kanban_cfg.get("failure_limit", DEFAULT_CONFIG["failure_threshold"]))
+ if not _has_explicit_threshold(diag_cfg):
diag_cfg["failure_threshold"] = diag_cfg["failure_limit"]
return diag_cfg
@@ -970,15 +822,8 @@ def compute_task_diagnostics(
cfg = {**DEFAULT_CONFIG, **config}
if graph is not None:
cfg["_graph"] = graph
- if (
- "failure_threshold" not in config
- and "spawn_failure_threshold" not in config
- and "failure_limit" in config
- ):
- cfg["failure_threshold"] = _positive_int(
- config.get("failure_limit"),
- DEFAULT_CONFIG["failure_threshold"],
- )
+ if not _has_explicit_threshold(config) and "failure_limit" in config:
+ cfg["failure_threshold"] = _positive_int(config.get("failure_limit"), DEFAULT_CONFIG["failure_threshold"])
out: list[Diagnostic] = []
for rule in _RULES:
try:
@@ -987,10 +832,5 @@ def compute_task_diagnostics(
# A broken rule must never 500 a whole /board request.
continue
severity_idx = {s: i for i, s in enumerate(SEVERITY_ORDER)}
- out.sort(
- key=lambda d: (
- -severity_idx.get(d.severity, -1),
- -(d.last_seen_at or 0),
- )
- )
+ out.sort(key=lambda d: (-severity_idx.get(d.severity, -1), -(d.last_seen_at or 0)))
return out