The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): book a dead worker the same way whichever process notices it
teknium1edd4ec312434
diff --git a/cli.py b/cli.pyindex 21144c3f487..ffc124df4bc 100644--- a/cli.py+++ b/cli.py@@ -4153,7 +4153,7 @@ def _run_quiet_single_query(cli, effective_query, emitter=None):from agent.turn_author import take_turn_author_from_envfrom hermes_cli.quiet_single_query import (adopt_unanswered_turn, bind_quiet_session_key, continue_quiet_notify_completions,- quiet_notify_linger_seconds, take_turn_report_path, write_turn_report,+ exit_single_query, quiet_notify_linger_seconds, take_turn_report_path, write_turn_report,)author = take_turn_author_from_env()@@ -4171,9 +4171,9 @@ def _run_quiet_single_query(cli, effective_query, emitter=None):except KeyboardInterrupt:_emit_interrupted_session_end(cli, reason="keyboard_interrupt")if emitter is not None:- sys.exit(emitter.emit_result({"failed": True, "error": "Interrupted"}, session_id=cli.session_id or "", exit_code=130))+ exit_single_query(emitter.emit_result({"failed": True, "error": "Interrupted"}, session_id=cli.session_id or "", exit_code=130))print(f"\nsession_id: {cli.session_id}", file=sys.stderr)- sys.exit(130)+ exit_single_query(130)# The exit line below reports session_id to stderr for automation wrappers;# without this sync it would point at the ended parent after compression._sync_cli_session_id_from_agent(cli)@@ -4242,7 +4242,7 @@ def _run_quiet_single_query(cli, effective_query, emitter=None):_exit_code = _single_query_exit_code(result)if emitter is not None:_exit_code = emitter.emit_result(result, session_id=cli.session_id or "", exit_code=_exit_code)- sys.exit(_exit_code)+ exit_single_query(_exit_code)def _route_single_query_images(cli, query, effective_query, single_query_images, single_query_image_urls):@@ -4541,8 +4541,9 @@ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: bool# isn't engaged) and takes the deterministic approvals.single_query_mode path instead of waiting the# full timeout. See #86878.os.environ["HERMES_SINGLE_QUERY_SESSION"] = "1"+ from hermes_cli.quiet_single_query import exit_single_queryif not cli._claim_active_session("cli", stderr=bool(quiet)):- sys.exit(1)+ exit_single_query(1)try:query, single_query_images = _collect_query_images(query, image)single_query_image_urls = _collect_kanban_task_images(single_query_images)@@ -4575,7 +4576,7 @@ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: boolif emitter is not None:emitter.emit_result({"failed": True, "error": "credentials or agent init failed"},session_id=cli.session_id or "", exit_code=1)- sys.exit(1) # credentials or agent init failed+ exit_single_query(1) # credentials or agent init failed# No welcome banner (~420 ms cold); session id / resume hint come from _print_exit_summary()._query_label = query or ("[image attached]" if single_query_images else "")if _query_label:@@ -4593,7 +4594,7 @@ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: boolcli._print_exit_summary(clear_screen=False)# Same exit contract as `-Q`: scripts and the Kanban dispatcher read the outcome from# the exit code. This path used to fall through to an implicit 0 for every outcome.- sys.exit(_single_query_exit_code(cli._last_turn_result))+ exit_single_query(_single_query_exit_code(cli._last_turn_result))finally:_finalize_single_query(cli)diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 419d653d146..3c195ff61ee 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -25,6 +25,8 @@ from typing import Mappingfrom typing import Optionalfrom typing import TYPE_CHECKING+from hermes_cli.quiet_single_query import KANBAN_WORKER_EXIT_TRAILER+if TYPE_CHECKING:from hermes_cli.kanban_db import Task@@ -179,7 +181,10 @@ def describe_suppression(results: Iterable[Optional["DispatchResult"]]) -> str:# ``dispatch_once`` and read by ``detect_crashed_workers`` to classify a dead-pid# task. Entry: ``pid -> (raw_wait_status, reaped_at_epoch)``; raw status kept so# both WIFEXITED/WEXITSTATUS and WIFSIGNALED can be consulted. Trimmed by age-# plus a total size cap.+# plus a total size cap. Process-local by nature (``waitpid`` only reaps our own+# children): a per-tick ``hermes kanban dispatch`` process finds it empty, so+# ``_classify_dead_worker_exit`` falls back to the exit trailer the worker+# leaves in its own log (``KANBAN_WORKER_EXIT_TRAILER``)._RECENT_WORKER_EXIT_TTL_SECONDS = 600_RECENT_WORKER_EXITS_MAX = 4096_recent_worker_exits: "dict[int, tuple[int, float]]" = {}@@ -229,17 +234,42 @@ def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":raw = int(raw)signal_number = raw & 0x7Fif signal_number == 0:- code = (raw >> 8) & 0xFF- if code == 0:- return ("clean_exit", 0)- if code == _kb.KANBAN_RATE_LIMIT_EXIT_CODE:- return ("rate_limited", code)- return ("nonzero_exit", code)+ return _exit_code_kind((raw >> 8) & 0xFF)if signal_number != 0x7F:return ("signaled", signal_number)return ("unknown", None)+def _exit_code_kind(code: int) -> "tuple[str, int]":+ """``(kind, code)`` for a worker's exit code, however it was observed."""+ if code == 0:+ return ("clean_exit", 0)+ if code == _kb.KANBAN_RATE_LIMIT_EXIT_CODE:+ return ("rate_limited", code)+ return ("nonzero_exit", code)+++_EXIT_TRAILER_RE = re.compile(+ r"^" + re.escape(KANBAN_WORKER_EXIT_TRAILER) + r"(\d+)\s*$", re.MULTILINE,+)+++def _worker_log_exit_code(task_id: str, board: Optional[str] = None) -> Optional[int]:+ """Exit code from the trailer the worker CLI wrote to its own log; None when absent.++ The durable twin of ``_recent_worker_exits``: written by the worker itself+ (``hermes_cli.quiet_single_query.exit_single_query``), so it is there whether+ or not the process running this sweep ever reaped the worker. Last trailer+ wins — the log is append-mode across re-runs.+ """+ try:+ raw = _kb.read_worker_log(task_id, tail_bytes=4000, board=board)+ except Exception:+ return None+ matches = _EXIT_TRAILER_RE.findall(raw or "")+ return int(matches[-1]) if matches else None++def reap_worker_zombies() -> "list[int]":"""Reap exited workers without blocking; returns reaped PIDs. POSIX reapsevery child via ``waitpid(-1)``; Windows polls the ``Popen`` handles@@ -963,6 +993,7 @@ def _worker_final_output(task_id: str, board: Optional[str] = None) -> str:return ""if not raw:return ""+ raw = _EXIT_TRAILER_RE.sub("", raw)cut = raw.rfind(_EXIT_SUMMARY_MARKER)if cut != -1:raw = raw[:cut]@@ -1002,7 +1033,7 @@ def _classify_dead_worker(in the event payload, appended to the error text) so the board and the retryworker see WHY instead of a bare label; a rate-limited requeue does not need it."""- dead = _classify_dead_worker_exit(pid, claimer)+ dead = _classify_dead_worker_exit(pid, claimer, task_id=task_id, board=board)if task_id and not dead.rate_limited:worker_output = _worker_final_output(task_id, board=board)if worker_output:@@ -1011,9 +1042,26 @@ def _classify_dead_worker(return dead-def _classify_dead_worker_exit(pid: int, claimer: Optional[str]) -> _DeadWorker:- """Exit status -> reclaim bookkeeping, before the worker's own words are folded in."""+def _classify_dead_worker_exit(+ pid: int,+ claimer: Optional[str],+ *,+ task_id: Optional[str] = None,+ board: Optional[str] = None,+) -> _DeadWorker:+ """Exit status -> reclaim bookkeeping, before the worker's own words are folded in.++ The reap registry only knows children of THIS process; a per-tick dispatcher+ reads the exit trailer the worker left in its log instead, so the same death+ gets the same booking (protocol violation / rate-limit requeue / crash) as+ under the gateway-embedded dispatcher. A worker that never reached its exit+ epilogue (killed, OOM) leaves no trailer and stays a plain crash.+ """kind, code = _classify_worker_exit(pid)+ if kind == "unknown" and task_id:+ logged = _worker_log_exit_code(task_id, board=board)+ if logged is not None:+ kind, code = _exit_code_kind(logged)if kind == "clean_exit":# rc=0 while still ``running``: usually the work succeeded and only the# paperwork was skipped; the corrective sentence reaches the retrydiff --git a/hermes_cli/quiet_single_query.py b/hermes_cli/quiet_single_query.pyindex 751ee28a4be..8088a1d7d34 100644--- a/hermes_cli/quiet_single_query.py+++ b/hermes_cli/quiet_single_query.py@@ -13,12 +13,31 @@ from __future__ import annotationsimport contextlibimport jsonimport os+import sysimport timefrom typing import Any, Callable, MutableMapping# Nested A→B→C is one extra turn; this caps a runaway message_agent chain._MAX_QUIET_NOTIFY_ROUNDS = 8+# Last line a Kanban worker leaves in its own log: ``[kanban-worker-exit] rc=<code>``. A per-tick+# ``hermes kanban dispatch`` process never reaped the worker, so ``os.waitpid`` cannot tell it how+# the worker exited; the trailer is the process-independent witness the dead-worker sweep reads+# instead, so a clean exit without a terminal board call is booked as the same protocol violation+# (and a 75 as the same rate-limit requeue) whichever process notices the death.+KANBAN_WORKER_EXIT_TRAILER = "[kanban-worker-exit] rc="+++def exit_single_query(code: int) -> None:+ """``sys.exit(code)`` for a one-shot turn; a Kanban worker first writes the exit trailer to its log."""+ if os.environ.get("HERMES_KANBAN_TASK"):+ with contextlib.suppress(Exception):+ # stderr: stdout may be the ``--stream-json`` record stream, and the worker log+ # captures both streams.+ print(f"\n{KANBAN_WORKER_EXIT_TRAILER}{int(code)}", file=sys.stderr, flush=True)+ sys.exit(code)++# A spawner that bounds only the TURN (the cron Bot Chat lane) hands the quiet child a report# path here. The child records the turn's outcome there the moment the turn ends, BEFORE the# one-shot exit linger, so the spawner can book the delivery and stop waiting while the lingerdiff --git a/tests/hermes_cli/test_kanban_worker_exit_trailer.py b/tests/hermes_cli/test_kanban_worker_exit_trailer.pynew file mode 100644index 00000000000..8162bf64c90--- /dev/null+++ b/tests/hermes_cli/test_kanban_worker_exit_trailer.py@@ -0,0 +1,114 @@+"""A dead Kanban worker is booked the same way whichever process notices it.++``_recent_worker_exits`` is filled by ``os.waitpid`` and so only knows children of+the process running the sweep; a per-tick ``hermes kanban dispatch`` process finds it+empty. The worker's own exit trailer in its log is the durable witness the sweep reads+instead, and a tripped protocol-violation budget must hold the card until an operator+unblocks it.+"""++from __future__ import annotations++import time+from pathlib import Path++import pytest++from hermes_cli import kanban_db as kb+from hermes_cli import kanban_db_connect as kbc+from hermes_cli import kanban_db_dispatch as kbd+from hermes_cli.quiet_single_query import KANBAN_WORKER_EXIT_TRAILER, exit_single_query+++def kanban_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_KANBAN_CRASH_GRACE_SECONDS", "0")+ monkeypatch.setattr(kb, "_pid_alive", lambda _pid: False)+ kbd._recent_worker_exits.clear()+ kb.init_db()+ return home+++def _dead_worker_with_log(conn, tid: str, pid: int, rc: int) -> None:+ """Claim ``tid`` for a worker that already exited ``rc`` and wrote its log — never reaped here."""+ host = kb._claimer_id().split(":", 1)[0]+ kb.claim_task(conn, tid, claimer=f"{host}:w{pid}")+ conn.execute(+ "UPDATE tasks SET worker_pid=?, worker_started_at=NULL, started_at=? WHERE id=?",+ (pid, int(time.time()) - 120, tid),+ )+ conn.commit()+ log = kb.worker_log_path(tid)+ log.parent.mkdir(parents=True, exist_ok=True)+ with open(log, "a", encoding="utf-8") as f:+ f.write(f"the model said something\n\nResume this session with:\n hermes --resume x\n\n{KANBAN_WORKER_EXIT_TRAILER}{rc}\n")+++ "rc, event, failure_counted",+ [(0, "protocol_violation", False), (kb.KANBAN_RATE_LIMIT_EXIT_CODE, "rate_limited", False)],+)+def test_fresh_process_sweep_books_the_logged_exit_code(kanban_home, rc, event, failure_counted):+ """Empty reap registry + exit trailer in the log: a clean exit is the protocol violation+ (marker, streak, no unified-budget hit) and a 75 is a rate-limit requeue — not a bare+ ``pid N not alive`` crash that counts a failure."""+ with kbc.connect() as conn:+ tid = kb.create_task(conn, title="t", assignee="a")+ _dead_worker_with_log(conn, tid, 70001, rc)++ kbd.detect_crashed_workers(conn)++ ev = conn.execute(+ "SELECT kind FROM task_events WHERE task_id=? ORDER BY id DESC LIMIT 1", (tid,)).fetchone()+ run = conn.execute(+ "SELECT outcome, error, metadata FROM task_runs WHERE task_id=? ORDER BY id DESC LIMIT 1",+ (tid,)).fetchone()+ task = kb.get_task(conn, tid)+ assert ev["kind"] == event+ assert "not alive" not in (run["error"] or "")+ assert task.status == "ready"+ assert task.consecutive_failures == (1 if failure_counted else 0)+ if rc == 0:+ assert kb._json_dict(run["metadata"]).get("protocol_violation") is True+ assert kbd._protocol_violation_streak(conn, tid) == 1+ assert KANBAN_WORKER_EXIT_TRAILER not in (run["error"] or "")+ else:+ assert run["outcome"] == "rate_limited"+++def test_violation_budget_trip_holds_until_operator_unblock(kanban_home):+ """The third consecutive clean exit trips the violation budget and ``recompute_ready``+ must not promote the card back the same tick (``consecutive_failures`` is still below+ ``failure_limit``); ``unblock_task`` lifts the hold."""+ with kbc.connect() as conn:+ tid = kb.create_task(conn, title="loop", assignee="a")+ for i in range(kbd._PROTOCOL_VIOLATION_FAILURE_LIMIT):+ _dead_worker_with_log(conn, tid, 71000 + i, 0)+ kbd.detect_crashed_workers(conn)+ kb.recompute_ready(conn, failure_limit=10)+ task = kb.get_task(conn, tid)+ assert task.status == "blocked"+ assert task.consecutive_failures < 10++ kb.unblock_task(conn, tid)+ assert kb.get_task(conn, tid).status == "ready"+ kb.recompute_ready(conn, failure_limit=10)+ assert kb.get_task(conn, tid).status == "ready"+++def test_exit_single_query_writes_trailer_only_for_kanban_workers(monkeypatch, capsys):+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)+ with pytest.raises(SystemExit) as exc:+ exit_single_query(1)+ assert exc.value.code == 1+ assert KANBAN_WORKER_EXIT_TRAILER not in capsys.readouterr().err++ monkeypatch.setenv("HERMES_KANBAN_TASK", "t_1")+ with pytest.raises(SystemExit) as exc:+ exit_single_query(kb.KANBAN_RATE_LIMIT_EXIT_CODE)+ assert exc.value.code == kb.KANBAN_RATE_LIMIT_EXIT_CODE+ assert f"{KANBAN_WORKER_EXIT_TRAILER}{kb.KANBAN_RATE_LIMIT_EXIT_CODE}" in capsys.readouterr().errdiff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 837799590ec..f164858d273 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -565,7 +565,12 @@ therefore exits non-zero: `1` for an ordinary failure, and `75`(`EX_TEMPFAIL`) when the provider was rate-limited, overloaded, returning5xx or timing out, or the account hit a billing/quota wall — the dispatcher records that run as `rate_limited` andrequeues the task without counting a failure, so a quota window is never-booked as a protocol violation.+booked as a protocol violation. The worker also writes its exit code as the+last line of its own log (`[kanban-worker-exit] rc=<code>`), so a per-tick+`hermes kanban dispatch` process — which never reaped the worker and cannot+read its exit status — books the same death the same way the gateway-embedded+dispatcher does; a worker killed before it reaches that line is a plain+`crashed` (`pid <n> not alive`).**Agent-side prevention:** Before the worker exits, Hermes injects up to twosynthetic nudges when it detects the model is about to stop without a terminal