Skip to content

The agent that grows with you

fix(kanban): share terminal outcome policy with managed workers

David Dudok de Witfffab1631b29
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index 431fbe189db..dfd9f29cbf2 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -204,12 +204,12 @@ def run_worker_turns(agent, frame, history):
author = frame.get('turn_author')
return agent.run_conversation(frame['text'], conversation_history=history,
**({'turn_author': author} if author is not None else {}))
- from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
+ from hermes_cli.turn_exit import turn_exit_code
code, last_output = 1, ''
try:
result = _run_task_turns(agent, frame, history, context)
- code = KANBAN_RATE_LIMIT_EXIT_CODE if result.get('failed') and result.get('failure_reason') in {'rate_limit', 'billing'} else int(bool(result.get('failed') or result.get('interrupted')))
- last_output = str(result.get('final_response') or '')[-500:]
+ code = turn_exit_code(result, kanban_worker=True)
+ last_output = str(result.get('final_response') or '')[-500:] if isinstance(result, dict) else ''
return result
finally:
_TURNS_DONE.set()
diff --git a/hermes_cli/cli_single_query.py b/hermes_cli/cli_single_query.py
index ff10812b524..246ae3301fd 100644
--- a/hermes_cli/cli_single_query.py
+++ b/hermes_cli/cli_single_query.py
@@ -125,9 +125,7 @@ def _sync_cli_session_id_from_agent(cli) -> None:
# ``failure_reason`` values that say nothing about the task itself: the provider is walled,
# down or unreachable, or the account is out of credit, so a Kanban worker signals "try
# later" instead of "I failed" and the dispatcher does not spend the task's retry budget on it.
-_TRANSIENT_PROVIDER_REASONS = frozenset({
- "rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout",
-})
+from hermes_cli.turn_exit import TRANSIENT_PROVIDER_REASONS as _TRANSIENT_PROVIDER_REASONS
# ``failure_reason`` values a retry can never heal: the credential was rejected, the model does
@@ -137,9 +135,7 @@ _TRANSIENT_PROVIDER_REASONS = frozenset({
# ``kanban.failure_limit`` is spent. ``billing`` stays transient: credit comes back.
# ``upstream_blocked`` (a WAF/CDN refusing the SDK's User-Agent) is terminal too: only a
# header change heals it, never a retry.
-_TERMINAL_PROVIDER_REASONS = frozenset({
- "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",
-})
+from hermes_cli.turn_exit import TERMINAL_PROVIDER_REASONS as _TERMINAL_PROVIDER_REASONS
def _single_query_exit_code(result, *, credentials_rate_limited: bool = False) -> int:
@@ -157,24 +153,13 @@ def _single_query_exit_code(result, *, credentials_rate_limited: bool = False) -
(EX_CONFIG): the dispatcher blocks the card at once.
"""
from cli import _TERMINAL_PROVIDER_REASONS, _TRANSIENT_PROVIDER_REASONS
- if not isinstance(result, dict):
- if credentials_rate_limited and os.environ.get("HERMES_KANBAN_TASK"):
- from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
- return KANBAN_RATE_LIMIT_EXIT_CODE
- return 1
- if result.get("interrupted"):
- return 130
- if not (result.get("failed") or result.get("partial") or result.get("completed") is False):
- return 0
- if os.environ.get("HERMES_KANBAN_TASK"):
- reason = result.get("failure_reason")
- if reason in _TRANSIENT_PROVIDER_REASONS:
- from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
- return KANBAN_RATE_LIMIT_EXIT_CODE
- if reason in _TERMINAL_PROVIDER_REASONS:
- from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
- return 1
+ from hermes_cli.turn_exit import turn_exit_code
+ return turn_exit_code(
+ result, kanban_worker=bool(os.environ.get("HERMES_KANBAN_TASK")),
+ credentials_rate_limited=credentials_rate_limited,
+ transient_reasons=_TRANSIENT_PROVIDER_REASONS,
+ terminal_reasons=_TERMINAL_PROVIDER_REASONS,
+ )
def _run_quiet_single_query(cli, effective_query, emitter=None):
diff --git a/hermes_cli/turn_exit.py b/hermes_cli/turn_exit.py
new file mode 100644
index 00000000000..56fdb40efe4
--- /dev/null
+++ b/hermes_cli/turn_exit.py
@@ -0,0 +1,38 @@
+"""Turn-result exit policy shared by CLI views and authority-owned workers.
+
+Worker identity is supplied by the caller, not inferred from a daemon's environment.
+"""
+
+# Provider walls do not spend a Kanban task's retry budget.
+TRANSIENT_PROVIDER_REASONS = frozenset({
+ "rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout",
+})
+# These failures need an operator change; the dispatcher parks the task immediately.
+TERMINAL_PROVIDER_REASONS = frozenset({
+ "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",
+})
+
+
+def turn_exit_code(
+ result, *, kanban_worker: bool, credentials_rate_limited: bool = False,
+ transient_reasons=TRANSIENT_PROVIDER_REASONS, terminal_reasons=TERMINAL_PROVIDER_REASONS,
+) -> int:
+ """Preserve completion, interruption and retryable/terminal provider outcomes."""
+ if not isinstance(result, dict):
+ if credentials_rate_limited and kanban_worker:
+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
+ return KANBAN_RATE_LIMIT_EXIT_CODE
+ return 1
+ if result.get("interrupted"):
+ return 130
+ if not (result.get("failed") or result.get("partial") or result.get("completed") is False):
+ return 0
+ if kanban_worker:
+ reason = result.get("failure_reason")
+ if reason in transient_reasons:
+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE
+ return KANBAN_RATE_LIMIT_EXIT_CODE
+ if reason in terminal_reasons:
+ from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
+ return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
+ return 1
diff --git a/tests/gateway/test_kanban_result_exit.py b/tests/gateway/test_kanban_result_exit.py
new file mode 100644
index 00000000000..bb5f8df59d6
--- /dev/null
+++ b/tests/gateway/test_kanban_result_exit.py
@@ -0,0 +1,48 @@
+"""Canonical Kanban receipts retain the shared one-shot outcome semantics."""
+import json
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import session_kanban
+from hermes_cli import kanban_db as kb
+from hermes_cli.kanban_db_connect import connect_closing
+
+
+ "result, expected",
+ [
+ ({"completed": True}, 0),
+ ({"failed": True}, 1),
+ ({"partial": True}, 1),
+ ({"completed": False}, 1),
+ ({"interrupted": True}, 130),
+ (None, 1),
+ *[({"failed": True, "failure_reason": reason}, kb.KANBAN_RATE_LIMIT_EXIT_CODE)
+ for reason in ("rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout")],
+ *[({"failed": True, "failure_reason": reason}, kb.KANBAN_TERMINAL_PROVIDER_EXIT_CODE)
+ for reason in ("auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked")],
+ ],
+)
+def test_managed_result_persists_exact_worker_exit(tmp_path, monkeypatch, result, expected):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)
+ kb.init_db()
+ path = kb.kanban_db_path()
+ with connect_closing(path) as conn:
+ task_id = kb.create_task(conn, title="private fixture", assignee="default")
+ task = kb.claim_task(conn, task_id, claimer="private-host:owner")
+ assert task is not None
+ context = {"db": str(path), "task_id": task_id,
+ "run_id": task.current_run_id, "claim_lock": task.claim_lock}
+ with kb.write_txn(conn):
+ kb._append_event(conn, task_id, "worker_bound",
+ {"pid": os.getpid(), "claim_lock": task.claim_lock},
+ run_id=task.current_run_id)
+ monkeypatch.setattr(session_kanban, "_run_task_turns", lambda *_args: result)
+ frame = {"policy": {"kanban_json": json.dumps(context)}}
+
+ assert session_kanban.run_worker_turns(SimpleNamespace(), frame, []) is result
+ assert session_kanban.worker_exit_code(path, context) == expected
+ assert session_kanban.worker_exit_code(path, context | {"claim_lock": "foreign"}) == 1
diff --git a/tests/hermes_cli/test_kanban_managed_exit_reconciliation.py b/tests/hermes_cli/test_kanban_managed_exit_reconciliation.py
new file mode 100644
index 00000000000..d1d18d05f78
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_managed_exit_reconciliation.py
@@ -0,0 +1,41 @@
+"""Join authority-owned worker receipts with main's exit classification."""
+import pytest
+
+from hermes_cli import kanban_db as kb
+from hermes_cli import kanban_db_dispatch as dispatch
+
+
+ "receipt, reaped, logged, event, rate_limited, terminal_provider",
+ [
+ (0, ("unknown", None), None, "protocol_violation", False, False),
+ (kb.KANBAN_RATE_LIMIT_EXIT_CODE, ("nonzero_exit", 1), None,
+ "rate_limited", True, False),
+ (kb.KANBAN_TERMINAL_PROVIDER_EXIT_CODE, ("unknown", None), None,
+ "crashed", False, True),
+ (3, ("unknown", None), None, "crashed", False, False),
+ (None, ("nonzero_exit", 3), None, "crashed", False, False),
+ (None, ("unknown", None), kb.KANBAN_RATE_LIMIT_EXIT_CODE,
+ "rate_limited", True, False),
+ ],
+)
+def test_dead_worker_classification_accepts_managed_and_legacy_results(
+ monkeypatch, receipt, reaped, logged, event, rate_limited, terminal_provider,
+):
+ monkeypatch.setattr(dispatch, "_classify_worker_exit", lambda _pid: reaped)
+ monkeypatch.setattr(dispatch, "_worker_log_exit_code", lambda *_a, **_k: logged)
+ monkeypatch.setattr(dispatch, "_worker_final_output", lambda *_a, **_k: "worker detail")
+
+ result = dispatch._classify_dead_worker(
+ 900001, "private-host:owner", receipt, task_id="private-task", board="private-board",
+ )
+
+ assert result.event_kind == event
+ assert result.rate_limited is rate_limited
+ assert result.terminal_provider is terminal_provider
+ expected_code = receipt if receipt is not None else reaped[1] if reaped[1] is not None else logged
+ assert result.event_payload["exit_code"] == expected_code
+ if rate_limited:
+ assert "worker_output" not in result.event_payload
+ else:
+ assert result.event_payload["worker_output"] == "worker detail"