The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(serve): the idle probe names the ledger that holds work
kshitijk4poor03132b18debe
diff --git a/hermes_cli/web_server_idle_exit.py b/hermes_cli/web_server_idle_exit.pyindex 459398bc992..0e2711575e4 100644--- a/hermes_cli/web_server_idle_exit.py+++ b/hermes_cli/web_server_idle_exit.py@@ -101,28 +101,34 @@ def _session_work_in_flight(session: dict) -> bool:if (thread := session.get(key)) is not None)-def turn_in_flight() -> Optional[bool]:- """True/False from the gateway's running-session table OR the in-process cron scheduler; None- when neither can be read. The session table lives on ``tui_gateway.server`` (the voice mixin's- helper is bound into that namespace). Cron runs live outside that table- (``cron.scheduler.get_running_job_ids``, the same ledger the gateway shutdown drain reads):- without it a daily job mid-run reported "no turn" and the exit killed it (#107485). None keeps- the backend alive forever, so the cause is logged once — a silent never-exits would be the- original bug with a new face."""+def busy_ledger() -> Optional[str]:+ """Name the ledger that holds work — ``"retirement_admission"``, ``"session:<id>"``,+ ``"delegation"``, ``"cron:<job ids>"`` — ``""`` when every ledger is empty, ``None`` when one+ cannot be read. The Desktop's idle probe reports this so a backend that will not retire says+ WHICH work it is protecting, instead of an opaque "turn in flight".++ Session work lives on ``tui_gateway.server`` (the voice mixin's helper is bound into that+ namespace). Cron runs live outside that table (``cron.scheduler.get_running_job_ids``, the same+ ledger the gateway shutdown drain reads): without it a daily job mid-run reported "no turn" and+ the exit killed it (#107485). None keeps the backend alive forever, so the cause is logged once —+ a silent never-exits would be the original bug with a new face."""global _probe_failure_loggedtry:import tui_gateway.server as gatewayfrom hermes_cli.backend_retirement import retirementif retirement.active_count():- return True+ return "retirement_admission"with gateway._sessions_lock:- running = any(_session_work_in_flight(s) for s in gateway._sessions.values())- if running:- return True+ busy_sessions = [sid for sid, s in gateway._sessions.items() if _session_work_in_flight(s)]+ if busy_sessions:+ return "session:" + ",".join(str(sid) for sid in busy_sessions)from tools.async_delegation import active_countfrom cron.scheduler import get_running_job_ids- return bool(active_count() or get_running_job_ids())+ if active_count():+ return "delegation"+ running_jobs = get_running_job_ids()+ return "cron:" + ",".join(sorted(running_jobs)) if running_jobs else ""except Exception:if not _probe_failure_logged:_probe_failure_logged = True@@ -130,6 +136,12 @@ def turn_in_flight() -> Optional[bool]:return None+def turn_in_flight() -> Optional[bool]:+ """True/False from :func:`busy_ledger`; None when it cannot be read."""+ ledger = busy_ledger()+ return None if ledger is None else bool(ledger)++def should_exit_idle(tracker: IdleClientTracker, grace_s: float,probe: Callable[[], Optional[bool]] = turn_in_flight) -> bool:"""Exit only when no client has been connected for ``grace_s`` AND no turn is provably running.diff --git a/hermes_cli/web_server_idle_proof.py b/hermes_cli/web_server_idle_proof.pyindex 879ad3bd255..a109c01996b 100644--- a/hermes_cli/web_server_idle_proof.py+++ b/hermes_cli/web_server_idle_proof.py@@ -12,7 +12,7 @@ from __future__ import annotationsimport loggingfrom typing import Callable, Optional-from hermes_cli.web_server_idle_exit import turn_in_flight+from hermes_cli.web_server_idle_exit import busy_ledger_log = logging.getLogger(__name__)@@ -36,19 +36,20 @@ def pending_human_input() -> Optional[int]:return None-def idle_proof(turn_probe: Callable[[], Optional[bool]] = turn_in_flight,+def idle_proof(turn_probe: Callable[[], Optional[bool | str]] = busy_ledger,input_probe: Callable[[], Optional[int]] = pending_human_input) -> dict:- """``{"idle": True | False | None, "reason": str | None}``.+ """``{"idle": True | False | None, "reason": str | None}`` plus ``"detail"`` naming the busy ledger.``True`` only when no turn is in flight (session table AND cron ledger) and nothing is waitingon a human. ``None`` whenever either probe is indeterminate — the caller treats it exactly like- busy.+ busy. ``turn_probe`` may answer with a bool or with :func:`busy_ledger`'s name; the name is+ surfaced as ``detail`` so a backend that refuses to retire says which work it is protecting."""turn = turn_probe()if turn is None:return {"idle": None, "reason": "turn_probe_unavailable"}if turn:- return {"idle": False, "reason": "turn_in_flight"}+ return {"idle": False, "reason": "turn_in_flight", "detail": turn if isinstance(turn, str) else None}pending = input_probe()if pending is None:return {"idle": None, "reason": "input_probe_unavailable"}diff --git a/tests/hermes_cli/test_web_server_idle_proof.py b/tests/hermes_cli/test_web_server_idle_proof.pyindex 71ae2915268..30c6aa1e21f 100644--- a/tests/hermes_cli/test_web_server_idle_proof.py+++ b/tests/hermes_cli/test_web_server_idle_proof.py@@ -26,7 +26,9 @@ REPO_ROOT = Path(__file__).resolve().parents[2]def test_idle_proof_is_true_only_when_every_ledger_is_provably_empty():assert idle_proof(turn_probe=lambda: False, input_probe=lambda: 0) == {"idle": True, "reason": None}- assert idle_proof(turn_probe=lambda: True, input_probe=lambda: 0)["idle"] is False+ assert idle_proof(turn_probe=lambda: True, input_probe=lambda: 0) == {+ "idle": False, "reason": "turn_in_flight", "detail": None}+ assert idle_proof(turn_probe=lambda: "session:abc", input_probe=lambda: 0)["detail"] == "session:abc"assert idle_proof(turn_probe=lambda: False, input_probe=lambda: 1) == {"idle": False, "reason": "awaiting_human_input"}# Fail closed: an indeterminate probe is never reported as idle.@@ -46,7 +48,8 @@ def test_idle_proof_reads_the_real_cron_and_human_input_ledgers():with scheduler._running_lock:scheduler._running_job_ids.add("idle-proof-live-job")try:- assert idle_proof() == {"idle": False, "reason": "turn_in_flight"}+ # The busy verdict names the ledger and the job, so a backend that will not retire is diagnosable.+ assert idle_proof() == {"idle": False, "reason": "turn_in_flight", "detail": "cron:idle-proof-live-job"}finally:with scheduler._running_lock:scheduler._running_job_ids.discard("idle-proof-live-job")@@ -186,7 +189,8 @@ def test_live_pooled_children_prove_idle_or_busy_over_the_desktop_probe(tmp_pathverdicts = {name: _probe(port) for name, port in ports.items()}assert verdicts["resident-a"] == (200, {"ok": True, "idle": True, "reason": None}), verdictsassert verdicts["resident-b"] == (200, {"ok": True, "idle": True, "reason": None}), verdicts- assert verdicts["cron-busy"] == (200, {"ok": True, "idle": False, "reason": "turn_in_flight"}), verdicts+ assert verdicts["cron-busy"] == (200, {+ "ok": True, "idle": False, "reason": "turn_in_flight", "detail": "cron:live-idle-proof-job"}), verdictsstatus, body = _probe(ports["resident-a"], token=None)assert status == 401 and "idle" not in body